babylon.max.js 4.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664
  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. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. BABYLON.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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  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. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  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 noIndexedDB = function (retryIndex) {
  6199. var oldRequest = request;
  6200. request = new XMLHttpRequest();
  6201. var loadUrl = Tools.BaseUrl + url;
  6202. request.open('GET', loadUrl, true);
  6203. if (useArrayBuffer) {
  6204. request.responseType = "arraybuffer";
  6205. }
  6206. if (progressCallBack) {
  6207. request.onprogress = progressCallBack;
  6208. }
  6209. request.onreadystatechange = function () {
  6210. var req = request;
  6211. // In case of undefined state in some browsers.
  6212. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6213. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6214. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6215. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6216. return;
  6217. }
  6218. retryStrategy = retryStrategy || Tools.DefaultRetryStrategy;
  6219. if (retryStrategy) {
  6220. var waitTime = retryStrategy(loadUrl, req, retryIndex || 0);
  6221. if (waitTime !== -1) {
  6222. setTimeout(function () { return noIndexedDB((retryIndex || 0) + 1); }, waitTime);
  6223. return;
  6224. }
  6225. }
  6226. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6227. if (onError) {
  6228. onError(req, e);
  6229. }
  6230. else {
  6231. throw e;
  6232. }
  6233. }
  6234. };
  6235. request.send();
  6236. if (oldRequest && onRetry) {
  6237. onRetry(oldRequest, request);
  6238. }
  6239. };
  6240. var loadFromIndexedDB = function () {
  6241. if (database) {
  6242. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6243. }
  6244. };
  6245. // If file and file input are set
  6246. if (url.indexOf("file:") !== -1) {
  6247. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6248. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6249. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6250. return request;
  6251. }
  6252. }
  6253. // Caching all files
  6254. if (database && database.enableSceneOffline) {
  6255. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6256. }
  6257. else {
  6258. noIndexedDB();
  6259. }
  6260. return request;
  6261. };
  6262. /**
  6263. * Load a script (identified by an url). When the url returns, the
  6264. * content of this file is added into a new script element, attached to the DOM (body element)
  6265. */
  6266. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6267. var head = document.getElementsByTagName('head')[0];
  6268. var script = document.createElement('script');
  6269. script.type = 'text/javascript';
  6270. script.src = scriptUrl;
  6271. script.onload = function () {
  6272. if (onSuccess) {
  6273. onSuccess();
  6274. }
  6275. };
  6276. script.onerror = function (e) {
  6277. if (onError) {
  6278. onError("Unable to load script", e);
  6279. }
  6280. };
  6281. head.appendChild(script);
  6282. };
  6283. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6284. var reader = new FileReader();
  6285. reader.onload = function (e) {
  6286. //target doesn't have result from ts 1.3
  6287. callback(e.target['result']);
  6288. };
  6289. reader.onprogress = progressCallback;
  6290. reader.readAsDataURL(fileToLoad);
  6291. };
  6292. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6293. var reader = new FileReader();
  6294. reader.onerror = function (e) {
  6295. Tools.Log("Error while reading file: " + fileToLoad.name);
  6296. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6297. };
  6298. reader.onload = function (e) {
  6299. //target doesn't have result from ts 1.3
  6300. callback(e.target['result']);
  6301. };
  6302. if (progressCallBack) {
  6303. reader.onprogress = progressCallBack;
  6304. }
  6305. if (!useArrayBuffer) {
  6306. // Asynchronous read
  6307. reader.readAsText(fileToLoad);
  6308. }
  6309. else {
  6310. reader.readAsArrayBuffer(fileToLoad);
  6311. }
  6312. };
  6313. //returns a downloadable url to a file content.
  6314. Tools.FileAsURL = function (content) {
  6315. var fileBlob = new Blob([content]);
  6316. var url = window.URL || window.webkitURL;
  6317. var link = url.createObjectURL(fileBlob);
  6318. return link;
  6319. };
  6320. // Misc.
  6321. Tools.Format = function (value, decimals) {
  6322. if (decimals === void 0) { decimals = 2; }
  6323. return value.toFixed(decimals);
  6324. };
  6325. Tools.CheckExtends = function (v, min, max) {
  6326. if (v.x < min.x)
  6327. min.x = v.x;
  6328. if (v.y < min.y)
  6329. min.y = v.y;
  6330. if (v.z < min.z)
  6331. min.z = v.z;
  6332. if (v.x > max.x)
  6333. max.x = v.x;
  6334. if (v.y > max.y)
  6335. max.y = v.y;
  6336. if (v.z > max.z)
  6337. max.z = v.z;
  6338. };
  6339. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6340. for (var prop in source) {
  6341. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6342. continue;
  6343. }
  6344. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6345. continue;
  6346. }
  6347. var sourceValue = source[prop];
  6348. var typeOfSourceValue = typeof sourceValue;
  6349. if (typeOfSourceValue === "function") {
  6350. continue;
  6351. }
  6352. if (typeOfSourceValue === "object") {
  6353. if (sourceValue instanceof Array) {
  6354. destination[prop] = [];
  6355. if (sourceValue.length > 0) {
  6356. if (typeof sourceValue[0] == "object") {
  6357. for (var index = 0; index < sourceValue.length; index++) {
  6358. var clonedValue = cloneValue(sourceValue[index], destination);
  6359. if (destination[prop].indexOf(clonedValue) === -1) {
  6360. destination[prop].push(clonedValue);
  6361. }
  6362. }
  6363. }
  6364. else {
  6365. destination[prop] = sourceValue.slice(0);
  6366. }
  6367. }
  6368. }
  6369. else {
  6370. destination[prop] = cloneValue(sourceValue, destination);
  6371. }
  6372. }
  6373. else {
  6374. destination[prop] = sourceValue;
  6375. }
  6376. }
  6377. };
  6378. Tools.IsEmpty = function (obj) {
  6379. for (var i in obj) {
  6380. if (obj.hasOwnProperty(i)) {
  6381. return false;
  6382. }
  6383. }
  6384. return true;
  6385. };
  6386. Tools.RegisterTopRootEvents = function (events) {
  6387. for (var index = 0; index < events.length; index++) {
  6388. var event = events[index];
  6389. window.addEventListener(event.name, event.handler, false);
  6390. try {
  6391. if (window.parent) {
  6392. window.parent.addEventListener(event.name, event.handler, false);
  6393. }
  6394. }
  6395. catch (e) {
  6396. // Silently fails...
  6397. }
  6398. }
  6399. };
  6400. Tools.UnregisterTopRootEvents = function (events) {
  6401. for (var index = 0; index < events.length; index++) {
  6402. var event = events[index];
  6403. window.removeEventListener(event.name, event.handler);
  6404. try {
  6405. if (window.parent) {
  6406. window.parent.removeEventListener(event.name, event.handler);
  6407. }
  6408. }
  6409. catch (e) {
  6410. // Silently fails...
  6411. }
  6412. }
  6413. };
  6414. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6415. if (mimeType === void 0) { mimeType = "image/png"; }
  6416. // Read the contents of the framebuffer
  6417. var numberOfChannelsByLine = width * 4;
  6418. var halfHeight = height / 2;
  6419. //Reading datas from WebGL
  6420. var data = engine.readPixels(0, 0, width, height);
  6421. //To flip image on Y axis.
  6422. for (var i = 0; i < halfHeight; i++) {
  6423. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6424. var currentCell = j + i * numberOfChannelsByLine;
  6425. var targetLine = height - i - 1;
  6426. var targetCell = j + targetLine * numberOfChannelsByLine;
  6427. var temp = data[currentCell];
  6428. data[currentCell] = data[targetCell];
  6429. data[targetCell] = temp;
  6430. }
  6431. }
  6432. // Create a 2D canvas to store the result
  6433. if (!screenshotCanvas) {
  6434. screenshotCanvas = document.createElement('canvas');
  6435. }
  6436. screenshotCanvas.width = width;
  6437. screenshotCanvas.height = height;
  6438. var context = screenshotCanvas.getContext('2d');
  6439. if (context) {
  6440. // Copy the pixels to a 2D canvas
  6441. var imageData = context.createImageData(width, height);
  6442. var castData = (imageData.data);
  6443. castData.set(data);
  6444. context.putImageData(imageData, 0, 0);
  6445. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6446. }
  6447. };
  6448. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6449. if (mimeType === void 0) { mimeType = "image/png"; }
  6450. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6451. if (successCallback) {
  6452. successCallback(base64Image);
  6453. }
  6454. else {
  6455. // We need HTMLCanvasElement.toBlob for HD screenshots
  6456. if (!screenshotCanvas.toBlob) {
  6457. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6458. screenshotCanvas.toBlob = function (callback, type, quality) {
  6459. var _this = this;
  6460. setTimeout(function () {
  6461. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6462. for (var i = 0; i < len; i++) {
  6463. arr[i] = binStr.charCodeAt(i);
  6464. }
  6465. callback(new Blob([arr], { type: type || 'image/png' }));
  6466. });
  6467. };
  6468. }
  6469. screenshotCanvas.toBlob(function (blob) {
  6470. var url = URL.createObjectURL(blob);
  6471. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6472. if (("download" in document.createElement("a"))) {
  6473. var a = window.document.createElement("a");
  6474. a.href = url;
  6475. if (fileName) {
  6476. a.setAttribute("download", fileName);
  6477. }
  6478. else {
  6479. var date = new Date();
  6480. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6481. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6482. }
  6483. window.document.body.appendChild(a);
  6484. a.addEventListener("click", function () {
  6485. if (a.parentElement) {
  6486. a.parentElement.removeChild(a);
  6487. }
  6488. });
  6489. a.click();
  6490. }
  6491. else {
  6492. var newWindow = window.open("");
  6493. if (!newWindow)
  6494. return;
  6495. var img = newWindow.document.createElement("img");
  6496. img.onload = function () {
  6497. // no longer need to read the blob so it's revoked
  6498. URL.revokeObjectURL(url);
  6499. };
  6500. img.src = url;
  6501. newWindow.document.body.appendChild(img);
  6502. }
  6503. });
  6504. }
  6505. };
  6506. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6507. if (mimeType === void 0) { mimeType = "image/png"; }
  6508. var width;
  6509. var height;
  6510. // If a precision value is specified
  6511. if (size.precision) {
  6512. width = Math.round(engine.getRenderWidth() * size.precision);
  6513. height = Math.round(width / engine.getAspectRatio(camera));
  6514. }
  6515. else if (size.width && size.height) {
  6516. width = size.width;
  6517. height = size.height;
  6518. }
  6519. else if (size.width && !size.height) {
  6520. width = size.width;
  6521. height = Math.round(width / engine.getAspectRatio(camera));
  6522. }
  6523. else if (size.height && !size.width) {
  6524. height = size.height;
  6525. width = Math.round(height * engine.getAspectRatio(camera));
  6526. }
  6527. else if (!isNaN(size)) {
  6528. height = size;
  6529. width = size;
  6530. }
  6531. else {
  6532. Tools.Error("Invalid 'size' parameter !");
  6533. return;
  6534. }
  6535. if (!screenshotCanvas) {
  6536. screenshotCanvas = document.createElement('canvas');
  6537. }
  6538. screenshotCanvas.width = width;
  6539. screenshotCanvas.height = height;
  6540. var renderContext = screenshotCanvas.getContext("2d");
  6541. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6542. var newWidth = width;
  6543. var newHeight = newWidth / ratio;
  6544. if (newHeight > height) {
  6545. newHeight = height;
  6546. newWidth = newHeight * ratio;
  6547. }
  6548. var offsetX = Math.max(0, width - newWidth) / 2;
  6549. var offsetY = Math.max(0, height - newHeight) / 2;
  6550. var renderingCanvas = engine.getRenderingCanvas();
  6551. if (renderContext && renderingCanvas) {
  6552. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6553. }
  6554. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6555. };
  6556. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6557. if (mimeType === void 0) { mimeType = "image/png"; }
  6558. if (samples === void 0) { samples = 1; }
  6559. if (antialiasing === void 0) { antialiasing = false; }
  6560. var width;
  6561. var height;
  6562. //If a precision value is specified
  6563. if (size.precision) {
  6564. width = Math.round(engine.getRenderWidth() * size.precision);
  6565. height = Math.round(width / engine.getAspectRatio(camera));
  6566. size = { width: width, height: height };
  6567. }
  6568. else if (size.width && size.height) {
  6569. width = size.width;
  6570. height = size.height;
  6571. }
  6572. else if (size.width && !size.height) {
  6573. width = size.width;
  6574. height = Math.round(width / engine.getAspectRatio(camera));
  6575. size = { width: width, height: height };
  6576. }
  6577. else if (size.height && !size.width) {
  6578. height = size.height;
  6579. width = Math.round(height * engine.getAspectRatio(camera));
  6580. size = { width: width, height: height };
  6581. }
  6582. else if (!isNaN(size)) {
  6583. height = size;
  6584. width = size;
  6585. }
  6586. else {
  6587. Tools.Error("Invalid 'size' parameter !");
  6588. return;
  6589. }
  6590. var scene = camera.getScene();
  6591. var previousCamera = null;
  6592. if (scene.activeCamera !== camera) {
  6593. previousCamera = scene.activeCamera;
  6594. scene.activeCamera = camera;
  6595. }
  6596. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6597. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6598. texture.renderList = null;
  6599. texture.samples = samples;
  6600. if (antialiasing) {
  6601. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6602. }
  6603. texture.onAfterRenderObservable.add(function () {
  6604. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6605. });
  6606. scene.incrementRenderId();
  6607. scene.resetCachedMaterial();
  6608. texture.render(true);
  6609. texture.dispose();
  6610. if (previousCamera) {
  6611. scene.activeCamera = previousCamera;
  6612. }
  6613. camera.getProjectionMatrix(true); // Force cache refresh;
  6614. };
  6615. // XHR response validator for local file scenario
  6616. Tools.ValidateXHRData = function (xhr, dataType) {
  6617. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6618. if (dataType === void 0) { dataType = 7; }
  6619. try {
  6620. if (dataType & 1) {
  6621. if (xhr.responseText && xhr.responseText.length > 0) {
  6622. return true;
  6623. }
  6624. else if (dataType === 1) {
  6625. return false;
  6626. }
  6627. }
  6628. if (dataType & 2) {
  6629. // Check header width and height since there is no "TGA" magic number
  6630. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6631. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6632. return true;
  6633. }
  6634. else if (dataType === 2) {
  6635. return false;
  6636. }
  6637. }
  6638. if (dataType & 4) {
  6639. // Check for the "DDS" magic number
  6640. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6641. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6642. return true;
  6643. }
  6644. else {
  6645. return false;
  6646. }
  6647. }
  6648. }
  6649. catch (e) {
  6650. // Global protection
  6651. }
  6652. return false;
  6653. };
  6654. /**
  6655. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6656. * Be aware Math.random() could cause collisions, but:
  6657. * "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"
  6658. */
  6659. Tools.RandomId = function () {
  6660. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6661. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6662. return v.toString(16);
  6663. });
  6664. };
  6665. Object.defineProperty(Tools, "NoneLogLevel", {
  6666. get: function () {
  6667. return Tools._NoneLogLevel;
  6668. },
  6669. enumerable: true,
  6670. configurable: true
  6671. });
  6672. Object.defineProperty(Tools, "MessageLogLevel", {
  6673. get: function () {
  6674. return Tools._MessageLogLevel;
  6675. },
  6676. enumerable: true,
  6677. configurable: true
  6678. });
  6679. Object.defineProperty(Tools, "WarningLogLevel", {
  6680. get: function () {
  6681. return Tools._WarningLogLevel;
  6682. },
  6683. enumerable: true,
  6684. configurable: true
  6685. });
  6686. Object.defineProperty(Tools, "ErrorLogLevel", {
  6687. get: function () {
  6688. return Tools._ErrorLogLevel;
  6689. },
  6690. enumerable: true,
  6691. configurable: true
  6692. });
  6693. Object.defineProperty(Tools, "AllLogLevel", {
  6694. get: function () {
  6695. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Tools._AddLogEntry = function (entry) {
  6701. Tools._LogCache = entry + Tools._LogCache;
  6702. if (Tools.OnNewCacheEntry) {
  6703. Tools.OnNewCacheEntry(entry);
  6704. }
  6705. };
  6706. Tools._FormatMessage = function (message) {
  6707. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6708. var date = new Date();
  6709. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6710. };
  6711. Tools._LogDisabled = function (message) {
  6712. // nothing to do
  6713. };
  6714. Tools._LogEnabled = function (message) {
  6715. var formattedMessage = Tools._FormatMessage(message);
  6716. console.log("BJS - " + formattedMessage);
  6717. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6718. Tools._AddLogEntry(entry);
  6719. };
  6720. Tools._WarnDisabled = function (message) {
  6721. // nothing to do
  6722. };
  6723. Tools._WarnEnabled = function (message) {
  6724. var formattedMessage = Tools._FormatMessage(message);
  6725. console.warn("BJS - " + formattedMessage);
  6726. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6727. Tools._AddLogEntry(entry);
  6728. };
  6729. Tools._ErrorDisabled = function (message) {
  6730. // nothing to do
  6731. };
  6732. Tools._ErrorEnabled = function (message) {
  6733. Tools.errorsCount++;
  6734. var formattedMessage = Tools._FormatMessage(message);
  6735. console.error("BJS - " + formattedMessage);
  6736. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6737. Tools._AddLogEntry(entry);
  6738. };
  6739. Object.defineProperty(Tools, "LogCache", {
  6740. get: function () {
  6741. return Tools._LogCache;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Tools.ClearLogCache = function () {
  6747. Tools._LogCache = "";
  6748. Tools.errorsCount = 0;
  6749. };
  6750. Object.defineProperty(Tools, "LogLevels", {
  6751. set: function (level) {
  6752. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6753. Tools.Log = Tools._LogEnabled;
  6754. }
  6755. else {
  6756. Tools.Log = Tools._LogDisabled;
  6757. }
  6758. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6759. Tools.Warn = Tools._WarnEnabled;
  6760. }
  6761. else {
  6762. Tools.Warn = Tools._WarnDisabled;
  6763. }
  6764. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6765. Tools.Error = Tools._ErrorEnabled;
  6766. }
  6767. else {
  6768. Tools.Error = Tools._ErrorDisabled;
  6769. }
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Tools.IsWindowObjectExist = function () {
  6775. return (typeof window) !== "undefined";
  6776. };
  6777. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6778. get: function () {
  6779. return Tools._PerformanceNoneLogLevel;
  6780. },
  6781. enumerable: true,
  6782. configurable: true
  6783. });
  6784. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6785. get: function () {
  6786. return Tools._PerformanceUserMarkLogLevel;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6792. get: function () {
  6793. return Tools._PerformanceConsoleLogLevel;
  6794. },
  6795. enumerable: true,
  6796. configurable: true
  6797. });
  6798. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6799. set: function (level) {
  6800. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6801. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6802. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6803. return;
  6804. }
  6805. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6806. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6807. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6808. return;
  6809. }
  6810. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6811. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6817. };
  6818. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6819. };
  6820. Tools._StartUserMark = function (counterName, condition) {
  6821. if (condition === void 0) { condition = true; }
  6822. if (!Tools._performance) {
  6823. if (!Tools.IsWindowObjectExist()) {
  6824. return;
  6825. }
  6826. Tools._performance = window.performance;
  6827. }
  6828. if (!condition || !Tools._performance.mark) {
  6829. return;
  6830. }
  6831. Tools._performance.mark(counterName + "-Begin");
  6832. };
  6833. Tools._EndUserMark = function (counterName, condition) {
  6834. if (condition === void 0) { condition = true; }
  6835. if (!condition || !Tools._performance.mark) {
  6836. return;
  6837. }
  6838. Tools._performance.mark(counterName + "-End");
  6839. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6840. };
  6841. Tools._StartPerformanceConsole = function (counterName, condition) {
  6842. if (condition === void 0) { condition = true; }
  6843. if (!condition) {
  6844. return;
  6845. }
  6846. Tools._StartUserMark(counterName, condition);
  6847. if (console.time) {
  6848. console.time(counterName);
  6849. }
  6850. };
  6851. Tools._EndPerformanceConsole = function (counterName, condition) {
  6852. if (condition === void 0) { condition = true; }
  6853. if (!condition) {
  6854. return;
  6855. }
  6856. Tools._EndUserMark(counterName, condition);
  6857. if (console.time) {
  6858. console.timeEnd(counterName);
  6859. }
  6860. };
  6861. Object.defineProperty(Tools, "Now", {
  6862. get: function () {
  6863. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6864. return window.performance.now();
  6865. }
  6866. return new Date().getTime();
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. /**
  6872. * This method will return the name of the class used to create the instance of the given object.
  6873. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6874. * @param object the object to get the class name from
  6875. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6876. */
  6877. Tools.GetClassName = function (object, isType) {
  6878. if (isType === void 0) { isType = false; }
  6879. var name = null;
  6880. if (!isType && object.getClassName) {
  6881. name = object.getClassName();
  6882. }
  6883. else {
  6884. if (object instanceof Object) {
  6885. var classObj = isType ? object : Object.getPrototypeOf(object);
  6886. name = classObj.constructor["__bjsclassName__"];
  6887. }
  6888. if (!name) {
  6889. name = typeof object;
  6890. }
  6891. }
  6892. return name;
  6893. };
  6894. Tools.First = function (array, predicate) {
  6895. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6896. var el = array_1[_i];
  6897. if (predicate(el)) {
  6898. return el;
  6899. }
  6900. }
  6901. return null;
  6902. };
  6903. /**
  6904. * This method will return the name of the full name of the class, including its owning module (if any).
  6905. * 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).
  6906. * @param object the object to get the class name from
  6907. * @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.
  6908. */
  6909. Tools.getFullClassName = function (object, isType) {
  6910. if (isType === void 0) { isType = false; }
  6911. var className = null;
  6912. var moduleName = null;
  6913. if (!isType && object.getClassName) {
  6914. className = object.getClassName();
  6915. }
  6916. else {
  6917. if (object instanceof Object) {
  6918. var classObj = isType ? object : Object.getPrototypeOf(object);
  6919. className = classObj.constructor["__bjsclassName__"];
  6920. moduleName = classObj.constructor["__bjsmoduleName__"];
  6921. }
  6922. if (!className) {
  6923. className = typeof object;
  6924. }
  6925. }
  6926. if (!className) {
  6927. return null;
  6928. }
  6929. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6930. };
  6931. /**
  6932. * 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.
  6933. * @param array
  6934. */
  6935. Tools.arrayOrStringFeeder = function (array) {
  6936. return function (index) {
  6937. if (index >= array.length) {
  6938. return null;
  6939. }
  6940. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6941. if (val && val.getHashCode) {
  6942. val = val.getHashCode();
  6943. }
  6944. if (typeof val === "string") {
  6945. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6946. }
  6947. return val;
  6948. };
  6949. };
  6950. /**
  6951. * Compute the hashCode of a stream of number
  6952. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6953. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6954. * @return the hash code computed
  6955. */
  6956. Tools.hashCodeFromStream = function (feeder) {
  6957. // Based from here: http://stackoverflow.com/a/7616484/802124
  6958. var hash = 0;
  6959. var index = 0;
  6960. var chr = feeder(index++);
  6961. while (chr != null) {
  6962. hash = ((hash << 5) - hash) + chr;
  6963. hash |= 0; // Convert to 32bit integer
  6964. chr = feeder(index++);
  6965. }
  6966. return hash;
  6967. };
  6968. Tools.BaseUrl = "";
  6969. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  6970. /**
  6971. * Default behaviour for cors in the application.
  6972. * It can be a string if the expected behavior is identical in the entire app.
  6973. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  6974. */
  6975. Tools.CorsBehavior = "anonymous";
  6976. Tools.UseFallbackTexture = true;
  6977. /**
  6978. * Use this object to register external classes like custom textures or material
  6979. * to allow the laoders to instantiate them
  6980. */
  6981. Tools.RegisteredExternalClasses = {};
  6982. // Used in case of a texture loading problem
  6983. 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";
  6984. Tools.PreprocessUrl = function (url) {
  6985. return url;
  6986. };
  6987. // Logs
  6988. Tools._NoneLogLevel = 0;
  6989. Tools._MessageLogLevel = 1;
  6990. Tools._WarningLogLevel = 2;
  6991. Tools._ErrorLogLevel = 4;
  6992. Tools._LogCache = "";
  6993. Tools.errorsCount = 0;
  6994. Tools.Log = Tools._LogEnabled;
  6995. Tools.Warn = Tools._WarnEnabled;
  6996. Tools.Error = Tools._ErrorEnabled;
  6997. // Performances
  6998. Tools._PerformanceNoneLogLevel = 0;
  6999. Tools._PerformanceUserMarkLogLevel = 1;
  7000. Tools._PerformanceConsoleLogLevel = 2;
  7001. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7002. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7003. return Tools;
  7004. }());
  7005. BABYLON.Tools = Tools;
  7006. /**
  7007. * This class is used to track a performance counter which is number based.
  7008. * The user has access to many properties which give statistics of different nature
  7009. *
  7010. * The implementer can track two kinds of Performance Counter: time and count
  7011. * 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.
  7012. * 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.
  7013. */
  7014. var PerfCounter = /** @class */ (function () {
  7015. function PerfCounter() {
  7016. this._startMonitoringTime = 0;
  7017. this._min = 0;
  7018. this._max = 0;
  7019. this._average = 0;
  7020. this._lastSecAverage = 0;
  7021. this._current = 0;
  7022. this._totalValueCount = 0;
  7023. this._totalAccumulated = 0;
  7024. this._lastSecAccumulated = 0;
  7025. this._lastSecTime = 0;
  7026. this._lastSecValueCount = 0;
  7027. }
  7028. Object.defineProperty(PerfCounter.prototype, "min", {
  7029. /**
  7030. * Returns the smallest value ever
  7031. */
  7032. get: function () {
  7033. return this._min;
  7034. },
  7035. enumerable: true,
  7036. configurable: true
  7037. });
  7038. Object.defineProperty(PerfCounter.prototype, "max", {
  7039. /**
  7040. * Returns the biggest value ever
  7041. */
  7042. get: function () {
  7043. return this._max;
  7044. },
  7045. enumerable: true,
  7046. configurable: true
  7047. });
  7048. Object.defineProperty(PerfCounter.prototype, "average", {
  7049. /**
  7050. * Returns the average value since the performance counter is running
  7051. */
  7052. get: function () {
  7053. return this._average;
  7054. },
  7055. enumerable: true,
  7056. configurable: true
  7057. });
  7058. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7059. /**
  7060. * Returns the average value of the last second the counter was monitored
  7061. */
  7062. get: function () {
  7063. return this._lastSecAverage;
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. Object.defineProperty(PerfCounter.prototype, "current", {
  7069. /**
  7070. * Returns the current value
  7071. */
  7072. get: function () {
  7073. return this._current;
  7074. },
  7075. enumerable: true,
  7076. configurable: true
  7077. });
  7078. Object.defineProperty(PerfCounter.prototype, "total", {
  7079. get: function () {
  7080. return this._totalAccumulated;
  7081. },
  7082. enumerable: true,
  7083. configurable: true
  7084. });
  7085. Object.defineProperty(PerfCounter.prototype, "count", {
  7086. get: function () {
  7087. return this._totalValueCount;
  7088. },
  7089. enumerable: true,
  7090. configurable: true
  7091. });
  7092. /**
  7093. * Call this method to start monitoring a new frame.
  7094. * 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.
  7095. */
  7096. PerfCounter.prototype.fetchNewFrame = function () {
  7097. this._totalValueCount++;
  7098. this._current = 0;
  7099. this._lastSecValueCount++;
  7100. };
  7101. /**
  7102. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7103. * @param newCount the count value to add to the monitored count
  7104. * @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.
  7105. */
  7106. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7107. if (!PerfCounter.Enabled) {
  7108. return;
  7109. }
  7110. this._current += newCount;
  7111. if (fetchResult) {
  7112. this._fetchResult();
  7113. }
  7114. };
  7115. /**
  7116. * Start monitoring this performance counter
  7117. */
  7118. PerfCounter.prototype.beginMonitoring = function () {
  7119. if (!PerfCounter.Enabled) {
  7120. return;
  7121. }
  7122. this._startMonitoringTime = Tools.Now;
  7123. };
  7124. /**
  7125. * Compute the time lapsed since the previous beginMonitoring() call.
  7126. * @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
  7127. */
  7128. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7129. if (newFrame === void 0) { newFrame = true; }
  7130. if (!PerfCounter.Enabled) {
  7131. return;
  7132. }
  7133. if (newFrame) {
  7134. this.fetchNewFrame();
  7135. }
  7136. var currentTime = Tools.Now;
  7137. this._current = currentTime - this._startMonitoringTime;
  7138. if (newFrame) {
  7139. this._fetchResult();
  7140. }
  7141. };
  7142. PerfCounter.prototype._fetchResult = function () {
  7143. this._totalAccumulated += this._current;
  7144. this._lastSecAccumulated += this._current;
  7145. // Min/Max update
  7146. this._min = Math.min(this._min, this._current);
  7147. this._max = Math.max(this._max, this._current);
  7148. this._average = this._totalAccumulated / this._totalValueCount;
  7149. // Reset last sec?
  7150. var now = Tools.Now;
  7151. if ((now - this._lastSecTime) > 1000) {
  7152. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7153. this._lastSecTime = now;
  7154. this._lastSecAccumulated = 0;
  7155. this._lastSecValueCount = 0;
  7156. }
  7157. };
  7158. PerfCounter.Enabled = true;
  7159. return PerfCounter;
  7160. }());
  7161. BABYLON.PerfCounter = PerfCounter;
  7162. /**
  7163. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7164. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7165. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7166. * @param name The name of the class, case should be preserved
  7167. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7168. */
  7169. function className(name, module) {
  7170. return function (target) {
  7171. target["__bjsclassName__"] = name;
  7172. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7173. };
  7174. }
  7175. BABYLON.className = className;
  7176. /**
  7177. * An implementation of a loop for asynchronous functions.
  7178. */
  7179. var AsyncLoop = /** @class */ (function () {
  7180. /**
  7181. * Constroctor.
  7182. * @param iterations the number of iterations.
  7183. * @param _fn the function to run each iteration
  7184. * @param _successCallback the callback that will be called upon succesful execution
  7185. * @param offset starting offset.
  7186. */
  7187. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7188. if (offset === void 0) { offset = 0; }
  7189. this.iterations = iterations;
  7190. this._fn = _fn;
  7191. this._successCallback = _successCallback;
  7192. this.index = offset - 1;
  7193. this._done = false;
  7194. }
  7195. /**
  7196. * Execute the next iteration. Must be called after the last iteration was finished.
  7197. */
  7198. AsyncLoop.prototype.executeNext = function () {
  7199. if (!this._done) {
  7200. if (this.index + 1 < this.iterations) {
  7201. ++this.index;
  7202. this._fn(this);
  7203. }
  7204. else {
  7205. this.breakLoop();
  7206. }
  7207. }
  7208. };
  7209. /**
  7210. * Break the loop and run the success callback.
  7211. */
  7212. AsyncLoop.prototype.breakLoop = function () {
  7213. this._done = true;
  7214. this._successCallback();
  7215. };
  7216. /**
  7217. * Helper function
  7218. */
  7219. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7220. if (offset === void 0) { offset = 0; }
  7221. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7222. loop.executeNext();
  7223. return loop;
  7224. };
  7225. /**
  7226. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7227. * @param iterations total number of iterations
  7228. * @param syncedIterations number of synchronous iterations in each async iteration.
  7229. * @param fn the function to call each iteration.
  7230. * @param callback a success call back that will be called when iterating stops.
  7231. * @param breakFunction a break condition (optional)
  7232. * @param timeout timeout settings for the setTimeout function. default - 0.
  7233. * @constructor
  7234. */
  7235. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7236. if (timeout === void 0) { timeout = 0; }
  7237. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7238. if (breakFunction && breakFunction())
  7239. loop.breakLoop();
  7240. else {
  7241. setTimeout(function () {
  7242. for (var i = 0; i < syncedIterations; ++i) {
  7243. var iteration = (loop.index * syncedIterations) + i;
  7244. if (iteration >= iterations)
  7245. break;
  7246. fn(iteration);
  7247. if (breakFunction && breakFunction()) {
  7248. loop.breakLoop();
  7249. break;
  7250. }
  7251. }
  7252. loop.executeNext();
  7253. }, timeout);
  7254. }
  7255. }, callback);
  7256. };
  7257. return AsyncLoop;
  7258. }());
  7259. BABYLON.AsyncLoop = AsyncLoop;
  7260. })(BABYLON || (BABYLON = {}));
  7261. //# sourceMappingURL=babylon.tools.js.map
  7262. var BABYLON;
  7263. (function (BABYLON) {
  7264. var Internals;
  7265. (function (Internals) {
  7266. var _AlphaState = /** @class */ (function () {
  7267. /**
  7268. * Initializes the state.
  7269. */
  7270. function _AlphaState() {
  7271. this._isAlphaBlendDirty = false;
  7272. this._isBlendFunctionParametersDirty = false;
  7273. this._isBlendEquationParametersDirty = false;
  7274. this._isBlendConstantsDirty = false;
  7275. this._alphaBlend = false;
  7276. this._blendFunctionParameters = new Array(4);
  7277. this._blendEquationParameters = new Array(2);
  7278. this._blendConstants = new Array(4);
  7279. this.reset();
  7280. }
  7281. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7282. get: function () {
  7283. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7284. },
  7285. enumerable: true,
  7286. configurable: true
  7287. });
  7288. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7289. get: function () {
  7290. return this._alphaBlend;
  7291. },
  7292. set: function (value) {
  7293. if (this._alphaBlend === value) {
  7294. return;
  7295. }
  7296. this._alphaBlend = value;
  7297. this._isAlphaBlendDirty = true;
  7298. },
  7299. enumerable: true,
  7300. configurable: true
  7301. });
  7302. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7303. if (this._blendConstants[0] === r &&
  7304. this._blendConstants[1] === g &&
  7305. this._blendConstants[2] === b &&
  7306. this._blendConstants[3] === a) {
  7307. return;
  7308. }
  7309. this._blendConstants[0] = r;
  7310. this._blendConstants[1] = g;
  7311. this._blendConstants[2] = b;
  7312. this._blendConstants[3] = a;
  7313. this._isBlendConstantsDirty = true;
  7314. };
  7315. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7316. if (this._blendFunctionParameters[0] === value0 &&
  7317. this._blendFunctionParameters[1] === value1 &&
  7318. this._blendFunctionParameters[2] === value2 &&
  7319. this._blendFunctionParameters[3] === value3) {
  7320. return;
  7321. }
  7322. this._blendFunctionParameters[0] = value0;
  7323. this._blendFunctionParameters[1] = value1;
  7324. this._blendFunctionParameters[2] = value2;
  7325. this._blendFunctionParameters[3] = value3;
  7326. this._isBlendFunctionParametersDirty = true;
  7327. };
  7328. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7329. if (this._blendEquationParameters[0] === rgb &&
  7330. this._blendEquationParameters[1] === alpha) {
  7331. return;
  7332. }
  7333. this._blendEquationParameters[0] = rgb;
  7334. this._blendEquationParameters[1] = alpha;
  7335. this._isBlendEquationParametersDirty = true;
  7336. };
  7337. _AlphaState.prototype.reset = function () {
  7338. this._alphaBlend = false;
  7339. this._blendFunctionParameters[0] = null;
  7340. this._blendFunctionParameters[1] = null;
  7341. this._blendFunctionParameters[2] = null;
  7342. this._blendFunctionParameters[3] = null;
  7343. this._blendEquationParameters[0] = null;
  7344. this._blendEquationParameters[1] = null;
  7345. this._blendConstants[0] = null;
  7346. this._blendConstants[1] = null;
  7347. this._blendConstants[2] = null;
  7348. this._blendConstants[3] = null;
  7349. this._isAlphaBlendDirty = true;
  7350. this._isBlendFunctionParametersDirty = false;
  7351. this._isBlendEquationParametersDirty = false;
  7352. this._isBlendConstantsDirty = false;
  7353. };
  7354. _AlphaState.prototype.apply = function (gl) {
  7355. if (!this.isDirty) {
  7356. return;
  7357. }
  7358. // Alpha blend
  7359. if (this._isAlphaBlendDirty) {
  7360. if (this._alphaBlend) {
  7361. gl.enable(gl.BLEND);
  7362. }
  7363. else {
  7364. gl.disable(gl.BLEND);
  7365. }
  7366. this._isAlphaBlendDirty = false;
  7367. }
  7368. // Alpha function
  7369. if (this._isBlendFunctionParametersDirty) {
  7370. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7371. this._isBlendFunctionParametersDirty = false;
  7372. }
  7373. // Alpha equation
  7374. if (this._isBlendEquationParametersDirty) {
  7375. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7376. this._isBlendEquationParametersDirty = false;
  7377. }
  7378. // Constants
  7379. if (this._isBlendConstantsDirty) {
  7380. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7381. this._isBlendConstantsDirty = false;
  7382. }
  7383. };
  7384. return _AlphaState;
  7385. }());
  7386. Internals._AlphaState = _AlphaState;
  7387. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7388. })(BABYLON || (BABYLON = {}));
  7389. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7390. var BABYLON;
  7391. (function (BABYLON) {
  7392. var Internals;
  7393. (function (Internals) {
  7394. var _DepthCullingState = /** @class */ (function () {
  7395. /**
  7396. * Initializes the state.
  7397. */
  7398. function _DepthCullingState() {
  7399. this._isDepthTestDirty = false;
  7400. this._isDepthMaskDirty = false;
  7401. this._isDepthFuncDirty = false;
  7402. this._isCullFaceDirty = false;
  7403. this._isCullDirty = false;
  7404. this._isZOffsetDirty = false;
  7405. this.reset();
  7406. }
  7407. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7408. get: function () {
  7409. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7410. },
  7411. enumerable: true,
  7412. configurable: true
  7413. });
  7414. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7415. get: function () {
  7416. return this._zOffset;
  7417. },
  7418. set: function (value) {
  7419. if (this._zOffset === value) {
  7420. return;
  7421. }
  7422. this._zOffset = value;
  7423. this._isZOffsetDirty = true;
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7429. get: function () {
  7430. return this._cullFace;
  7431. },
  7432. set: function (value) {
  7433. if (this._cullFace === value) {
  7434. return;
  7435. }
  7436. this._cullFace = value;
  7437. this._isCullFaceDirty = true;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7443. get: function () {
  7444. return this._cull;
  7445. },
  7446. set: function (value) {
  7447. if (this._cull === value) {
  7448. return;
  7449. }
  7450. this._cull = value;
  7451. this._isCullDirty = true;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7457. get: function () {
  7458. return this._depthFunc;
  7459. },
  7460. set: function (value) {
  7461. if (this._depthFunc === value) {
  7462. return;
  7463. }
  7464. this._depthFunc = value;
  7465. this._isDepthFuncDirty = true;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7471. get: function () {
  7472. return this._depthMask;
  7473. },
  7474. set: function (value) {
  7475. if (this._depthMask === value) {
  7476. return;
  7477. }
  7478. this._depthMask = value;
  7479. this._isDepthMaskDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7485. get: function () {
  7486. return this._depthTest;
  7487. },
  7488. set: function (value) {
  7489. if (this._depthTest === value) {
  7490. return;
  7491. }
  7492. this._depthTest = value;
  7493. this._isDepthTestDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. _DepthCullingState.prototype.reset = function () {
  7499. this._depthMask = true;
  7500. this._depthTest = true;
  7501. this._depthFunc = null;
  7502. this._cullFace = null;
  7503. this._cull = null;
  7504. this._zOffset = 0;
  7505. this._isDepthTestDirty = true;
  7506. this._isDepthMaskDirty = true;
  7507. this._isDepthFuncDirty = false;
  7508. this._isCullFaceDirty = false;
  7509. this._isCullDirty = false;
  7510. this._isZOffsetDirty = false;
  7511. };
  7512. _DepthCullingState.prototype.apply = function (gl) {
  7513. if (!this.isDirty) {
  7514. return;
  7515. }
  7516. // Cull
  7517. if (this._isCullDirty) {
  7518. if (this.cull) {
  7519. gl.enable(gl.CULL_FACE);
  7520. }
  7521. else {
  7522. gl.disable(gl.CULL_FACE);
  7523. }
  7524. this._isCullDirty = false;
  7525. }
  7526. // Cull face
  7527. if (this._isCullFaceDirty) {
  7528. gl.cullFace(this.cullFace);
  7529. this._isCullFaceDirty = false;
  7530. }
  7531. // Depth mask
  7532. if (this._isDepthMaskDirty) {
  7533. gl.depthMask(this.depthMask);
  7534. this._isDepthMaskDirty = false;
  7535. }
  7536. // Depth test
  7537. if (this._isDepthTestDirty) {
  7538. if (this.depthTest) {
  7539. gl.enable(gl.DEPTH_TEST);
  7540. }
  7541. else {
  7542. gl.disable(gl.DEPTH_TEST);
  7543. }
  7544. this._isDepthTestDirty = false;
  7545. }
  7546. // Depth func
  7547. if (this._isDepthFuncDirty) {
  7548. gl.depthFunc(this.depthFunc);
  7549. this._isDepthFuncDirty = false;
  7550. }
  7551. // zOffset
  7552. if (this._isZOffsetDirty) {
  7553. if (this.zOffset) {
  7554. gl.enable(gl.POLYGON_OFFSET_FILL);
  7555. gl.polygonOffset(this.zOffset, 0);
  7556. }
  7557. else {
  7558. gl.disable(gl.POLYGON_OFFSET_FILL);
  7559. }
  7560. this._isZOffsetDirty = false;
  7561. }
  7562. };
  7563. return _DepthCullingState;
  7564. }());
  7565. Internals._DepthCullingState = _DepthCullingState;
  7566. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7567. })(BABYLON || (BABYLON = {}));
  7568. //# sourceMappingURL=babylon.depthCullingState.js.map
  7569. var BABYLON;
  7570. (function (BABYLON) {
  7571. var Internals;
  7572. (function (Internals) {
  7573. var _StencilState = /** @class */ (function () {
  7574. function _StencilState() {
  7575. this._isStencilTestDirty = false;
  7576. this._isStencilMaskDirty = false;
  7577. this._isStencilFuncDirty = false;
  7578. this._isStencilOpDirty = false;
  7579. this.reset();
  7580. }
  7581. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7582. get: function () {
  7583. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7589. get: function () {
  7590. return this._stencilFunc;
  7591. },
  7592. set: function (value) {
  7593. if (this._stencilFunc === value) {
  7594. return;
  7595. }
  7596. this._stencilFunc = value;
  7597. this._isStencilFuncDirty = true;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7603. get: function () {
  7604. return this._stencilFuncRef;
  7605. },
  7606. set: function (value) {
  7607. if (this._stencilFuncRef === value) {
  7608. return;
  7609. }
  7610. this._stencilFuncRef = value;
  7611. this._isStencilFuncDirty = true;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7617. get: function () {
  7618. return this._stencilFuncMask;
  7619. },
  7620. set: function (value) {
  7621. if (this._stencilFuncMask === value) {
  7622. return;
  7623. }
  7624. this._stencilFuncMask = value;
  7625. this._isStencilFuncDirty = true;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7631. get: function () {
  7632. return this._stencilOpStencilFail;
  7633. },
  7634. set: function (value) {
  7635. if (this._stencilOpStencilFail === value) {
  7636. return;
  7637. }
  7638. this._stencilOpStencilFail = value;
  7639. this._isStencilOpDirty = true;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7645. get: function () {
  7646. return this._stencilOpDepthFail;
  7647. },
  7648. set: function (value) {
  7649. if (this._stencilOpDepthFail === value) {
  7650. return;
  7651. }
  7652. this._stencilOpDepthFail = value;
  7653. this._isStencilOpDirty = true;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7659. get: function () {
  7660. return this._stencilOpStencilDepthPass;
  7661. },
  7662. set: function (value) {
  7663. if (this._stencilOpStencilDepthPass === value) {
  7664. return;
  7665. }
  7666. this._stencilOpStencilDepthPass = value;
  7667. this._isStencilOpDirty = true;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7673. get: function () {
  7674. return this._stencilMask;
  7675. },
  7676. set: function (value) {
  7677. if (this._stencilMask === value) {
  7678. return;
  7679. }
  7680. this._stencilMask = value;
  7681. this._isStencilMaskDirty = true;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7687. get: function () {
  7688. return this._stencilTest;
  7689. },
  7690. set: function (value) {
  7691. if (this._stencilTest === value) {
  7692. return;
  7693. }
  7694. this._stencilTest = value;
  7695. this._isStencilTestDirty = true;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. _StencilState.prototype.reset = function () {
  7701. this._stencilTest = false;
  7702. this._stencilMask = 0xFF;
  7703. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7704. this._stencilFuncRef = 1;
  7705. this._stencilFuncMask = 0xFF;
  7706. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7707. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7708. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7709. this._isStencilTestDirty = true;
  7710. this._isStencilMaskDirty = true;
  7711. this._isStencilFuncDirty = true;
  7712. this._isStencilOpDirty = true;
  7713. };
  7714. _StencilState.prototype.apply = function (gl) {
  7715. if (!this.isDirty) {
  7716. return;
  7717. }
  7718. // Stencil test
  7719. if (this._isStencilTestDirty) {
  7720. if (this.stencilTest) {
  7721. gl.enable(gl.STENCIL_TEST);
  7722. }
  7723. else {
  7724. gl.disable(gl.STENCIL_TEST);
  7725. }
  7726. this._isStencilTestDirty = false;
  7727. }
  7728. // Stencil mask
  7729. if (this._isStencilMaskDirty) {
  7730. gl.stencilMask(this.stencilMask);
  7731. this._isStencilMaskDirty = false;
  7732. }
  7733. // Stencil func
  7734. if (this._isStencilFuncDirty) {
  7735. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7736. this._isStencilFuncDirty = false;
  7737. }
  7738. // Stencil op
  7739. if (this._isStencilOpDirty) {
  7740. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7741. this._isStencilOpDirty = false;
  7742. }
  7743. };
  7744. return _StencilState;
  7745. }());
  7746. Internals._StencilState = _StencilState;
  7747. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7748. })(BABYLON || (BABYLON = {}));
  7749. //# sourceMappingURL=babylon.stencilState.js.map
  7750. var BABYLON;
  7751. (function (BABYLON) {
  7752. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7753. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7754. };
  7755. var compileRawShader = function (gl, source, type) {
  7756. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7757. gl.shaderSource(shader, source);
  7758. gl.compileShader(shader);
  7759. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7760. var log = gl.getShaderInfoLog(shader);
  7761. if (log) {
  7762. throw new Error(log);
  7763. }
  7764. }
  7765. if (!shader) {
  7766. throw new Error("Something went wrong while compile the shader.");
  7767. }
  7768. return shader;
  7769. };
  7770. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7771. var magFilter = gl.NEAREST;
  7772. var minFilter = gl.NEAREST;
  7773. switch (samplingMode) {
  7774. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7775. magFilter = gl.LINEAR;
  7776. if (generateMipMaps) {
  7777. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7778. }
  7779. else {
  7780. minFilter = gl.LINEAR;
  7781. }
  7782. break;
  7783. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7784. magFilter = gl.LINEAR;
  7785. if (generateMipMaps) {
  7786. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7787. }
  7788. else {
  7789. minFilter = gl.LINEAR;
  7790. }
  7791. break;
  7792. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7793. magFilter = gl.NEAREST;
  7794. if (generateMipMaps) {
  7795. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7796. }
  7797. else {
  7798. minFilter = gl.NEAREST;
  7799. }
  7800. break;
  7801. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7802. magFilter = gl.NEAREST;
  7803. if (generateMipMaps) {
  7804. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7805. }
  7806. else {
  7807. minFilter = gl.NEAREST;
  7808. }
  7809. break;
  7810. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7811. magFilter = gl.NEAREST;
  7812. if (generateMipMaps) {
  7813. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7814. }
  7815. else {
  7816. minFilter = gl.LINEAR;
  7817. }
  7818. break;
  7819. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7820. magFilter = gl.NEAREST;
  7821. if (generateMipMaps) {
  7822. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7823. }
  7824. else {
  7825. minFilter = gl.LINEAR;
  7826. }
  7827. break;
  7828. case BABYLON.Texture.NEAREST_LINEAR:
  7829. magFilter = gl.NEAREST;
  7830. minFilter = gl.LINEAR;
  7831. break;
  7832. case BABYLON.Texture.NEAREST_NEAREST:
  7833. magFilter = gl.NEAREST;
  7834. minFilter = gl.NEAREST;
  7835. break;
  7836. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7837. magFilter = gl.LINEAR;
  7838. if (generateMipMaps) {
  7839. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7840. }
  7841. else {
  7842. minFilter = gl.NEAREST;
  7843. }
  7844. break;
  7845. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7846. magFilter = gl.LINEAR;
  7847. if (generateMipMaps) {
  7848. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7849. }
  7850. else {
  7851. minFilter = gl.NEAREST;
  7852. }
  7853. break;
  7854. case BABYLON.Texture.LINEAR_LINEAR:
  7855. magFilter = gl.LINEAR;
  7856. minFilter = gl.LINEAR;
  7857. break;
  7858. case BABYLON.Texture.LINEAR_NEAREST:
  7859. magFilter = gl.LINEAR;
  7860. minFilter = gl.NEAREST;
  7861. break;
  7862. }
  7863. return {
  7864. min: minFilter,
  7865. mag: magFilter
  7866. };
  7867. };
  7868. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7869. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7870. var img;
  7871. var onload = function () {
  7872. loadedImages[index] = img;
  7873. loadedImages._internalCount++;
  7874. if (scene) {
  7875. scene._removePendingData(img);
  7876. }
  7877. if (loadedImages._internalCount === 6) {
  7878. onfinish(loadedImages);
  7879. }
  7880. };
  7881. var onerror = function (message, exception) {
  7882. if (scene) {
  7883. scene._removePendingData(img);
  7884. }
  7885. if (onErrorCallBack) {
  7886. onErrorCallBack(message, exception);
  7887. }
  7888. };
  7889. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7890. if (scene) {
  7891. scene._addPendingData(img);
  7892. }
  7893. };
  7894. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7895. if (onError === void 0) { onError = null; }
  7896. var loadedImages = [];
  7897. loadedImages._internalCount = 0;
  7898. for (var index = 0; index < 6; index++) {
  7899. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7900. }
  7901. };
  7902. var partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  7903. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7904. var onload = function (data) {
  7905. loadedFiles[index] = data;
  7906. loadedFiles._internalCount++;
  7907. if (loadedFiles._internalCount === 6) {
  7908. onfinish(loadedFiles);
  7909. }
  7910. };
  7911. var onerror = function (request, exception) {
  7912. if (onErrorCallBack && request) {
  7913. onErrorCallBack(request.status + " " + request.statusText, exception);
  7914. }
  7915. };
  7916. BABYLON.Tools.LoadFile(url, onload, undefined, undefined, true, onerror);
  7917. };
  7918. var cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  7919. if (onError === void 0) { onError = null; }
  7920. var loadedFiles = [];
  7921. loadedFiles._internalCount = 0;
  7922. for (var index = 0; index < 6; index++) {
  7923. partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  7924. }
  7925. };
  7926. var BufferPointer = /** @class */ (function () {
  7927. function BufferPointer() {
  7928. }
  7929. return BufferPointer;
  7930. }());
  7931. var InstancingAttributeInfo = /** @class */ (function () {
  7932. function InstancingAttributeInfo() {
  7933. }
  7934. return InstancingAttributeInfo;
  7935. }());
  7936. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7937. /**
  7938. * Define options used to create a render target texture
  7939. */
  7940. var RenderTargetCreationOptions = /** @class */ (function () {
  7941. function RenderTargetCreationOptions() {
  7942. }
  7943. return RenderTargetCreationOptions;
  7944. }());
  7945. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7946. /**
  7947. * Regroup several parameters relative to the browser in use
  7948. */
  7949. var EngineCapabilities = /** @class */ (function () {
  7950. function EngineCapabilities() {
  7951. }
  7952. return EngineCapabilities;
  7953. }());
  7954. BABYLON.EngineCapabilities = EngineCapabilities;
  7955. /**
  7956. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7957. */
  7958. var Engine = /** @class */ (function () {
  7959. /**
  7960. * @constructor
  7961. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7962. * @param {boolean} [antialias] - enable antialias
  7963. * @param options - further options to be sent to the getContext function
  7964. */
  7965. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7966. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7967. var _this = this;
  7968. // Public members
  7969. this.forcePOTTextures = false;
  7970. this.isFullscreen = false;
  7971. this.isPointerLock = false;
  7972. this.cullBackFaces = true;
  7973. this.renderEvenInBackground = true;
  7974. this.preventCacheWipeBetweenFrames = false;
  7975. // To enable/disable IDB support and avoid XHR on .manifest
  7976. this.enableOfflineSupport = false;
  7977. this.scenes = new Array();
  7978. this.postProcesses = new Array();
  7979. // Observables
  7980. /**
  7981. * Observable event triggered each time the rendering canvas is resized
  7982. */
  7983. this.onResizeObservable = new BABYLON.Observable();
  7984. /**
  7985. * Observable event triggered each time the canvas loses focus
  7986. */
  7987. this.onCanvasBlurObservable = new BABYLON.Observable();
  7988. /**
  7989. * Observable event triggered each time the canvas gains focus
  7990. */
  7991. this.onCanvasFocusObservable = new BABYLON.Observable();
  7992. /**
  7993. * Observable event triggered each time the canvas receives pointerout event
  7994. */
  7995. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7996. /**
  7997. * Observable event triggered before each texture is initialized
  7998. */
  7999. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8000. //WebVR
  8001. this._vrDisplay = undefined;
  8002. this._vrSupported = false;
  8003. this._vrExclusivePointerMode = false;
  8004. // Uniform buffers list
  8005. this.disableUniformBuffers = false;
  8006. this._uniformBuffers = new Array();
  8007. // Observables
  8008. /**
  8009. * Observable raised when the engine begins a new frame
  8010. */
  8011. this.onBeginFrameObservable = new BABYLON.Observable();
  8012. /**
  8013. * Observable raised when the engine ends the current frame
  8014. */
  8015. this.onEndFrameObservable = new BABYLON.Observable();
  8016. /**
  8017. * Observable raised when the engine is about to compile a shader
  8018. */
  8019. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8020. /**
  8021. * Observable raised when the engine has jsut compiled a shader
  8022. */
  8023. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8024. this._windowIsBackground = false;
  8025. this._webGLVersion = 1.0;
  8026. this._badOS = false;
  8027. this._badDesktopOS = false;
  8028. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8029. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8030. this.onVRRequestPresentStart = new BABYLON.Observable();
  8031. this._colorWrite = true;
  8032. this._drawCalls = new BABYLON.PerfCounter();
  8033. this._renderingQueueLaunched = false;
  8034. this._activeRenderLoops = new Array();
  8035. // Deterministic lockstepMaxSteps
  8036. this._deterministicLockstep = false;
  8037. this._lockstepMaxSteps = 4;
  8038. // Lost context
  8039. this.onContextLostObservable = new BABYLON.Observable();
  8040. this.onContextRestoredObservable = new BABYLON.Observable();
  8041. this._contextWasLost = false;
  8042. this._doNotHandleContextLost = false;
  8043. // FPS
  8044. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8045. this._fps = 60;
  8046. this._deltaTime = 0;
  8047. /**
  8048. * Turn this value on if you want to pause FPS computation when in background
  8049. */
  8050. this.disablePerformanceMonitorInBackground = false;
  8051. // States
  8052. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8053. this._stencilState = new BABYLON.Internals._StencilState();
  8054. this._alphaState = new BABYLON.Internals._AlphaState();
  8055. this._alphaMode = Engine.ALPHA_DISABLE;
  8056. // Cache
  8057. this._internalTexturesCache = new Array();
  8058. this._boundTexturesCache = {};
  8059. this._boundTexturesOrder = new Array();
  8060. this._compiledEffects = {};
  8061. this._vertexAttribArraysEnabled = [];
  8062. this._uintIndicesCurrentlySet = false;
  8063. this._currentBoundBuffer = new Array();
  8064. this._currentBufferPointers = new Array();
  8065. this._currentInstanceLocations = new Array();
  8066. this._currentInstanceBuffers = new Array();
  8067. this._vaoRecordInProgress = false;
  8068. this._mustWipeVertexAttributes = false;
  8069. this._nextFreeTextureSlot = 0;
  8070. // Hardware supported Compressed Textures
  8071. this._texturesSupported = new Array();
  8072. this._onVRFullScreenTriggered = function () {
  8073. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8074. //get the old size before we change
  8075. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8076. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8077. //get the width and height, change the render size
  8078. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8079. _this.setHardwareScalingLevel(1);
  8080. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8081. }
  8082. else {
  8083. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8084. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8085. }
  8086. };
  8087. this._boundUniforms = {};
  8088. var canvas = null;
  8089. Engine.Instances.push(this);
  8090. if (!canvasOrContext) {
  8091. return;
  8092. }
  8093. options = options || {};
  8094. if (canvasOrContext.getContext) {
  8095. canvas = canvasOrContext;
  8096. this._renderingCanvas = canvas;
  8097. if (antialias != null) {
  8098. options.antialias = antialias;
  8099. }
  8100. if (options.deterministicLockstep === undefined) {
  8101. options.deterministicLockstep = false;
  8102. }
  8103. if (options.lockstepMaxSteps === undefined) {
  8104. options.lockstepMaxSteps = 4;
  8105. }
  8106. if (options.preserveDrawingBuffer === undefined) {
  8107. options.preserveDrawingBuffer = false;
  8108. }
  8109. if (options.audioEngine === undefined) {
  8110. options.audioEngine = true;
  8111. }
  8112. if (options.stencil === undefined) {
  8113. options.stencil = true;
  8114. }
  8115. this._deterministicLockstep = options.deterministicLockstep;
  8116. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8117. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8118. // Exceptions
  8119. if (!options.disableWebGL2Support) {
  8120. if (navigator && navigator.userAgent) {
  8121. var ua = navigator.userAgent;
  8122. for (var _i = 0, _a = Engine.WebGL2UniformBuffersExceptionList; _i < _a.length; _i++) {
  8123. var exception = _a[_i];
  8124. if (ua.indexOf(exception) > -1) {
  8125. this.disableUniformBuffers = true;
  8126. break;
  8127. }
  8128. }
  8129. }
  8130. }
  8131. // GL
  8132. if (!options.disableWebGL2Support) {
  8133. try {
  8134. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8135. if (this._gl) {
  8136. this._webGLVersion = 2.0;
  8137. }
  8138. }
  8139. catch (e) {
  8140. // Do nothing
  8141. }
  8142. }
  8143. if (!this._gl) {
  8144. if (!canvas) {
  8145. throw new Error("The provided canvas is null or undefined.");
  8146. }
  8147. try {
  8148. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8149. }
  8150. catch (e) {
  8151. throw new Error("WebGL not supported");
  8152. }
  8153. }
  8154. if (!this._gl) {
  8155. throw new Error("WebGL not supported");
  8156. }
  8157. this._onCanvasFocus = function () {
  8158. _this.onCanvasFocusObservable.notifyObservers(_this);
  8159. };
  8160. this._onCanvasBlur = function () {
  8161. _this.onCanvasBlurObservable.notifyObservers(_this);
  8162. };
  8163. canvas.addEventListener("focus", this._onCanvasFocus);
  8164. canvas.addEventListener("blur", this._onCanvasBlur);
  8165. this._onBlur = function () {
  8166. if (_this.disablePerformanceMonitorInBackground) {
  8167. _this._performanceMonitor.disable();
  8168. }
  8169. _this._windowIsBackground = true;
  8170. };
  8171. this._onFocus = function () {
  8172. if (_this.disablePerformanceMonitorInBackground) {
  8173. _this._performanceMonitor.enable();
  8174. }
  8175. _this._windowIsBackground = false;
  8176. };
  8177. this._onCanvasPointerOut = function () {
  8178. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8179. };
  8180. window.addEventListener("blur", this._onBlur);
  8181. window.addEventListener("focus", this._onFocus);
  8182. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8183. // Context lost
  8184. if (!this._doNotHandleContextLost) {
  8185. this._onContextLost = function (evt) {
  8186. evt.preventDefault();
  8187. _this._contextWasLost = true;
  8188. BABYLON.Tools.Warn("WebGL context lost.");
  8189. _this.onContextLostObservable.notifyObservers(_this);
  8190. };
  8191. this._onContextRestored = function (evt) {
  8192. // Adding a timeout to avoid race condition at browser level
  8193. setTimeout(function () {
  8194. // Rebuild gl context
  8195. _this._initGLContext();
  8196. // Rebuild effects
  8197. _this._rebuildEffects();
  8198. // Rebuild textures
  8199. _this._rebuildInternalTextures();
  8200. // Rebuild buffers
  8201. _this._rebuildBuffers();
  8202. // Cache
  8203. _this.wipeCaches(true);
  8204. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8205. _this.onContextRestoredObservable.notifyObservers(_this);
  8206. _this._contextWasLost = false;
  8207. }, 0);
  8208. };
  8209. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8210. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8211. }
  8212. }
  8213. else {
  8214. this._gl = canvasOrContext;
  8215. this._renderingCanvas = this._gl.canvas;
  8216. if (this._gl.renderbufferStorageMultisample) {
  8217. this._webGLVersion = 2.0;
  8218. }
  8219. options.stencil = this._gl.getContextAttributes().stencil;
  8220. }
  8221. // Viewport
  8222. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8223. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8224. this.resize();
  8225. this._isStencilEnable = options.stencil ? true : false;
  8226. this._initGLContext();
  8227. if (canvas) {
  8228. // Fullscreen
  8229. this._onFullscreenChange = function () {
  8230. if (document.fullscreen !== undefined) {
  8231. _this.isFullscreen = document.fullscreen;
  8232. }
  8233. else if (document.mozFullScreen !== undefined) {
  8234. _this.isFullscreen = document.mozFullScreen;
  8235. }
  8236. else if (document.webkitIsFullScreen !== undefined) {
  8237. _this.isFullscreen = document.webkitIsFullScreen;
  8238. }
  8239. else if (document.msIsFullScreen !== undefined) {
  8240. _this.isFullscreen = document.msIsFullScreen;
  8241. }
  8242. // Pointer lock
  8243. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8244. canvas.requestPointerLock = canvas.requestPointerLock ||
  8245. canvas.msRequestPointerLock ||
  8246. canvas.mozRequestPointerLock ||
  8247. canvas.webkitRequestPointerLock;
  8248. if (canvas.requestPointerLock) {
  8249. canvas.requestPointerLock();
  8250. }
  8251. }
  8252. };
  8253. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8254. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8255. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8256. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8257. // Pointer lock
  8258. this._onPointerLockChange = function () {
  8259. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8260. document.webkitPointerLockElement === canvas ||
  8261. document.msPointerLockElement === canvas ||
  8262. document.pointerLockElement === canvas);
  8263. };
  8264. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8265. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8266. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8267. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8268. this._onVRDisplayPointerRestricted = function () {
  8269. if (canvas) {
  8270. canvas.requestPointerLock();
  8271. }
  8272. };
  8273. this._onVRDisplayPointerUnrestricted = function () {
  8274. document.exitPointerLock();
  8275. };
  8276. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8277. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8278. }
  8279. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8280. Engine.audioEngine = new BABYLON.AudioEngine();
  8281. }
  8282. // Prepare buffer pointers
  8283. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8284. this._currentBufferPointers[i] = new BufferPointer();
  8285. }
  8286. // Load WebVR Devices
  8287. if (options.autoEnableWebVR) {
  8288. this.initWebVR();
  8289. }
  8290. // Detect if we are running on a faulty buggy OS.
  8291. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8292. // Detect if we are running on a faulty buggy desktop OS.
  8293. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8294. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8295. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8296. }
  8297. Object.defineProperty(Engine, "LastCreatedEngine", {
  8298. get: function () {
  8299. if (Engine.Instances.length === 0) {
  8300. return null;
  8301. }
  8302. return Engine.Instances[Engine.Instances.length - 1];
  8303. },
  8304. enumerable: true,
  8305. configurable: true
  8306. });
  8307. Object.defineProperty(Engine, "LastCreatedScene", {
  8308. get: function () {
  8309. var lastCreatedEngine = Engine.LastCreatedEngine;
  8310. if (!lastCreatedEngine) {
  8311. return null;
  8312. }
  8313. if (lastCreatedEngine.scenes.length === 0) {
  8314. return null;
  8315. }
  8316. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. /**
  8322. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8323. */
  8324. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8325. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8326. var engine = Engine.Instances[engineIndex];
  8327. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8328. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8329. }
  8330. }
  8331. };
  8332. Object.defineProperty(Engine, "NEVER", {
  8333. get: function () {
  8334. return Engine._NEVER;
  8335. },
  8336. enumerable: true,
  8337. configurable: true
  8338. });
  8339. Object.defineProperty(Engine, "ALWAYS", {
  8340. get: function () {
  8341. return Engine._ALWAYS;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(Engine, "LESS", {
  8347. get: function () {
  8348. return Engine._LESS;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Engine, "EQUAL", {
  8354. get: function () {
  8355. return Engine._EQUAL;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Engine, "LEQUAL", {
  8361. get: function () {
  8362. return Engine._LEQUAL;
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. Object.defineProperty(Engine, "GREATER", {
  8368. get: function () {
  8369. return Engine._GREATER;
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. Object.defineProperty(Engine, "GEQUAL", {
  8375. get: function () {
  8376. return Engine._GEQUAL;
  8377. },
  8378. enumerable: true,
  8379. configurable: true
  8380. });
  8381. Object.defineProperty(Engine, "NOTEQUAL", {
  8382. get: function () {
  8383. return Engine._NOTEQUAL;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(Engine, "KEEP", {
  8389. get: function () {
  8390. return Engine._KEEP;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Object.defineProperty(Engine, "REPLACE", {
  8396. get: function () {
  8397. return Engine._REPLACE;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(Engine, "INCR", {
  8403. get: function () {
  8404. return Engine._INCR;
  8405. },
  8406. enumerable: true,
  8407. configurable: true
  8408. });
  8409. Object.defineProperty(Engine, "DECR", {
  8410. get: function () {
  8411. return Engine._DECR;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(Engine, "INVERT", {
  8417. get: function () {
  8418. return Engine._INVERT;
  8419. },
  8420. enumerable: true,
  8421. configurable: true
  8422. });
  8423. Object.defineProperty(Engine, "INCR_WRAP", {
  8424. get: function () {
  8425. return Engine._INCR_WRAP;
  8426. },
  8427. enumerable: true,
  8428. configurable: true
  8429. });
  8430. Object.defineProperty(Engine, "DECR_WRAP", {
  8431. get: function () {
  8432. return Engine._DECR_WRAP;
  8433. },
  8434. enumerable: true,
  8435. configurable: true
  8436. });
  8437. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8438. get: function () {
  8439. return Engine._ALPHA_DISABLE;
  8440. },
  8441. enumerable: true,
  8442. configurable: true
  8443. });
  8444. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8445. get: function () {
  8446. return Engine._ALPHA_ONEONE;
  8447. },
  8448. enumerable: true,
  8449. configurable: true
  8450. });
  8451. Object.defineProperty(Engine, "ALPHA_ADD", {
  8452. get: function () {
  8453. return Engine._ALPHA_ADD;
  8454. },
  8455. enumerable: true,
  8456. configurable: true
  8457. });
  8458. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8459. get: function () {
  8460. return Engine._ALPHA_COMBINE;
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8466. get: function () {
  8467. return Engine._ALPHA_SUBTRACT;
  8468. },
  8469. enumerable: true,
  8470. configurable: true
  8471. });
  8472. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8473. get: function () {
  8474. return Engine._ALPHA_MULTIPLY;
  8475. },
  8476. enumerable: true,
  8477. configurable: true
  8478. });
  8479. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8480. get: function () {
  8481. return Engine._ALPHA_MAXIMIZED;
  8482. },
  8483. enumerable: true,
  8484. configurable: true
  8485. });
  8486. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8487. get: function () {
  8488. return Engine._ALPHA_PREMULTIPLIED;
  8489. },
  8490. enumerable: true,
  8491. configurable: true
  8492. });
  8493. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8494. get: function () {
  8495. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8496. },
  8497. enumerable: true,
  8498. configurable: true
  8499. });
  8500. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8501. get: function () {
  8502. return Engine._ALPHA_INTERPOLATE;
  8503. },
  8504. enumerable: true,
  8505. configurable: true
  8506. });
  8507. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8508. get: function () {
  8509. return Engine._ALPHA_SCREENMODE;
  8510. },
  8511. enumerable: true,
  8512. configurable: true
  8513. });
  8514. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8515. get: function () {
  8516. return Engine._DELAYLOADSTATE_NONE;
  8517. },
  8518. enumerable: true,
  8519. configurable: true
  8520. });
  8521. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8522. get: function () {
  8523. return Engine._DELAYLOADSTATE_LOADED;
  8524. },
  8525. enumerable: true,
  8526. configurable: true
  8527. });
  8528. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8529. get: function () {
  8530. return Engine._DELAYLOADSTATE_LOADING;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8536. get: function () {
  8537. return Engine._DELAYLOADSTATE_NOTLOADED;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8543. get: function () {
  8544. return Engine._TEXTUREFORMAT_ALPHA;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8550. get: function () {
  8551. return Engine._TEXTUREFORMAT_LUMINANCE;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8557. get: function () {
  8558. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8564. get: function () {
  8565. return Engine._TEXTUREFORMAT_RGB;
  8566. },
  8567. enumerable: true,
  8568. configurable: true
  8569. });
  8570. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8571. get: function () {
  8572. return Engine._TEXTUREFORMAT_RGBA;
  8573. },
  8574. enumerable: true,
  8575. configurable: true
  8576. });
  8577. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8578. get: function () {
  8579. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8580. },
  8581. enumerable: true,
  8582. configurable: true
  8583. });
  8584. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8585. get: function () {
  8586. return Engine._TEXTURETYPE_FLOAT;
  8587. },
  8588. enumerable: true,
  8589. configurable: true
  8590. });
  8591. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8592. get: function () {
  8593. return Engine._TEXTURETYPE_HALF_FLOAT;
  8594. },
  8595. enumerable: true,
  8596. configurable: true
  8597. });
  8598. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8599. get: function () {
  8600. return Engine._SCALEMODE_FLOOR;
  8601. },
  8602. enumerable: true,
  8603. configurable: true
  8604. });
  8605. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8606. get: function () {
  8607. return Engine._SCALEMODE_NEAREST;
  8608. },
  8609. enumerable: true,
  8610. configurable: true
  8611. });
  8612. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8613. get: function () {
  8614. return Engine._SCALEMODE_CEILING;
  8615. },
  8616. enumerable: true,
  8617. configurable: true
  8618. });
  8619. Object.defineProperty(Engine, "Version", {
  8620. get: function () {
  8621. return "3.2.0-alpha0";
  8622. },
  8623. enumerable: true,
  8624. configurable: true
  8625. });
  8626. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8627. get: function () {
  8628. return this._vrExclusivePointerMode;
  8629. },
  8630. enumerable: true,
  8631. configurable: true
  8632. });
  8633. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8634. get: function () {
  8635. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8636. },
  8637. enumerable: true,
  8638. configurable: true
  8639. });
  8640. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8641. get: function () {
  8642. return this._webGLVersion < 2 || this.forcePOTTextures;
  8643. },
  8644. enumerable: true,
  8645. configurable: true
  8646. });
  8647. Object.defineProperty(Engine.prototype, "badOS", {
  8648. get: function () {
  8649. return this._badOS;
  8650. },
  8651. enumerable: true,
  8652. configurable: true
  8653. });
  8654. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8655. get: function () {
  8656. return this._badDesktopOS;
  8657. },
  8658. enumerable: true,
  8659. configurable: true
  8660. });
  8661. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8662. get: function () {
  8663. return this._performanceMonitor;
  8664. },
  8665. enumerable: true,
  8666. configurable: true
  8667. });
  8668. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8669. get: function () {
  8670. return this._texturesSupported;
  8671. },
  8672. enumerable: true,
  8673. configurable: true
  8674. });
  8675. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8676. get: function () {
  8677. return this._textureFormatInUse;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(Engine.prototype, "currentViewport", {
  8683. get: function () {
  8684. return this._cachedViewport;
  8685. },
  8686. enumerable: true,
  8687. configurable: true
  8688. });
  8689. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8690. // Empty texture
  8691. get: function () {
  8692. if (!this._emptyTexture) {
  8693. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8694. }
  8695. return this._emptyTexture;
  8696. },
  8697. enumerable: true,
  8698. configurable: true
  8699. });
  8700. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8701. get: function () {
  8702. if (!this._emptyTexture3D) {
  8703. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8704. }
  8705. return this._emptyTexture3D;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8711. get: function () {
  8712. if (!this._emptyCubeTexture) {
  8713. var faceData = new Uint8Array(4);
  8714. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8715. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8716. }
  8717. return this._emptyCubeTexture;
  8718. },
  8719. enumerable: true,
  8720. configurable: true
  8721. });
  8722. Engine.prototype._rebuildInternalTextures = function () {
  8723. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8724. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8725. var internalTexture = currentState_1[_i];
  8726. internalTexture._rebuild();
  8727. }
  8728. };
  8729. Engine.prototype._rebuildEffects = function () {
  8730. for (var key in this._compiledEffects) {
  8731. var effect = this._compiledEffects[key];
  8732. effect._prepareEffect();
  8733. }
  8734. BABYLON.Effect.ResetCache();
  8735. };
  8736. Engine.prototype._rebuildBuffers = function () {
  8737. // Index / Vertex
  8738. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8739. var scene = _a[_i];
  8740. scene.resetCachedMaterial();
  8741. scene._rebuildGeometries();
  8742. scene._rebuildTextures();
  8743. }
  8744. // Uniforms
  8745. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8746. var uniformBuffer = _c[_b];
  8747. uniformBuffer._rebuild();
  8748. }
  8749. };
  8750. Engine.prototype._initGLContext = function () {
  8751. // Caps
  8752. this._caps = new EngineCapabilities();
  8753. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8754. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8755. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8756. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8757. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8758. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8759. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8760. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8761. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8762. // Infos
  8763. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8764. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8765. if (rendererInfo != null) {
  8766. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8767. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8768. }
  8769. if (!this._glVendor) {
  8770. this._glVendor = "Unknown vendor";
  8771. }
  8772. if (!this._glRenderer) {
  8773. this._glRenderer = "Unknown renderer";
  8774. }
  8775. // Constants
  8776. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8777. if (this._gl.RGBA16F !== 0x881A) {
  8778. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8779. }
  8780. if (this._gl.RGBA32F !== 0x8814) {
  8781. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8782. }
  8783. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8784. this._gl.DEPTH24_STENCIL8 = 35056;
  8785. }
  8786. // Extensions
  8787. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8788. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8789. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8790. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8791. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8792. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8793. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8794. 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');
  8795. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8796. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8797. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8798. this._caps.highPrecisionShaderSupported = true;
  8799. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8800. if (this._caps.timerQuery) {
  8801. if (this._webGLVersion === 1) {
  8802. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8803. }
  8804. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8805. }
  8806. // Checks if some of the format renders first to allow the use of webgl inspector.
  8807. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8808. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8809. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8810. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8811. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8812. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8813. if (this._webGLVersion > 1) {
  8814. this._gl.HALF_FLOAT_OES = 0x140B;
  8815. }
  8816. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8817. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8818. // Draw buffers
  8819. if (this._webGLVersion > 1) {
  8820. this._caps.drawBuffersExtension = true;
  8821. }
  8822. else {
  8823. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8824. if (drawBuffersExtension !== null) {
  8825. this._caps.drawBuffersExtension = true;
  8826. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8827. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8828. for (var i = 0; i < 16; i++) {
  8829. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8830. }
  8831. }
  8832. else {
  8833. this._caps.drawBuffersExtension = false;
  8834. }
  8835. }
  8836. // Depth Texture
  8837. if (this._webGLVersion > 1) {
  8838. this._caps.depthTextureExtension = true;
  8839. }
  8840. else {
  8841. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8842. if (depthTextureExtension != null) {
  8843. this._caps.depthTextureExtension = true;
  8844. }
  8845. }
  8846. // Vertex array object
  8847. if (this._webGLVersion > 1) {
  8848. this._caps.vertexArrayObject = true;
  8849. }
  8850. else {
  8851. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8852. if (vertexArrayObjectExtension != null) {
  8853. this._caps.vertexArrayObject = true;
  8854. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8855. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8856. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8857. }
  8858. else {
  8859. this._caps.vertexArrayObject = false;
  8860. }
  8861. }
  8862. // Instances count
  8863. if (this._webGLVersion > 1) {
  8864. this._caps.instancedArrays = true;
  8865. }
  8866. else {
  8867. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8868. if (instanceExtension != null) {
  8869. this._caps.instancedArrays = true;
  8870. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8871. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8872. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8873. }
  8874. else {
  8875. this._caps.instancedArrays = false;
  8876. }
  8877. }
  8878. // Intelligently add supported compressed formats in order to check for.
  8879. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8880. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8881. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8882. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8883. if (this._caps.astc)
  8884. this.texturesSupported.push('-astc.ktx');
  8885. if (this._caps.s3tc)
  8886. this.texturesSupported.push('-dxt.ktx');
  8887. if (this._caps.pvrtc)
  8888. this.texturesSupported.push('-pvrtc.ktx');
  8889. if (this._caps.etc2)
  8890. this.texturesSupported.push('-etc2.ktx');
  8891. if (this._caps.etc1)
  8892. this.texturesSupported.push('-etc1.ktx');
  8893. if (this._gl.getShaderPrecisionFormat) {
  8894. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8895. if (highp) {
  8896. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8897. }
  8898. }
  8899. // Depth buffer
  8900. this.setDepthBuffer(true);
  8901. this.setDepthFunctionToLessOrEqual();
  8902. this.setDepthWrite(true);
  8903. };
  8904. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8905. get: function () {
  8906. return this._webGLVersion;
  8907. },
  8908. enumerable: true,
  8909. configurable: true
  8910. });
  8911. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8912. /**
  8913. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8914. */
  8915. get: function () {
  8916. return this._isStencilEnable;
  8917. },
  8918. enumerable: true,
  8919. configurable: true
  8920. });
  8921. Engine.prototype._prepareWorkingCanvas = function () {
  8922. if (this._workingCanvas) {
  8923. return;
  8924. }
  8925. this._workingCanvas = document.createElement("canvas");
  8926. var context = this._workingCanvas.getContext("2d");
  8927. if (context) {
  8928. this._workingContext = context;
  8929. }
  8930. };
  8931. Engine.prototype.resetTextureCache = function () {
  8932. for (var key in this._boundTexturesCache) {
  8933. var boundTexture = this._boundTexturesCache[key];
  8934. if (boundTexture) {
  8935. this._removeDesignatedSlot(boundTexture);
  8936. }
  8937. this._boundTexturesCache[key] = null;
  8938. }
  8939. this._nextFreeTextureSlot = 0;
  8940. this._activeChannel = -1;
  8941. };
  8942. Engine.prototype.isDeterministicLockStep = function () {
  8943. return this._deterministicLockstep;
  8944. };
  8945. Engine.prototype.getLockstepMaxSteps = function () {
  8946. return this._lockstepMaxSteps;
  8947. };
  8948. Engine.prototype.getGlInfo = function () {
  8949. return {
  8950. vendor: this._glVendor,
  8951. renderer: this._glRenderer,
  8952. version: this._glVersion
  8953. };
  8954. };
  8955. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8956. if (useScreen === void 0) { useScreen = false; }
  8957. var viewport = camera.viewport;
  8958. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8959. };
  8960. Engine.prototype.getRenderWidth = function (useScreen) {
  8961. if (useScreen === void 0) { useScreen = false; }
  8962. if (!useScreen && this._currentRenderTarget) {
  8963. return this._currentRenderTarget.width;
  8964. }
  8965. return this._gl.drawingBufferWidth;
  8966. };
  8967. Engine.prototype.getRenderHeight = function (useScreen) {
  8968. if (useScreen === void 0) { useScreen = false; }
  8969. if (!useScreen && this._currentRenderTarget) {
  8970. return this._currentRenderTarget.height;
  8971. }
  8972. return this._gl.drawingBufferHeight;
  8973. };
  8974. Engine.prototype.getRenderingCanvas = function () {
  8975. return this._renderingCanvas;
  8976. };
  8977. Engine.prototype.getRenderingCanvasClientRect = function () {
  8978. if (!this._renderingCanvas) {
  8979. return null;
  8980. }
  8981. return this._renderingCanvas.getBoundingClientRect();
  8982. };
  8983. Engine.prototype.setHardwareScalingLevel = function (level) {
  8984. this._hardwareScalingLevel = level;
  8985. this.resize();
  8986. };
  8987. Engine.prototype.getHardwareScalingLevel = function () {
  8988. return this._hardwareScalingLevel;
  8989. };
  8990. Engine.prototype.getLoadedTexturesCache = function () {
  8991. return this._internalTexturesCache;
  8992. };
  8993. Engine.prototype.getCaps = function () {
  8994. return this._caps;
  8995. };
  8996. Object.defineProperty(Engine.prototype, "drawCalls", {
  8997. /** The number of draw calls submitted last frame */
  8998. get: function () {
  8999. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9000. return 0;
  9001. },
  9002. enumerable: true,
  9003. configurable: true
  9004. });
  9005. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9006. get: function () {
  9007. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9008. return null;
  9009. },
  9010. enumerable: true,
  9011. configurable: true
  9012. });
  9013. Engine.prototype.getDepthFunction = function () {
  9014. return this._depthCullingState.depthFunc;
  9015. };
  9016. Engine.prototype.setDepthFunction = function (depthFunc) {
  9017. this._depthCullingState.depthFunc = depthFunc;
  9018. };
  9019. Engine.prototype.setDepthFunctionToGreater = function () {
  9020. this._depthCullingState.depthFunc = this._gl.GREATER;
  9021. };
  9022. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9023. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9024. };
  9025. Engine.prototype.setDepthFunctionToLess = function () {
  9026. this._depthCullingState.depthFunc = this._gl.LESS;
  9027. };
  9028. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9029. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9030. };
  9031. Engine.prototype.getStencilBuffer = function () {
  9032. return this._stencilState.stencilTest;
  9033. };
  9034. Engine.prototype.setStencilBuffer = function (enable) {
  9035. this._stencilState.stencilTest = enable;
  9036. };
  9037. Engine.prototype.getStencilMask = function () {
  9038. return this._stencilState.stencilMask;
  9039. };
  9040. Engine.prototype.setStencilMask = function (mask) {
  9041. this._stencilState.stencilMask = mask;
  9042. };
  9043. Engine.prototype.getStencilFunction = function () {
  9044. return this._stencilState.stencilFunc;
  9045. };
  9046. Engine.prototype.getStencilFunctionReference = function () {
  9047. return this._stencilState.stencilFuncRef;
  9048. };
  9049. Engine.prototype.getStencilFunctionMask = function () {
  9050. return this._stencilState.stencilFuncMask;
  9051. };
  9052. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9053. this._stencilState.stencilFunc = stencilFunc;
  9054. };
  9055. Engine.prototype.setStencilFunctionReference = function (reference) {
  9056. this._stencilState.stencilFuncRef = reference;
  9057. };
  9058. Engine.prototype.setStencilFunctionMask = function (mask) {
  9059. this._stencilState.stencilFuncMask = mask;
  9060. };
  9061. Engine.prototype.getStencilOperationFail = function () {
  9062. return this._stencilState.stencilOpStencilFail;
  9063. };
  9064. Engine.prototype.getStencilOperationDepthFail = function () {
  9065. return this._stencilState.stencilOpDepthFail;
  9066. };
  9067. Engine.prototype.getStencilOperationPass = function () {
  9068. return this._stencilState.stencilOpStencilDepthPass;
  9069. };
  9070. Engine.prototype.setStencilOperationFail = function (operation) {
  9071. this._stencilState.stencilOpStencilFail = operation;
  9072. };
  9073. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9074. this._stencilState.stencilOpDepthFail = operation;
  9075. };
  9076. Engine.prototype.setStencilOperationPass = function (operation) {
  9077. this._stencilState.stencilOpStencilDepthPass = operation;
  9078. };
  9079. Engine.prototype.setDitheringState = function (value) {
  9080. if (value) {
  9081. this._gl.enable(this._gl.DITHER);
  9082. }
  9083. else {
  9084. this._gl.disable(this._gl.DITHER);
  9085. }
  9086. };
  9087. Engine.prototype.setRasterizerState = function (value) {
  9088. if (value) {
  9089. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9090. }
  9091. else {
  9092. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9093. }
  9094. };
  9095. /**
  9096. * stop executing a render loop function and remove it from the execution array
  9097. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9098. */
  9099. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9100. if (!renderFunction) {
  9101. this._activeRenderLoops = [];
  9102. return;
  9103. }
  9104. var index = this._activeRenderLoops.indexOf(renderFunction);
  9105. if (index >= 0) {
  9106. this._activeRenderLoops.splice(index, 1);
  9107. }
  9108. };
  9109. Engine.prototype._renderLoop = function () {
  9110. if (!this._contextWasLost) {
  9111. var shouldRender = true;
  9112. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9113. shouldRender = false;
  9114. }
  9115. if (shouldRender) {
  9116. // Start new frame
  9117. this.beginFrame();
  9118. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9119. var renderFunction = this._activeRenderLoops[index];
  9120. renderFunction();
  9121. }
  9122. // Present
  9123. this.endFrame();
  9124. }
  9125. }
  9126. if (this._activeRenderLoops.length > 0) {
  9127. // Register new frame
  9128. var requester = null;
  9129. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9130. requester = this._vrDisplay;
  9131. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9132. }
  9133. else {
  9134. this._renderingQueueLaunched = false;
  9135. }
  9136. };
  9137. /**
  9138. * Register and execute a render loop. The engine can have more than one render function.
  9139. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9140. * @example
  9141. * engine.runRenderLoop(function () {
  9142. * scene.render()
  9143. * })
  9144. */
  9145. Engine.prototype.runRenderLoop = function (renderFunction) {
  9146. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9147. return;
  9148. }
  9149. this._activeRenderLoops.push(renderFunction);
  9150. if (!this._renderingQueueLaunched) {
  9151. this._renderingQueueLaunched = true;
  9152. this._bindedRenderFunction = this._renderLoop.bind(this);
  9153. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9154. }
  9155. };
  9156. /**
  9157. * Toggle full screen mode.
  9158. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9159. * @param {any} options - an options object to be sent to the requestFullscreen function
  9160. */
  9161. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9162. if (this.isFullscreen) {
  9163. BABYLON.Tools.ExitFullscreen();
  9164. }
  9165. else {
  9166. this._pointerLockRequested = requestPointerLock;
  9167. if (this._renderingCanvas) {
  9168. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9169. }
  9170. }
  9171. };
  9172. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9173. if (stencil === void 0) { stencil = false; }
  9174. this.applyStates();
  9175. var mode = 0;
  9176. if (backBuffer && color) {
  9177. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9178. mode |= this._gl.COLOR_BUFFER_BIT;
  9179. }
  9180. if (depth) {
  9181. this._gl.clearDepth(1.0);
  9182. mode |= this._gl.DEPTH_BUFFER_BIT;
  9183. }
  9184. if (stencil) {
  9185. this._gl.clearStencil(0);
  9186. mode |= this._gl.STENCIL_BUFFER_BIT;
  9187. }
  9188. this._gl.clear(mode);
  9189. };
  9190. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9191. var gl = this._gl;
  9192. // Save state
  9193. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9194. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9195. // Change state
  9196. gl.enable(gl.SCISSOR_TEST);
  9197. gl.scissor(x, y, width, height);
  9198. // Clear
  9199. this.clear(clearColor, true, true, true);
  9200. // Restore state
  9201. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9202. if (curScissor === true) {
  9203. gl.enable(gl.SCISSOR_TEST);
  9204. }
  9205. else {
  9206. gl.disable(gl.SCISSOR_TEST);
  9207. }
  9208. };
  9209. /**
  9210. * Set the WebGL's viewport
  9211. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9212. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9213. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9214. */
  9215. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9216. var width = requiredWidth || this.getRenderWidth();
  9217. var height = requiredHeight || this.getRenderHeight();
  9218. var x = viewport.x || 0;
  9219. var y = viewport.y || 0;
  9220. this._cachedViewport = viewport;
  9221. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9222. };
  9223. /**
  9224. * Directly set the WebGL Viewport
  9225. * The x, y, width & height are directly passed to the WebGL call
  9226. * @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.
  9227. */
  9228. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9229. var currentViewport = this._cachedViewport;
  9230. this._cachedViewport = null;
  9231. this._gl.viewport(x, y, width, height);
  9232. return currentViewport;
  9233. };
  9234. Engine.prototype.beginFrame = function () {
  9235. this.onBeginFrameObservable.notifyObservers(this);
  9236. this._measureFps();
  9237. };
  9238. Engine.prototype.endFrame = function () {
  9239. //force a flush in case we are using a bad OS.
  9240. if (this._badOS) {
  9241. this.flushFramebuffer();
  9242. }
  9243. //submit frame to the vr device, if enabled
  9244. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9245. // TODO: We should only submit the frame if we read frameData successfully.
  9246. this._vrDisplay.submitFrame();
  9247. }
  9248. this.onEndFrameObservable.notifyObservers(this);
  9249. };
  9250. /**
  9251. * resize the view according to the canvas' size.
  9252. * @example
  9253. * window.addEventListener("resize", function () {
  9254. * engine.resize();
  9255. * });
  9256. */
  9257. Engine.prototype.resize = function () {
  9258. // We're not resizing the size of the canvas while in VR mode & presenting
  9259. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9260. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9261. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9262. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9263. }
  9264. };
  9265. /**
  9266. * force a specific size of the canvas
  9267. * @param {number} width - the new canvas' width
  9268. * @param {number} height - the new canvas' height
  9269. */
  9270. Engine.prototype.setSize = function (width, height) {
  9271. if (!this._renderingCanvas) {
  9272. return;
  9273. }
  9274. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9275. return;
  9276. }
  9277. this._renderingCanvas.width = width;
  9278. this._renderingCanvas.height = height;
  9279. for (var index = 0; index < this.scenes.length; index++) {
  9280. var scene = this.scenes[index];
  9281. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9282. var cam = scene.cameras[camIndex];
  9283. cam._currentRenderId = 0;
  9284. }
  9285. }
  9286. if (this.onResizeObservable.hasObservers) {
  9287. this.onResizeObservable.notifyObservers(this);
  9288. }
  9289. };
  9290. // WebVR functions
  9291. Engine.prototype.isVRDevicePresent = function () {
  9292. return !!this._vrDisplay;
  9293. };
  9294. Engine.prototype.getVRDevice = function () {
  9295. return this._vrDisplay;
  9296. };
  9297. Engine.prototype.initWebVR = function () {
  9298. var _this = this;
  9299. var notifyObservers = function () {
  9300. var eventArgs = {
  9301. vrDisplay: _this._vrDisplay,
  9302. vrSupported: _this._vrSupported
  9303. };
  9304. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9305. };
  9306. if (!this._onVrDisplayConnect) {
  9307. this._onVrDisplayConnect = function (event) {
  9308. _this._vrDisplay = event.display;
  9309. notifyObservers();
  9310. };
  9311. this._onVrDisplayDisconnect = function () {
  9312. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9313. _this._vrDisplay = undefined;
  9314. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9315. notifyObservers();
  9316. };
  9317. this._onVrDisplayPresentChange = function () {
  9318. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9319. };
  9320. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9321. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9322. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9323. }
  9324. this._getVRDisplays(notifyObservers);
  9325. return this.onVRDisplayChangedObservable;
  9326. };
  9327. Engine.prototype.enableVR = function () {
  9328. var _this = this;
  9329. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9330. var onResolved = function () {
  9331. _this.onVRRequestPresentComplete.notifyObservers(true);
  9332. _this._onVRFullScreenTriggered();
  9333. };
  9334. var onRejected = function () {
  9335. _this.onVRRequestPresentComplete.notifyObservers(false);
  9336. };
  9337. this.onVRRequestPresentStart.notifyObservers(this);
  9338. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9339. }
  9340. };
  9341. Engine.prototype.disableVR = function () {
  9342. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9343. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9344. }
  9345. };
  9346. Engine.prototype._getVRDisplays = function (callback) {
  9347. var _this = this;
  9348. var getWebVRDevices = function (devices) {
  9349. _this._vrSupported = true;
  9350. // note that devices may actually be an empty array. This is fine;
  9351. // we expect this._vrDisplay to be undefined in this case.
  9352. return _this._vrDisplay = devices[0];
  9353. };
  9354. if (navigator.getVRDisplays) {
  9355. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9356. // TODO: System CANNOT support WebVR, despite API presence.
  9357. _this._vrSupported = false;
  9358. callback();
  9359. });
  9360. }
  9361. else {
  9362. // TODO: Browser does not support WebVR
  9363. this._vrDisplay = undefined;
  9364. this._vrSupported = false;
  9365. callback();
  9366. }
  9367. };
  9368. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9369. if (this._currentRenderTarget) {
  9370. this.unBindFramebuffer(this._currentRenderTarget);
  9371. }
  9372. this._currentRenderTarget = texture;
  9373. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9374. var gl = this._gl;
  9375. if (texture.isCube) {
  9376. if (faceIndex === undefined) {
  9377. faceIndex = 0;
  9378. }
  9379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9380. }
  9381. if (this._cachedViewport && !forceFullscreenViewport) {
  9382. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9383. }
  9384. else {
  9385. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9386. }
  9387. this.wipeCaches();
  9388. };
  9389. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9390. if (this._currentFramebuffer !== framebuffer) {
  9391. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9392. this._currentFramebuffer = framebuffer;
  9393. }
  9394. };
  9395. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9396. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9397. this._currentRenderTarget = null;
  9398. // If MSAA, we need to bitblt back to main texture
  9399. var gl = this._gl;
  9400. if (texture._MSAAFramebuffer) {
  9401. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9402. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9403. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9404. }
  9405. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9406. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9407. gl.generateMipmap(gl.TEXTURE_2D);
  9408. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9409. }
  9410. if (onBeforeUnbind) {
  9411. if (texture._MSAAFramebuffer) {
  9412. // Bind the correct framebuffer
  9413. this.bindUnboundFramebuffer(texture._framebuffer);
  9414. }
  9415. onBeforeUnbind();
  9416. }
  9417. this.bindUnboundFramebuffer(null);
  9418. };
  9419. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9420. if (texture.generateMipMaps) {
  9421. var gl = this._gl;
  9422. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9423. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9424. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9425. }
  9426. };
  9427. Engine.prototype.flushFramebuffer = function () {
  9428. this._gl.flush();
  9429. };
  9430. Engine.prototype.restoreDefaultFramebuffer = function () {
  9431. if (this._currentRenderTarget) {
  9432. this.unBindFramebuffer(this._currentRenderTarget);
  9433. }
  9434. else {
  9435. this.bindUnboundFramebuffer(null);
  9436. }
  9437. if (this._cachedViewport) {
  9438. this.setViewport(this._cachedViewport);
  9439. }
  9440. this.wipeCaches();
  9441. };
  9442. // UBOs
  9443. Engine.prototype.createUniformBuffer = function (elements) {
  9444. var ubo = this._gl.createBuffer();
  9445. if (!ubo) {
  9446. throw new Error("Unable to create uniform buffer");
  9447. }
  9448. this.bindUniformBuffer(ubo);
  9449. if (elements instanceof Float32Array) {
  9450. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9451. }
  9452. else {
  9453. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9454. }
  9455. this.bindUniformBuffer(null);
  9456. ubo.references = 1;
  9457. return ubo;
  9458. };
  9459. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9460. var ubo = this._gl.createBuffer();
  9461. if (!ubo) {
  9462. throw new Error("Unable to create dynamic uniform buffer");
  9463. }
  9464. this.bindUniformBuffer(ubo);
  9465. if (elements instanceof Float32Array) {
  9466. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9467. }
  9468. else {
  9469. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9470. }
  9471. this.bindUniformBuffer(null);
  9472. ubo.references = 1;
  9473. return ubo;
  9474. };
  9475. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9476. this.bindUniformBuffer(uniformBuffer);
  9477. if (offset === undefined) {
  9478. offset = 0;
  9479. }
  9480. if (count === undefined) {
  9481. if (elements instanceof Float32Array) {
  9482. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9483. }
  9484. else {
  9485. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9486. }
  9487. }
  9488. else {
  9489. if (elements instanceof Float32Array) {
  9490. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9491. }
  9492. else {
  9493. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9494. }
  9495. }
  9496. this.bindUniformBuffer(null);
  9497. };
  9498. // VBOs
  9499. Engine.prototype._resetVertexBufferBinding = function () {
  9500. this.bindArrayBuffer(null);
  9501. this._cachedVertexBuffers = null;
  9502. };
  9503. Engine.prototype.createVertexBuffer = function (vertices) {
  9504. var vbo = this._gl.createBuffer();
  9505. if (!vbo) {
  9506. throw new Error("Unable to create vertex buffer");
  9507. }
  9508. this.bindArrayBuffer(vbo);
  9509. if (vertices instanceof Float32Array) {
  9510. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9511. }
  9512. else {
  9513. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9514. }
  9515. this._resetVertexBufferBinding();
  9516. vbo.references = 1;
  9517. return vbo;
  9518. };
  9519. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9520. var vbo = this._gl.createBuffer();
  9521. if (!vbo) {
  9522. throw new Error("Unable to create dynamic vertex buffer");
  9523. }
  9524. this.bindArrayBuffer(vbo);
  9525. if (vertices instanceof Float32Array) {
  9526. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9527. }
  9528. else {
  9529. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9530. }
  9531. this._resetVertexBufferBinding();
  9532. vbo.references = 1;
  9533. return vbo;
  9534. };
  9535. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9536. if (offset === void 0) { offset = 0; }
  9537. // Force cache update
  9538. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9539. this.bindIndexBuffer(indexBuffer);
  9540. var arrayBuffer;
  9541. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9542. arrayBuffer = indices;
  9543. }
  9544. else {
  9545. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9546. }
  9547. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9548. this._resetIndexBufferBinding();
  9549. };
  9550. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9551. this.bindArrayBuffer(vertexBuffer);
  9552. if (offset === undefined) {
  9553. offset = 0;
  9554. }
  9555. if (count === undefined) {
  9556. if (vertices instanceof Float32Array) {
  9557. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9558. }
  9559. else {
  9560. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9561. }
  9562. }
  9563. else {
  9564. if (vertices instanceof Float32Array) {
  9565. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9566. }
  9567. else {
  9568. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9569. }
  9570. }
  9571. this._resetVertexBufferBinding();
  9572. };
  9573. Engine.prototype._resetIndexBufferBinding = function () {
  9574. this.bindIndexBuffer(null);
  9575. this._cachedIndexBuffer = null;
  9576. };
  9577. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9578. var vbo = this._gl.createBuffer();
  9579. if (!vbo) {
  9580. throw new Error("Unable to create index buffer");
  9581. }
  9582. this.bindIndexBuffer(vbo);
  9583. // Check for 32 bits indices
  9584. var arrayBuffer;
  9585. var need32Bits = false;
  9586. if (indices instanceof Uint16Array) {
  9587. arrayBuffer = indices;
  9588. }
  9589. else {
  9590. //check 32 bit support
  9591. if (this._caps.uintIndices) {
  9592. if (indices instanceof Uint32Array) {
  9593. arrayBuffer = indices;
  9594. need32Bits = true;
  9595. }
  9596. else {
  9597. //number[] or Int32Array, check if 32 bit is necessary
  9598. for (var index = 0; index < indices.length; index++) {
  9599. if (indices[index] > 65535) {
  9600. need32Bits = true;
  9601. break;
  9602. }
  9603. }
  9604. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9605. }
  9606. }
  9607. else {
  9608. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9609. arrayBuffer = new Uint16Array(indices);
  9610. }
  9611. }
  9612. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9613. this._resetIndexBufferBinding();
  9614. vbo.references = 1;
  9615. vbo.is32Bits = need32Bits;
  9616. return vbo;
  9617. };
  9618. Engine.prototype.bindArrayBuffer = function (buffer) {
  9619. if (!this._vaoRecordInProgress) {
  9620. this._unbindVertexArrayObject();
  9621. }
  9622. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9623. };
  9624. Engine.prototype.bindUniformBuffer = function (buffer) {
  9625. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9626. };
  9627. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9628. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9629. };
  9630. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9631. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9632. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9633. };
  9634. ;
  9635. Engine.prototype.bindIndexBuffer = function (buffer) {
  9636. if (!this._vaoRecordInProgress) {
  9637. this._unbindVertexArrayObject();
  9638. }
  9639. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9640. };
  9641. Engine.prototype.bindBuffer = function (buffer, target) {
  9642. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9643. this._gl.bindBuffer(target, buffer);
  9644. this._currentBoundBuffer[target] = buffer;
  9645. }
  9646. };
  9647. Engine.prototype.updateArrayBuffer = function (data) {
  9648. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9649. };
  9650. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9651. var pointer = this._currentBufferPointers[indx];
  9652. var changed = false;
  9653. if (!pointer.active) {
  9654. changed = true;
  9655. pointer.active = true;
  9656. pointer.index = indx;
  9657. pointer.size = size;
  9658. pointer.type = type;
  9659. pointer.normalized = normalized;
  9660. pointer.stride = stride;
  9661. pointer.offset = offset;
  9662. pointer.buffer = buffer;
  9663. }
  9664. else {
  9665. if (pointer.buffer !== buffer) {
  9666. pointer.buffer = buffer;
  9667. changed = true;
  9668. }
  9669. if (pointer.size !== size) {
  9670. pointer.size = size;
  9671. changed = true;
  9672. }
  9673. if (pointer.type !== type) {
  9674. pointer.type = type;
  9675. changed = true;
  9676. }
  9677. if (pointer.normalized !== normalized) {
  9678. pointer.normalized = normalized;
  9679. changed = true;
  9680. }
  9681. if (pointer.stride !== stride) {
  9682. pointer.stride = stride;
  9683. changed = true;
  9684. }
  9685. if (pointer.offset !== offset) {
  9686. pointer.offset = offset;
  9687. changed = true;
  9688. }
  9689. }
  9690. if (changed || this._vaoRecordInProgress) {
  9691. this.bindArrayBuffer(buffer);
  9692. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9693. }
  9694. };
  9695. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9696. if (indexBuffer == null) {
  9697. return;
  9698. }
  9699. if (this._cachedIndexBuffer !== indexBuffer) {
  9700. this._cachedIndexBuffer = indexBuffer;
  9701. this.bindIndexBuffer(indexBuffer);
  9702. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9703. }
  9704. };
  9705. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9706. var attributes = effect.getAttributesNames();
  9707. if (!this._vaoRecordInProgress) {
  9708. this._unbindVertexArrayObject();
  9709. }
  9710. this.unbindAllAttributes();
  9711. for (var index = 0; index < attributes.length; index++) {
  9712. var order = effect.getAttributeLocation(index);
  9713. if (order >= 0) {
  9714. var vertexBuffer = vertexBuffers[attributes[index]];
  9715. if (!vertexBuffer) {
  9716. continue;
  9717. }
  9718. this._gl.enableVertexAttribArray(order);
  9719. if (!this._vaoRecordInProgress) {
  9720. this._vertexAttribArraysEnabled[order] = true;
  9721. }
  9722. var buffer = vertexBuffer.getBuffer();
  9723. if (buffer) {
  9724. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9725. if (vertexBuffer.getIsInstanced()) {
  9726. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9727. if (!this._vaoRecordInProgress) {
  9728. this._currentInstanceLocations.push(order);
  9729. this._currentInstanceBuffers.push(buffer);
  9730. }
  9731. }
  9732. }
  9733. }
  9734. }
  9735. };
  9736. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9737. var vao = this._gl.createVertexArray();
  9738. this._vaoRecordInProgress = true;
  9739. this._gl.bindVertexArray(vao);
  9740. this._mustWipeVertexAttributes = true;
  9741. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9742. this.bindIndexBuffer(indexBuffer);
  9743. this._vaoRecordInProgress = false;
  9744. this._gl.bindVertexArray(null);
  9745. return vao;
  9746. };
  9747. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9748. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9749. this._cachedVertexArrayObject = vertexArrayObject;
  9750. this._gl.bindVertexArray(vertexArrayObject);
  9751. this._cachedVertexBuffers = null;
  9752. this._cachedIndexBuffer = null;
  9753. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9754. this._mustWipeVertexAttributes = true;
  9755. }
  9756. };
  9757. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9758. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9759. this._cachedVertexBuffers = vertexBuffer;
  9760. this._cachedEffectForVertexBuffers = effect;
  9761. var attributesCount = effect.getAttributesCount();
  9762. this._unbindVertexArrayObject();
  9763. this.unbindAllAttributes();
  9764. var offset = 0;
  9765. for (var index = 0; index < attributesCount; index++) {
  9766. if (index < vertexDeclaration.length) {
  9767. var order = effect.getAttributeLocation(index);
  9768. if (order >= 0) {
  9769. this._gl.enableVertexAttribArray(order);
  9770. this._vertexAttribArraysEnabled[order] = true;
  9771. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9772. }
  9773. offset += vertexDeclaration[index] * 4;
  9774. }
  9775. }
  9776. }
  9777. this._bindIndexBufferWithCache(indexBuffer);
  9778. };
  9779. Engine.prototype._unbindVertexArrayObject = function () {
  9780. if (!this._cachedVertexArrayObject) {
  9781. return;
  9782. }
  9783. this._cachedVertexArrayObject = null;
  9784. this._gl.bindVertexArray(null);
  9785. };
  9786. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9787. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9788. this._cachedVertexBuffers = vertexBuffers;
  9789. this._cachedEffectForVertexBuffers = effect;
  9790. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9791. }
  9792. this._bindIndexBufferWithCache(indexBuffer);
  9793. };
  9794. Engine.prototype.unbindInstanceAttributes = function () {
  9795. var boundBuffer;
  9796. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9797. var instancesBuffer = this._currentInstanceBuffers[i];
  9798. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9799. boundBuffer = instancesBuffer;
  9800. this.bindArrayBuffer(instancesBuffer);
  9801. }
  9802. var offsetLocation = this._currentInstanceLocations[i];
  9803. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9804. }
  9805. this._currentInstanceBuffers.length = 0;
  9806. this._currentInstanceLocations.length = 0;
  9807. };
  9808. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9809. this._gl.deleteVertexArray(vao);
  9810. };
  9811. Engine.prototype._releaseBuffer = function (buffer) {
  9812. buffer.references--;
  9813. if (buffer.references === 0) {
  9814. this._gl.deleteBuffer(buffer);
  9815. return true;
  9816. }
  9817. return false;
  9818. };
  9819. Engine.prototype.createInstancesBuffer = function (capacity) {
  9820. var buffer = this._gl.createBuffer();
  9821. if (!buffer) {
  9822. throw new Error("Unable to create instance buffer");
  9823. }
  9824. buffer.capacity = capacity;
  9825. this.bindArrayBuffer(buffer);
  9826. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9827. return buffer;
  9828. };
  9829. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9830. this._gl.deleteBuffer(buffer);
  9831. };
  9832. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9833. this.bindArrayBuffer(instancesBuffer);
  9834. if (data) {
  9835. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9836. }
  9837. if (offsetLocations[0].index !== undefined) {
  9838. var stride = 0;
  9839. for (var i = 0; i < offsetLocations.length; i++) {
  9840. var ai = offsetLocations[i];
  9841. stride += ai.attributeSize * 4;
  9842. }
  9843. for (var i = 0; i < offsetLocations.length; i++) {
  9844. var ai = offsetLocations[i];
  9845. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9846. this._gl.enableVertexAttribArray(ai.index);
  9847. this._vertexAttribArraysEnabled[ai.index] = true;
  9848. }
  9849. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9850. this._gl.vertexAttribDivisor(ai.index, 1);
  9851. this._currentInstanceLocations.push(ai.index);
  9852. this._currentInstanceBuffers.push(instancesBuffer);
  9853. }
  9854. }
  9855. else {
  9856. for (var index = 0; index < 4; index++) {
  9857. var offsetLocation = offsetLocations[index];
  9858. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9859. this._gl.enableVertexAttribArray(offsetLocation);
  9860. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9861. }
  9862. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9863. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9864. this._currentInstanceLocations.push(offsetLocation);
  9865. this._currentInstanceBuffers.push(instancesBuffer);
  9866. }
  9867. }
  9868. };
  9869. Engine.prototype.applyStates = function () {
  9870. this._depthCullingState.apply(this._gl);
  9871. this._stencilState.apply(this._gl);
  9872. this._alphaState.apply(this._gl);
  9873. };
  9874. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9875. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  9876. };
  9877. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9878. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  9879. };
  9880. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9881. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  9882. };
  9883. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  9884. // Apply states
  9885. this.applyStates();
  9886. this._drawCalls.addCount(1, false);
  9887. // Render
  9888. var drawMode = this.DrawMode(fillMode);
  9889. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9890. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9891. if (instancesCount) {
  9892. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  9893. }
  9894. else {
  9895. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  9896. }
  9897. };
  9898. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  9899. // Apply states
  9900. this.applyStates();
  9901. this._drawCalls.addCount(1, false);
  9902. var drawMode = this.DrawMode(fillMode);
  9903. if (instancesCount) {
  9904. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  9905. }
  9906. else {
  9907. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  9908. }
  9909. };
  9910. Engine.prototype.DrawMode = function (fillMode) {
  9911. switch (fillMode) {
  9912. // Triangle views
  9913. case BABYLON.Material.TriangleFillMode:
  9914. return this._gl.TRIANGLES;
  9915. case BABYLON.Material.PointFillMode:
  9916. return this._gl.POINTS;
  9917. case BABYLON.Material.WireFrameFillMode:
  9918. return this._gl.LINES;
  9919. // Draw modes
  9920. case BABYLON.Material.PointListDrawMode:
  9921. return this._gl.POINTS;
  9922. case BABYLON.Material.LineListDrawMode:
  9923. return this._gl.LINES;
  9924. case BABYLON.Material.LineLoopDrawMode:
  9925. return this._gl.LINE_LOOP;
  9926. case BABYLON.Material.LineStripDrawMode:
  9927. return this._gl.LINE_STRIP;
  9928. case BABYLON.Material.TriangleStripDrawMode:
  9929. return this._gl.TRIANGLE_STRIP;
  9930. case BABYLON.Material.TriangleFanDrawMode:
  9931. return this._gl.TRIANGLE_FAN;
  9932. default:
  9933. return this._gl.TRIANGLES;
  9934. }
  9935. };
  9936. // Shaders
  9937. Engine.prototype._releaseEffect = function (effect) {
  9938. if (this._compiledEffects[effect._key]) {
  9939. delete this._compiledEffects[effect._key];
  9940. this._deleteProgram(effect.getProgram());
  9941. }
  9942. };
  9943. Engine.prototype._deleteProgram = function (program) {
  9944. if (program) {
  9945. program.__SPECTOR_rebuildProgram = null;
  9946. if (program.transformFeedback) {
  9947. this.deleteTransformFeedback(program.transformFeedback);
  9948. program.transformFeedback = null;
  9949. }
  9950. this._gl.deleteProgram(program);
  9951. }
  9952. };
  9953. /**
  9954. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9955. * @param samplers An array of string used to represent textures
  9956. */
  9957. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9958. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9959. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9960. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9961. if (this._compiledEffects[name]) {
  9962. var compiledEffect = this._compiledEffects[name];
  9963. if (onCompiled && compiledEffect.isReady()) {
  9964. onCompiled(compiledEffect);
  9965. }
  9966. return compiledEffect;
  9967. }
  9968. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9969. effect._key = name;
  9970. this._compiledEffects[name] = effect;
  9971. return effect;
  9972. };
  9973. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9974. if (uniformsNames === void 0) { uniformsNames = []; }
  9975. if (samplers === void 0) { samplers = []; }
  9976. if (defines === void 0) { defines = ""; }
  9977. return this.createEffect({
  9978. vertex: "particles",
  9979. fragmentElement: fragmentName
  9980. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9981. };
  9982. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9983. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9984. context = context || this._gl;
  9985. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9986. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9987. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9988. };
  9989. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9990. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9991. context = context || this._gl;
  9992. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9993. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9994. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9995. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9996. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9997. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9998. return program;
  9999. };
  10000. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10001. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10002. var shaderProgram = context.createProgram();
  10003. if (!shaderProgram) {
  10004. throw new Error("Unable to create program");
  10005. }
  10006. context.attachShader(shaderProgram, vertexShader);
  10007. context.attachShader(shaderProgram, fragmentShader);
  10008. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10009. var transformFeedback = this.createTransformFeedback();
  10010. this.bindTransformFeedback(transformFeedback);
  10011. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10012. shaderProgram.transformFeedback = transformFeedback;
  10013. }
  10014. context.linkProgram(shaderProgram);
  10015. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10016. this.bindTransformFeedback(null);
  10017. }
  10018. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10019. if (!linked) {
  10020. context.validateProgram(shaderProgram);
  10021. var error = context.getProgramInfoLog(shaderProgram);
  10022. if (error) {
  10023. throw new Error(error);
  10024. }
  10025. }
  10026. context.deleteShader(vertexShader);
  10027. context.deleteShader(fragmentShader);
  10028. return shaderProgram;
  10029. };
  10030. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10031. var results = new Array();
  10032. for (var index = 0; index < uniformsNames.length; index++) {
  10033. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10034. }
  10035. return results;
  10036. };
  10037. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10038. var results = [];
  10039. for (var index = 0; index < attributesNames.length; index++) {
  10040. try {
  10041. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10042. }
  10043. catch (e) {
  10044. results.push(-1);
  10045. }
  10046. }
  10047. return results;
  10048. };
  10049. Engine.prototype.enableEffect = function (effect) {
  10050. if (!effect) {
  10051. return;
  10052. }
  10053. // Use program
  10054. this.bindSamplers(effect);
  10055. this._currentEffect = effect;
  10056. if (effect.onBind) {
  10057. effect.onBind(effect);
  10058. }
  10059. effect.onBindObservable.notifyObservers(effect);
  10060. };
  10061. Engine.prototype.setIntArray = function (uniform, array) {
  10062. if (!uniform)
  10063. return;
  10064. this._gl.uniform1iv(uniform, array);
  10065. };
  10066. Engine.prototype.setIntArray2 = function (uniform, array) {
  10067. if (!uniform || array.length % 2 !== 0)
  10068. return;
  10069. this._gl.uniform2iv(uniform, array);
  10070. };
  10071. Engine.prototype.setIntArray3 = function (uniform, array) {
  10072. if (!uniform || array.length % 3 !== 0)
  10073. return;
  10074. this._gl.uniform3iv(uniform, array);
  10075. };
  10076. Engine.prototype.setIntArray4 = function (uniform, array) {
  10077. if (!uniform || array.length % 4 !== 0)
  10078. return;
  10079. this._gl.uniform4iv(uniform, array);
  10080. };
  10081. Engine.prototype.setFloatArray = function (uniform, array) {
  10082. if (!uniform)
  10083. return;
  10084. this._gl.uniform1fv(uniform, array);
  10085. };
  10086. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10087. if (!uniform || array.length % 2 !== 0)
  10088. return;
  10089. this._gl.uniform2fv(uniform, array);
  10090. };
  10091. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10092. if (!uniform || array.length % 3 !== 0)
  10093. return;
  10094. this._gl.uniform3fv(uniform, array);
  10095. };
  10096. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10097. if (!uniform || array.length % 4 !== 0)
  10098. return;
  10099. this._gl.uniform4fv(uniform, array);
  10100. };
  10101. Engine.prototype.setArray = function (uniform, array) {
  10102. if (!uniform)
  10103. return;
  10104. this._gl.uniform1fv(uniform, array);
  10105. };
  10106. Engine.prototype.setArray2 = function (uniform, array) {
  10107. if (!uniform || array.length % 2 !== 0)
  10108. return;
  10109. this._gl.uniform2fv(uniform, array);
  10110. };
  10111. Engine.prototype.setArray3 = function (uniform, array) {
  10112. if (!uniform || array.length % 3 !== 0)
  10113. return;
  10114. this._gl.uniform3fv(uniform, array);
  10115. };
  10116. Engine.prototype.setArray4 = function (uniform, array) {
  10117. if (!uniform || array.length % 4 !== 0)
  10118. return;
  10119. this._gl.uniform4fv(uniform, array);
  10120. };
  10121. Engine.prototype.setMatrices = function (uniform, matrices) {
  10122. if (!uniform)
  10123. return;
  10124. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10125. };
  10126. Engine.prototype.setMatrix = function (uniform, matrix) {
  10127. if (!uniform)
  10128. return;
  10129. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10130. };
  10131. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10132. if (!uniform)
  10133. return;
  10134. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10135. };
  10136. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10137. if (!uniform)
  10138. return;
  10139. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10140. };
  10141. Engine.prototype.setFloat = function (uniform, value) {
  10142. if (!uniform)
  10143. return;
  10144. this._gl.uniform1f(uniform, value);
  10145. };
  10146. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10147. if (!uniform)
  10148. return;
  10149. this._gl.uniform2f(uniform, x, y);
  10150. };
  10151. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10152. if (!uniform)
  10153. return;
  10154. this._gl.uniform3f(uniform, x, y, z);
  10155. };
  10156. Engine.prototype.setBool = function (uniform, bool) {
  10157. if (!uniform)
  10158. return;
  10159. this._gl.uniform1i(uniform, bool);
  10160. };
  10161. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10162. if (!uniform)
  10163. return;
  10164. this._gl.uniform4f(uniform, x, y, z, w);
  10165. };
  10166. Engine.prototype.setColor3 = function (uniform, color3) {
  10167. if (!uniform)
  10168. return;
  10169. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10170. };
  10171. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10172. if (!uniform)
  10173. return;
  10174. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10175. };
  10176. // States
  10177. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10178. if (zOffset === void 0) { zOffset = 0; }
  10179. if (reverseSide === void 0) { reverseSide = false; }
  10180. // Culling
  10181. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10182. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10183. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10184. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10185. if (culling) {
  10186. this._depthCullingState.cullFace = cullFace;
  10187. this._depthCullingState.cull = true;
  10188. }
  10189. else {
  10190. this._depthCullingState.cull = false;
  10191. }
  10192. }
  10193. // Z offset
  10194. this.setZOffset(zOffset);
  10195. };
  10196. Engine.prototype.setZOffset = function (value) {
  10197. this._depthCullingState.zOffset = value;
  10198. };
  10199. Engine.prototype.getZOffset = function () {
  10200. return this._depthCullingState.zOffset;
  10201. };
  10202. Engine.prototype.setDepthBuffer = function (enable) {
  10203. this._depthCullingState.depthTest = enable;
  10204. };
  10205. Engine.prototype.getDepthWrite = function () {
  10206. return this._depthCullingState.depthMask;
  10207. };
  10208. Engine.prototype.setDepthWrite = function (enable) {
  10209. this._depthCullingState.depthMask = enable;
  10210. };
  10211. Engine.prototype.setColorWrite = function (enable) {
  10212. this._gl.colorMask(enable, enable, enable, enable);
  10213. this._colorWrite = enable;
  10214. };
  10215. Engine.prototype.getColorWrite = function () {
  10216. return this._colorWrite;
  10217. };
  10218. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10219. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10220. };
  10221. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10222. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10223. if (this._alphaMode === mode) {
  10224. return;
  10225. }
  10226. switch (mode) {
  10227. case Engine.ALPHA_DISABLE:
  10228. this._alphaState.alphaBlend = false;
  10229. break;
  10230. case Engine.ALPHA_PREMULTIPLIED:
  10231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10232. this._alphaState.alphaBlend = true;
  10233. break;
  10234. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10235. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10236. this._alphaState.alphaBlend = true;
  10237. break;
  10238. case Engine.ALPHA_COMBINE:
  10239. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10240. this._alphaState.alphaBlend = true;
  10241. break;
  10242. case Engine.ALPHA_ONEONE:
  10243. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10244. this._alphaState.alphaBlend = true;
  10245. break;
  10246. case Engine.ALPHA_ADD:
  10247. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10248. this._alphaState.alphaBlend = true;
  10249. break;
  10250. case Engine.ALPHA_SUBTRACT:
  10251. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10252. this._alphaState.alphaBlend = true;
  10253. break;
  10254. case Engine.ALPHA_MULTIPLY:
  10255. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10256. this._alphaState.alphaBlend = true;
  10257. break;
  10258. case Engine.ALPHA_MAXIMIZED:
  10259. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10260. this._alphaState.alphaBlend = true;
  10261. break;
  10262. case Engine.ALPHA_INTERPOLATE:
  10263. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10264. this._alphaState.alphaBlend = true;
  10265. break;
  10266. case Engine.ALPHA_SCREENMODE:
  10267. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10268. this._alphaState.alphaBlend = true;
  10269. break;
  10270. }
  10271. if (!noDepthWriteChange) {
  10272. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10273. }
  10274. this._alphaMode = mode;
  10275. };
  10276. Engine.prototype.getAlphaMode = function () {
  10277. return this._alphaMode;
  10278. };
  10279. Engine.prototype.setAlphaTesting = function (enable) {
  10280. this._alphaTest = enable;
  10281. };
  10282. Engine.prototype.getAlphaTesting = function () {
  10283. return !!this._alphaTest;
  10284. };
  10285. // Textures
  10286. Engine.prototype.wipeCaches = function (bruteForce) {
  10287. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  10288. return;
  10289. }
  10290. this.resetTextureCache();
  10291. this._currentEffect = null;
  10292. // 6/8/2017: deltakosh: Should not be required anymore.
  10293. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10294. if (bruteForce) {
  10295. this._currentProgram = null;
  10296. this._stencilState.reset();
  10297. this._depthCullingState.reset();
  10298. this.setDepthFunctionToLessOrEqual();
  10299. this._alphaState.reset();
  10300. }
  10301. this._cachedVertexBuffers = null;
  10302. this._cachedIndexBuffer = null;
  10303. this._cachedEffectForVertexBuffers = null;
  10304. this._unbindVertexArrayObject();
  10305. this.bindIndexBuffer(null);
  10306. this.bindArrayBuffer(null);
  10307. };
  10308. /**
  10309. * Set the compressed texture format to use, based on the formats you have, and the formats
  10310. * supported by the hardware / browser.
  10311. *
  10312. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10313. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10314. * to API arguments needed to compressed textures. This puts the burden on the container
  10315. * generator to house the arcane code for determining these for current & future formats.
  10316. *
  10317. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10318. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10319. *
  10320. * Note: The result of this call is not taken into account when a texture is base64.
  10321. *
  10322. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10323. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10324. *
  10325. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10326. * @returns The extension selected.
  10327. */
  10328. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10329. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10330. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10331. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10332. return this._textureFormatInUse = this._texturesSupported[i];
  10333. }
  10334. }
  10335. }
  10336. // actively set format to nothing, to allow this to be called more than once
  10337. // and possibly fail the 2nd time
  10338. this._textureFormatInUse = null;
  10339. return null;
  10340. };
  10341. Engine.prototype._createTexture = function () {
  10342. var texture = this._gl.createTexture();
  10343. if (!texture) {
  10344. throw new Error("Unable to create texture");
  10345. }
  10346. return texture;
  10347. };
  10348. /**
  10349. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10350. * @param {string} urlArg- This contains one of the following:
  10351. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10352. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10353. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10354. *
  10355. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10356. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10357. * @param {Scene} scene- Needed for loading to the correct scene.
  10358. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10359. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10360. * @param {callback} onError- Optional callback to be called upon failure.
  10361. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10362. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10363. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10364. *
  10365. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10366. */
  10367. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10368. var _this = this;
  10369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10370. if (onLoad === void 0) { onLoad = null; }
  10371. if (onError === void 0) { onError = null; }
  10372. if (buffer === void 0) { buffer = null; }
  10373. if (fallBack === void 0) { fallBack = null; }
  10374. if (format === void 0) { format = null; }
  10375. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10376. var fromData = url.substr(0, 5) === "data:";
  10377. var fromBlob = url.substr(0, 5) === "blob:";
  10378. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10379. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10380. // establish the file extension, if possible
  10381. var lastDot = url.lastIndexOf('.');
  10382. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10383. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10384. var isTGA = (extension === ".tga");
  10385. // determine if a ktx file should be substituted
  10386. var isKTX = false;
  10387. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10388. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10389. isKTX = true;
  10390. }
  10391. if (scene) {
  10392. scene._addPendingData(texture);
  10393. }
  10394. texture.url = url;
  10395. texture.generateMipMaps = !noMipmap;
  10396. texture.samplingMode = samplingMode;
  10397. texture.invertY = invertY;
  10398. if (!this._doNotHandleContextLost) {
  10399. // Keep a link to the buffer only if we plan to handle context lost
  10400. texture._buffer = buffer;
  10401. }
  10402. var onLoadObserver = null;
  10403. if (onLoad && !fallBack) {
  10404. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10405. }
  10406. if (!fallBack)
  10407. this._internalTexturesCache.push(texture);
  10408. var onerror = function (message, exception) {
  10409. if (scene) {
  10410. scene._removePendingData(texture);
  10411. }
  10412. if (onLoadObserver) {
  10413. texture.onLoadedObservable.remove(onLoadObserver);
  10414. }
  10415. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10416. if (isKTX) {
  10417. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10418. }
  10419. else if (BABYLON.Tools.UseFallbackTexture) {
  10420. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10421. }
  10422. if (onError) {
  10423. onError(message || "Unknown error", exception);
  10424. }
  10425. };
  10426. var callback = null;
  10427. // processing for non-image formats
  10428. if (isKTX || isTGA || isDDS) {
  10429. if (isKTX) {
  10430. callback = function (data) {
  10431. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10432. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10433. ktx.uploadLevels(_this._gl, !noMipmap);
  10434. return false;
  10435. }, samplingMode);
  10436. };
  10437. }
  10438. else if (isTGA) {
  10439. callback = function (arrayBuffer) {
  10440. var data = new Uint8Array(arrayBuffer);
  10441. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10442. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10443. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10444. return false;
  10445. }, samplingMode);
  10446. };
  10447. }
  10448. else if (isDDS) {
  10449. callback = function (data) {
  10450. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10451. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10452. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10453. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10454. return false;
  10455. }, samplingMode);
  10456. };
  10457. }
  10458. if (!buffer) {
  10459. BABYLON.Tools.LoadFile(url, function (data) {
  10460. if (callback) {
  10461. callback(data);
  10462. }
  10463. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10464. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10465. });
  10466. }
  10467. else {
  10468. if (callback) {
  10469. callback(buffer);
  10470. }
  10471. }
  10472. // image format processing
  10473. }
  10474. else {
  10475. var onload = function (img) {
  10476. if (fromBlob && !_this._doNotHandleContextLost) {
  10477. // We need to store the image if we need to rebuild the texture
  10478. // in case of a webgl context lost
  10479. texture._buffer = img;
  10480. }
  10481. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10482. var gl = _this._gl;
  10483. var isPot = (img.width === potWidth && img.height === potHeight);
  10484. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10485. if (isPot) {
  10486. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10487. return false;
  10488. }
  10489. // Using shaders to rescale because canvas.drawImage is lossy
  10490. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10491. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10492. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10496. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10497. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10498. _this._releaseTexture(source);
  10499. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10500. continuationCallback();
  10501. });
  10502. return true;
  10503. }, samplingMode);
  10504. };
  10505. if (!fromData || isBase64)
  10506. if (buffer instanceof HTMLImageElement) {
  10507. onload(buffer);
  10508. }
  10509. else {
  10510. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10511. }
  10512. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10513. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10514. else
  10515. onload(buffer);
  10516. }
  10517. return texture;
  10518. };
  10519. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10520. var _this = this;
  10521. var rtt = this.createRenderTargetTexture({
  10522. width: destination.width,
  10523. height: destination.height,
  10524. }, {
  10525. generateMipMaps: false,
  10526. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10527. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10528. generateDepthBuffer: false,
  10529. generateStencilBuffer: false
  10530. });
  10531. if (!this._rescalePostProcess) {
  10532. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10533. }
  10534. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10535. _this._rescalePostProcess.onApply = function (effect) {
  10536. effect._bindTexture("textureSampler", source);
  10537. };
  10538. var hostingScene = scene;
  10539. if (!hostingScene) {
  10540. hostingScene = _this.scenes[_this.scenes.length - 1];
  10541. }
  10542. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10543. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10544. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10545. _this.unBindFramebuffer(rtt);
  10546. _this._releaseTexture(rtt);
  10547. if (onComplete) {
  10548. onComplete();
  10549. }
  10550. });
  10551. };
  10552. Engine.prototype._getInternalFormat = function (format) {
  10553. var internalFormat = this._gl.RGBA;
  10554. switch (format) {
  10555. case Engine.TEXTUREFORMAT_ALPHA:
  10556. internalFormat = this._gl.ALPHA;
  10557. break;
  10558. case Engine.TEXTUREFORMAT_LUMINANCE:
  10559. internalFormat = this._gl.LUMINANCE;
  10560. break;
  10561. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10562. internalFormat = this._gl.LUMINANCE_ALPHA;
  10563. break;
  10564. case Engine.TEXTUREFORMAT_RGB:
  10565. internalFormat = this._gl.RGB;
  10566. break;
  10567. case Engine.TEXTUREFORMAT_RGBA:
  10568. internalFormat = this._gl.RGBA;
  10569. break;
  10570. }
  10571. return internalFormat;
  10572. };
  10573. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10574. if (compression === void 0) { compression = null; }
  10575. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10576. if (!texture) {
  10577. return;
  10578. }
  10579. var internalFormat = this._getInternalFormat(format);
  10580. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10581. var textureType = this._getWebGLTextureType(type);
  10582. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10583. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10584. if (!this._doNotHandleContextLost) {
  10585. texture._bufferView = data;
  10586. texture.format = format;
  10587. texture.type = type;
  10588. texture.invertY = invertY;
  10589. texture._compression = compression;
  10590. }
  10591. if (texture.width % 4 !== 0) {
  10592. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10593. }
  10594. if (compression && data) {
  10595. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10596. }
  10597. else {
  10598. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10599. }
  10600. if (texture.generateMipMaps) {
  10601. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10602. }
  10603. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10604. this.resetTextureCache();
  10605. texture.isReady = true;
  10606. };
  10607. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10608. if (compression === void 0) { compression = null; }
  10609. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  10610. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10611. texture.baseWidth = width;
  10612. texture.baseHeight = height;
  10613. texture.width = width;
  10614. texture.height = height;
  10615. texture.format = format;
  10616. texture.generateMipMaps = generateMipMaps;
  10617. texture.samplingMode = samplingMode;
  10618. texture.invertY = invertY;
  10619. texture._compression = compression;
  10620. texture.type = type;
  10621. if (!this._doNotHandleContextLost) {
  10622. texture._bufferView = data;
  10623. }
  10624. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10625. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10626. // Filters
  10627. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10628. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10630. if (generateMipMaps) {
  10631. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10632. }
  10633. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10634. this._internalTexturesCache.push(texture);
  10635. return texture;
  10636. };
  10637. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10638. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10639. texture.baseWidth = width;
  10640. texture.baseHeight = height;
  10641. if (generateMipMaps) {
  10642. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10643. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10644. }
  10645. this.resetTextureCache();
  10646. texture.width = width;
  10647. texture.height = height;
  10648. texture.isReady = false;
  10649. texture.generateMipMaps = generateMipMaps;
  10650. texture.samplingMode = samplingMode;
  10651. this.updateTextureSamplingMode(samplingMode, texture);
  10652. this._internalTexturesCache.push(texture);
  10653. return texture;
  10654. };
  10655. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10656. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10657. if (texture.isCube) {
  10658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10659. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10660. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10662. }
  10663. else if (texture.is3D) {
  10664. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10665. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10666. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10667. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10668. }
  10669. else {
  10670. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10672. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10674. }
  10675. texture.samplingMode = samplingMode;
  10676. };
  10677. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10678. if (premulAlpha === void 0) { premulAlpha = false; }
  10679. if (!texture) {
  10680. return;
  10681. }
  10682. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10683. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10684. if (premulAlpha) {
  10685. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10686. }
  10687. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10688. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10689. if (texture.generateMipMaps) {
  10690. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10691. }
  10692. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10693. if (premulAlpha) {
  10694. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10695. }
  10696. this.resetTextureCache();
  10697. texture.isReady = true;
  10698. };
  10699. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10700. if (!texture || texture._isDisabled) {
  10701. return;
  10702. }
  10703. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10704. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10705. try {
  10706. // Testing video texture support
  10707. if (this._videoTextureSupported === undefined) {
  10708. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10709. if (this._gl.getError() !== 0) {
  10710. this._videoTextureSupported = false;
  10711. }
  10712. else {
  10713. this._videoTextureSupported = true;
  10714. }
  10715. }
  10716. // Copy video through the current working canvas if video texture is not supported
  10717. if (!this._videoTextureSupported) {
  10718. if (!texture._workingCanvas) {
  10719. texture._workingCanvas = document.createElement("canvas");
  10720. var context = texture._workingCanvas.getContext("2d");
  10721. if (!context) {
  10722. throw new Error("Unable to get 2d context");
  10723. }
  10724. texture._workingContext = context;
  10725. texture._workingCanvas.width = texture.width;
  10726. texture._workingCanvas.height = texture.height;
  10727. }
  10728. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10729. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10730. }
  10731. else {
  10732. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10733. }
  10734. if (texture.generateMipMaps) {
  10735. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10736. }
  10737. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10738. this.resetTextureCache();
  10739. texture.isReady = true;
  10740. }
  10741. catch (ex) {
  10742. // Something unexpected
  10743. // Let's disable the texture
  10744. texture._isDisabled = true;
  10745. }
  10746. };
  10747. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10748. var fullOptions = new RenderTargetCreationOptions();
  10749. if (options !== undefined && typeof options === "object") {
  10750. fullOptions.generateMipMaps = options.generateMipMaps;
  10751. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10752. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10753. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10754. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10755. }
  10756. else {
  10757. fullOptions.generateMipMaps = options;
  10758. fullOptions.generateDepthBuffer = true;
  10759. fullOptions.generateStencilBuffer = false;
  10760. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10761. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10762. }
  10763. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10764. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10765. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10766. }
  10767. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10768. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10769. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10770. }
  10771. var gl = this._gl;
  10772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10773. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10774. var width = size.width || size;
  10775. var height = size.height || size;
  10776. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10777. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10778. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10779. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10780. }
  10781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10783. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10784. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10785. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10786. // Create the framebuffer
  10787. var framebuffer = gl.createFramebuffer();
  10788. this.bindUnboundFramebuffer(framebuffer);
  10789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10790. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10791. if (fullOptions.generateMipMaps) {
  10792. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10793. }
  10794. // Unbind
  10795. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10796. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10797. this.bindUnboundFramebuffer(null);
  10798. texture._framebuffer = framebuffer;
  10799. texture.baseWidth = width;
  10800. texture.baseHeight = height;
  10801. texture.width = width;
  10802. texture.height = height;
  10803. texture.isReady = true;
  10804. texture.samples = 1;
  10805. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10806. texture.samplingMode = fullOptions.samplingMode;
  10807. texture.type = fullOptions.type;
  10808. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10809. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10810. this.resetTextureCache();
  10811. this._internalTexturesCache.push(texture);
  10812. return texture;
  10813. };
  10814. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10815. var generateMipMaps = false;
  10816. var generateDepthBuffer = true;
  10817. var generateStencilBuffer = false;
  10818. var generateDepthTexture = false;
  10819. var textureCount = 1;
  10820. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10821. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10822. var types = [], samplingModes = [];
  10823. if (options !== undefined) {
  10824. generateMipMaps = options.generateMipMaps;
  10825. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10826. generateStencilBuffer = options.generateStencilBuffer;
  10827. generateDepthTexture = options.generateDepthTexture;
  10828. textureCount = options.textureCount || 1;
  10829. if (options.types) {
  10830. types = options.types;
  10831. }
  10832. if (options.samplingModes) {
  10833. samplingModes = options.samplingModes;
  10834. }
  10835. }
  10836. var gl = this._gl;
  10837. // Create the framebuffer
  10838. var framebuffer = gl.createFramebuffer();
  10839. this.bindUnboundFramebuffer(framebuffer);
  10840. var width = size.width || size;
  10841. var height = size.height || size;
  10842. var textures = [];
  10843. var attachments = [];
  10844. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10845. for (var i = 0; i < textureCount; i++) {
  10846. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10847. var type = types[i] || defaultType;
  10848. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10849. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10850. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10851. }
  10852. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10853. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10854. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10855. }
  10856. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10857. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10858. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10859. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10860. }
  10861. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10862. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10863. textures.push(texture);
  10864. attachments.push(attachment);
  10865. gl.activeTexture(gl["TEXTURE" + i]);
  10866. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10871. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10872. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10873. if (generateMipMaps) {
  10874. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10875. }
  10876. // Unbind
  10877. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10878. texture._framebuffer = framebuffer;
  10879. texture._depthStencilBuffer = depthStencilBuffer;
  10880. texture.baseWidth = width;
  10881. texture.baseHeight = height;
  10882. texture.width = width;
  10883. texture.height = height;
  10884. texture.isReady = true;
  10885. texture.samples = 1;
  10886. texture.generateMipMaps = generateMipMaps;
  10887. texture.samplingMode = samplingMode;
  10888. texture.type = type;
  10889. texture._generateDepthBuffer = generateDepthBuffer;
  10890. texture._generateStencilBuffer = generateStencilBuffer;
  10891. this._internalTexturesCache.push(texture);
  10892. }
  10893. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10894. // Depth texture
  10895. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10896. gl.activeTexture(gl.TEXTURE0);
  10897. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10902. 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);
  10903. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10904. depthTexture._framebuffer = framebuffer;
  10905. depthTexture.baseWidth = width;
  10906. depthTexture.baseHeight = height;
  10907. depthTexture.width = width;
  10908. depthTexture.height = height;
  10909. depthTexture.isReady = true;
  10910. depthTexture.samples = 1;
  10911. depthTexture.generateMipMaps = generateMipMaps;
  10912. depthTexture.samplingMode = gl.NEAREST;
  10913. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10914. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10915. textures.push(depthTexture);
  10916. this._internalTexturesCache.push(depthTexture);
  10917. }
  10918. gl.drawBuffers(attachments);
  10919. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10920. this.bindUnboundFramebuffer(null);
  10921. this.resetTextureCache();
  10922. return textures;
  10923. };
  10924. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10925. if (samples === void 0) { samples = 1; }
  10926. var depthStencilBuffer = null;
  10927. var gl = this._gl;
  10928. // Create the depth/stencil buffer
  10929. if (generateStencilBuffer) {
  10930. depthStencilBuffer = gl.createRenderbuffer();
  10931. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10932. if (samples > 1) {
  10933. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10934. }
  10935. else {
  10936. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10937. }
  10938. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10939. }
  10940. else if (generateDepthBuffer) {
  10941. depthStencilBuffer = gl.createRenderbuffer();
  10942. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10943. if (samples > 1) {
  10944. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10945. }
  10946. else {
  10947. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10948. }
  10949. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10950. }
  10951. return depthStencilBuffer;
  10952. };
  10953. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10954. if (this.webGLVersion < 2 || !texture) {
  10955. return 1;
  10956. }
  10957. if (texture.samples === samples) {
  10958. return samples;
  10959. }
  10960. var gl = this._gl;
  10961. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10962. // Dispose previous render buffers
  10963. if (texture._depthStencilBuffer) {
  10964. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10965. }
  10966. if (texture._MSAAFramebuffer) {
  10967. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10968. }
  10969. if (texture._MSAARenderBuffer) {
  10970. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10971. }
  10972. if (samples > 1) {
  10973. var framebuffer = gl.createFramebuffer();
  10974. if (!framebuffer) {
  10975. throw new Error("Unable to create multi sampled framebuffer");
  10976. }
  10977. texture._MSAAFramebuffer = framebuffer;
  10978. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10979. var colorRenderbuffer = gl.createRenderbuffer();
  10980. if (!colorRenderbuffer) {
  10981. throw new Error("Unable to create multi sampled framebuffer");
  10982. }
  10983. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10984. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10985. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10986. texture._MSAARenderBuffer = colorRenderbuffer;
  10987. }
  10988. else {
  10989. this.bindUnboundFramebuffer(texture._framebuffer);
  10990. }
  10991. texture.samples = samples;
  10992. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10993. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10994. this.bindUnboundFramebuffer(null);
  10995. return samples;
  10996. };
  10997. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10998. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10999. };
  11000. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  11001. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  11002. };
  11003. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  11004. var gl = this._gl;
  11005. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11006. var generateMipMaps = true;
  11007. var generateDepthBuffer = true;
  11008. var generateStencilBuffer = false;
  11009. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11010. if (options !== undefined) {
  11011. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  11012. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11013. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  11014. if (options.samplingMode !== undefined) {
  11015. samplingMode = options.samplingMode;
  11016. }
  11017. }
  11018. texture.isCube = true;
  11019. texture.generateMipMaps = generateMipMaps;
  11020. texture.samples = 1;
  11021. texture.samplingMode = samplingMode;
  11022. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11023. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11024. for (var face = 0; face < 6; face++) {
  11025. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  11026. }
  11027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11028. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11029. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11030. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11031. // Create the framebuffer
  11032. var framebuffer = gl.createFramebuffer();
  11033. this.bindUnboundFramebuffer(framebuffer);
  11034. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  11035. // Mipmaps
  11036. if (texture.generateMipMaps) {
  11037. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11038. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11039. }
  11040. // Unbind
  11041. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11042. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11043. this.bindUnboundFramebuffer(null);
  11044. texture._framebuffer = framebuffer;
  11045. texture.width = size;
  11046. texture.height = size;
  11047. texture.isReady = true;
  11048. this.resetTextureCache();
  11049. this._internalTexturesCache.push(texture);
  11050. return texture;
  11051. };
  11052. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11053. var _this = this;
  11054. if (onLoad === void 0) { onLoad = null; }
  11055. if (onError === void 0) { onError = null; }
  11056. if (forcedExtension === void 0) { forcedExtension = null; }
  11057. var callback = function (loadData) {
  11058. if (!loadData) {
  11059. if (onLoad) {
  11060. onLoad(null);
  11061. }
  11062. return;
  11063. }
  11064. var texture = loadData.texture;
  11065. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11066. texture._lodGenerationScale = scale;
  11067. texture._lodGenerationOffset = offset;
  11068. if (_this._caps.textureLOD) {
  11069. // Do not add extra process if texture lod is supported.
  11070. if (onLoad) {
  11071. onLoad(texture);
  11072. }
  11073. return;
  11074. }
  11075. var mipSlices = 3;
  11076. var gl = _this._gl;
  11077. var width = loadData.width;
  11078. if (!width) {
  11079. return;
  11080. }
  11081. var textures = [];
  11082. for (var i = 0; i < mipSlices; i++) {
  11083. //compute LOD from even spacing in smoothness (matching shader calculation)
  11084. var smoothness = i / (mipSlices - 1);
  11085. var roughness = 1 - smoothness;
  11086. var minLODIndex = offset; // roughness = 0
  11087. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11088. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11089. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11090. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11091. glTextureFromLod.isCube = true;
  11092. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  11093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11096. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11097. if (loadData.isDDS) {
  11098. var info = loadData.info;
  11099. var data = loadData.data;
  11100. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11101. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11102. }
  11103. else {
  11104. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11105. }
  11106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11107. // Wrap in a base texture for easy binding.
  11108. var lodTexture = new BABYLON.BaseTexture(scene);
  11109. lodTexture.isCube = true;
  11110. lodTexture._texture = glTextureFromLod;
  11111. glTextureFromLod.isReady = true;
  11112. textures.push(lodTexture);
  11113. }
  11114. texture._lodTextureHigh = textures[2];
  11115. texture._lodTextureMid = textures[1];
  11116. texture._lodTextureLow = textures[0];
  11117. if (onLoad) {
  11118. onLoad(texture);
  11119. }
  11120. };
  11121. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11122. };
  11123. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11124. var _this = this;
  11125. if (onLoad === void 0) { onLoad = null; }
  11126. if (onError === void 0) { onError = null; }
  11127. if (forcedExtension === void 0) { forcedExtension = null; }
  11128. var gl = this._gl;
  11129. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11130. texture.isCube = true;
  11131. texture.url = rootUrl;
  11132. texture.generateMipMaps = !noMipmap;
  11133. if (!this._doNotHandleContextLost) {
  11134. texture._extension = forcedExtension;
  11135. texture._files = files;
  11136. }
  11137. var isKTX = false;
  11138. var isDDS = false;
  11139. var lastDot = rootUrl.lastIndexOf('.');
  11140. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11141. if (this._textureFormatInUse) {
  11142. extension = this._textureFormatInUse;
  11143. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11144. isKTX = true;
  11145. }
  11146. else {
  11147. isDDS = (extension === ".dds");
  11148. }
  11149. var onerror = function (request, exception) {
  11150. if (onError && request) {
  11151. onError(request.status + " " + request.statusText, exception);
  11152. }
  11153. };
  11154. if (isKTX) {
  11155. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11156. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11157. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11158. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11159. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11160. ktx.uploadLevels(_this._gl, !noMipmap);
  11161. _this.setCubeMapTextureParams(gl, loadMipmap);
  11162. texture.width = ktx.pixelWidth;
  11163. texture.height = ktx.pixelHeight;
  11164. texture.isReady = true;
  11165. }, undefined, undefined, true, onerror);
  11166. }
  11167. else if (isDDS) {
  11168. if (files && files.length === 6) {
  11169. cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11170. var info;
  11171. var loadMipmap = false;
  11172. var width = 0;
  11173. for (var index = 0; index < imgs.length; index++) {
  11174. var data = imgs[index];
  11175. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11176. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11177. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11178. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11179. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11180. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11181. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11182. }
  11183. texture.width = info.width;
  11184. texture.height = info.height;
  11185. texture.type = info.textureType;
  11186. width = info.width;
  11187. }
  11188. _this.setCubeMapTextureParams(gl, loadMipmap);
  11189. texture.isReady = true;
  11190. if (onLoad) {
  11191. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11192. }
  11193. }, files, onError);
  11194. }
  11195. else {
  11196. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11197. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11198. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11199. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11200. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11201. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11202. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11203. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11204. }
  11205. _this.setCubeMapTextureParams(gl, loadMipmap);
  11206. texture.width = info.width;
  11207. texture.height = info.height;
  11208. texture.isReady = true;
  11209. texture.type = info.textureType;
  11210. if (onLoad) {
  11211. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11212. }
  11213. }, undefined, undefined, true, onerror);
  11214. }
  11215. }
  11216. else {
  11217. if (!files) {
  11218. throw new Error("Cannot load cubemap because files were not defined");
  11219. }
  11220. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11221. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11222. var height = width;
  11223. _this._prepareWorkingCanvas();
  11224. if (!_this._workingCanvas || !_this._workingContext) {
  11225. return;
  11226. }
  11227. _this._workingCanvas.width = width;
  11228. _this._workingCanvas.height = height;
  11229. var faces = [
  11230. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11231. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11232. ];
  11233. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11234. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11235. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11236. for (var index = 0; index < faces.length; index++) {
  11237. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11238. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11239. }
  11240. if (!noMipmap) {
  11241. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11242. }
  11243. _this.setCubeMapTextureParams(gl, !noMipmap);
  11244. texture.width = width;
  11245. texture.height = height;
  11246. texture.isReady = true;
  11247. if (format) {
  11248. texture.format = format;
  11249. }
  11250. texture.onLoadedObservable.notifyObservers(texture);
  11251. texture.onLoadedObservable.clear();
  11252. if (onLoad) {
  11253. onLoad();
  11254. }
  11255. }, files, onError);
  11256. }
  11257. this._internalTexturesCache.push(texture);
  11258. return texture;
  11259. };
  11260. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11261. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11265. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11266. this.resetTextureCache();
  11267. };
  11268. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11269. if (compression === void 0) { compression = null; }
  11270. if (level === void 0) { level = 0; }
  11271. texture._bufferViewArray = data;
  11272. texture.format = format;
  11273. texture.type = type;
  11274. texture.invertY = invertY;
  11275. texture._compression = compression;
  11276. var gl = this._gl;
  11277. var textureType = this._getWebGLTextureType(type);
  11278. var internalFormat = this._getInternalFormat(format);
  11279. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11280. var needConversion = false;
  11281. if (internalFormat === gl.RGB) {
  11282. internalFormat = gl.RGBA;
  11283. needConversion = true;
  11284. }
  11285. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11286. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11287. if (texture.width % 4 !== 0) {
  11288. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11289. }
  11290. // Data are known to be in +X +Y +Z -X -Y -Z
  11291. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11292. var faceData = data[faceIndex];
  11293. if (compression) {
  11294. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11295. }
  11296. else {
  11297. if (needConversion) {
  11298. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11299. }
  11300. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11301. }
  11302. }
  11303. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11304. if (isPot && texture.generateMipMaps && level === 0) {
  11305. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11306. }
  11307. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11308. this.resetTextureCache();
  11309. texture.isReady = true;
  11310. };
  11311. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11312. if (compression === void 0) { compression = null; }
  11313. var gl = this._gl;
  11314. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11315. texture.isCube = true;
  11316. texture.generateMipMaps = generateMipMaps;
  11317. texture.format = format;
  11318. texture.type = type;
  11319. if (!this._doNotHandleContextLost) {
  11320. texture._bufferViewArray = data;
  11321. }
  11322. var textureType = this._getWebGLTextureType(type);
  11323. var internalFormat = this._getInternalFormat(format);
  11324. if (internalFormat === gl.RGB) {
  11325. internalFormat = gl.RGBA;
  11326. }
  11327. var width = size;
  11328. var height = width;
  11329. texture.width = width;
  11330. texture.height = height;
  11331. // Double check on POT to generate Mips.
  11332. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11333. if (!isPot) {
  11334. generateMipMaps = false;
  11335. }
  11336. // Upload data if needed. The texture won't be ready until then.
  11337. if (data) {
  11338. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11339. }
  11340. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11341. // Filters
  11342. if (data && generateMipMaps) {
  11343. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11344. }
  11345. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11348. }
  11349. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11350. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11351. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11352. }
  11353. else {
  11354. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11357. }
  11358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11359. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11360. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11361. return texture;
  11362. };
  11363. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11364. var _this = this;
  11365. if (onLoad === void 0) { onLoad = null; }
  11366. if (onError === void 0) { onError = null; }
  11367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11368. if (invertY === void 0) { invertY = false; }
  11369. var gl = this._gl;
  11370. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11371. scene._addPendingData(texture);
  11372. texture.url = url;
  11373. this._internalTexturesCache.push(texture);
  11374. var onerror = function (request, exception) {
  11375. scene._removePendingData(texture);
  11376. if (onError && request) {
  11377. onError(request.status + " " + request.statusText, exception);
  11378. }
  11379. };
  11380. var internalCallback = function (data) {
  11381. var width = texture.width;
  11382. var faceDataArrays = callback(data);
  11383. if (!faceDataArrays) {
  11384. return;
  11385. }
  11386. if (mipmmapGenerator) {
  11387. var textureType = _this._getWebGLTextureType(type);
  11388. var internalFormat = _this._getInternalFormat(format);
  11389. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11390. var needConversion = false;
  11391. if (internalFormat === gl.RGB) {
  11392. internalFormat = gl.RGBA;
  11393. needConversion = true;
  11394. }
  11395. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11396. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11397. var mipData = mipmmapGenerator(faceDataArrays);
  11398. for (var level = 0; level < mipData.length; level++) {
  11399. var mipSize = width >> level;
  11400. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11401. var mipFaceData = mipData[level][faceIndex];
  11402. if (needConversion) {
  11403. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11404. }
  11405. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11406. }
  11407. }
  11408. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11409. }
  11410. else {
  11411. texture.generateMipMaps = !noMipmap;
  11412. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11413. }
  11414. texture.isReady = true;
  11415. _this.resetTextureCache();
  11416. scene._removePendingData(texture);
  11417. if (onLoad) {
  11418. onLoad();
  11419. }
  11420. };
  11421. BABYLON.Tools.LoadFile(url, function (data) {
  11422. internalCallback(data);
  11423. }, undefined, scene.database, true, onerror);
  11424. return texture;
  11425. };
  11426. ;
  11427. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11428. if (compression === void 0) { compression = null; }
  11429. var internalFormat = this._getInternalFormat(format);
  11430. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11431. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11432. if (!this._doNotHandleContextLost) {
  11433. texture._bufferView = data;
  11434. texture.format = format;
  11435. texture.invertY = invertY;
  11436. texture._compression = compression;
  11437. }
  11438. if (texture.width % 4 !== 0) {
  11439. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11440. }
  11441. if (compression && data) {
  11442. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11443. }
  11444. else {
  11445. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11446. }
  11447. if (texture.generateMipMaps) {
  11448. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11449. }
  11450. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11451. this.resetTextureCache();
  11452. texture.isReady = true;
  11453. };
  11454. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11455. if (compression === void 0) { compression = null; }
  11456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11457. texture.baseWidth = width;
  11458. texture.baseHeight = height;
  11459. texture.baseDepth = depth;
  11460. texture.width = width;
  11461. texture.height = height;
  11462. texture.depth = depth;
  11463. texture.format = format;
  11464. texture.generateMipMaps = generateMipMaps;
  11465. texture.samplingMode = samplingMode;
  11466. texture.is3D = true;
  11467. if (!this._doNotHandleContextLost) {
  11468. texture._bufferView = data;
  11469. }
  11470. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11471. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11472. // Filters
  11473. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11474. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11475. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11476. if (generateMipMaps) {
  11477. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11478. }
  11479. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11480. this._internalTexturesCache.push(texture);
  11481. return texture;
  11482. };
  11483. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11484. var gl = this._gl;
  11485. if (!gl) {
  11486. return;
  11487. }
  11488. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11491. if (!noMipmap && !isCompressed) {
  11492. gl.generateMipmap(gl.TEXTURE_2D);
  11493. }
  11494. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11495. this.resetTextureCache();
  11496. if (scene) {
  11497. scene._removePendingData(texture);
  11498. }
  11499. texture.onLoadedObservable.notifyObservers(texture);
  11500. texture.onLoadedObservable.clear();
  11501. };
  11502. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11503. var _this = this;
  11504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11505. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11506. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11507. var gl = this._gl;
  11508. if (!gl) {
  11509. return;
  11510. }
  11511. if (!texture._webGLTexture) {
  11512. this.resetTextureCache();
  11513. if (scene) {
  11514. scene._removePendingData(texture);
  11515. }
  11516. return;
  11517. }
  11518. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11519. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11520. texture.baseWidth = width;
  11521. texture.baseHeight = height;
  11522. texture.width = potWidth;
  11523. texture.height = potHeight;
  11524. texture.isReady = true;
  11525. if (processFunction(potWidth, potHeight, function () {
  11526. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11527. })) {
  11528. // Returning as texture needs extra async steps
  11529. return;
  11530. }
  11531. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11532. };
  11533. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11534. // Create new RGBA data container.
  11535. var rgbaData;
  11536. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11537. rgbaData = new Float32Array(width * height * 4);
  11538. }
  11539. else {
  11540. rgbaData = new Uint32Array(width * height * 4);
  11541. }
  11542. // Convert each pixel.
  11543. for (var x = 0; x < width; x++) {
  11544. for (var y = 0; y < height; y++) {
  11545. var index = (y * width + x) * 3;
  11546. var newIndex = (y * width + x) * 4;
  11547. // Map Old Value to new value.
  11548. rgbaData[newIndex + 0] = rgbData[index + 0];
  11549. rgbaData[newIndex + 1] = rgbData[index + 1];
  11550. rgbaData[newIndex + 2] = rgbData[index + 2];
  11551. // Add fully opaque alpha channel.
  11552. rgbaData[newIndex + 3] = 1;
  11553. }
  11554. }
  11555. return rgbaData;
  11556. };
  11557. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11558. var gl = this._gl;
  11559. if (texture._framebuffer) {
  11560. gl.deleteFramebuffer(texture._framebuffer);
  11561. texture._framebuffer = null;
  11562. }
  11563. if (texture._depthStencilBuffer) {
  11564. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11565. texture._depthStencilBuffer = null;
  11566. }
  11567. if (texture._MSAAFramebuffer) {
  11568. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11569. texture._MSAAFramebuffer = null;
  11570. }
  11571. if (texture._MSAARenderBuffer) {
  11572. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11573. texture._MSAARenderBuffer = null;
  11574. }
  11575. };
  11576. Engine.prototype._releaseTexture = function (texture) {
  11577. var gl = this._gl;
  11578. this._releaseFramebufferObjects(texture);
  11579. gl.deleteTexture(texture._webGLTexture);
  11580. // Unbind channels
  11581. this.unbindAllTextures();
  11582. var index = this._internalTexturesCache.indexOf(texture);
  11583. if (index !== -1) {
  11584. this._internalTexturesCache.splice(index, 1);
  11585. }
  11586. // Integrated fixed lod samplers.
  11587. if (texture._lodTextureHigh) {
  11588. texture._lodTextureHigh.dispose();
  11589. }
  11590. if (texture._lodTextureMid) {
  11591. texture._lodTextureMid.dispose();
  11592. }
  11593. if (texture._lodTextureLow) {
  11594. texture._lodTextureLow.dispose();
  11595. }
  11596. };
  11597. Engine.prototype.setProgram = function (program) {
  11598. if (this._currentProgram !== program) {
  11599. this._gl.useProgram(program);
  11600. this._currentProgram = program;
  11601. }
  11602. };
  11603. Engine.prototype.bindSamplers = function (effect) {
  11604. this.setProgram(effect.getProgram());
  11605. var samplers = effect.getSamplers();
  11606. for (var index = 0; index < samplers.length; index++) {
  11607. var uniform = effect.getUniform(samplers[index]);
  11608. if (uniform) {
  11609. this._boundUniforms[index] = uniform;
  11610. }
  11611. }
  11612. this._currentEffect = null;
  11613. };
  11614. Engine.prototype._activateTextureChannel = function (channel) {
  11615. if (this._activeChannel !== channel) {
  11616. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  11617. this._activeChannel = channel;
  11618. }
  11619. };
  11620. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  11621. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11622. if (index > -1 && index !== this._boundTexturesOrder.length - 1) {
  11623. this._boundTexturesOrder.splice(index, 1);
  11624. this._boundTexturesOrder.push(internalTexture);
  11625. }
  11626. };
  11627. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  11628. var currentSlot = internalTexture._designatedSlot;
  11629. internalTexture._designatedSlot = -1;
  11630. var index = this._boundTexturesOrder.indexOf(internalTexture);
  11631. if (index > -1) {
  11632. this._boundTexturesOrder.splice(index, 1);
  11633. }
  11634. return currentSlot;
  11635. };
  11636. Engine.prototype._bindTextureDirectly = function (target, texture, isPartOfTextureArray) {
  11637. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11638. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  11639. var isTextureForRendering = texture && texture._initialSlot > -1;
  11640. if (currentTextureBound !== texture) {
  11641. if (currentTextureBound) {
  11642. this._removeDesignatedSlot(currentTextureBound);
  11643. }
  11644. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11645. if (this._activeChannel >= 0) {
  11646. this._boundTexturesCache[this._activeChannel] = texture;
  11647. if (isTextureForRendering) {
  11648. this._boundTexturesOrder.push(texture);
  11649. }
  11650. }
  11651. }
  11652. if (isTextureForRendering) {
  11653. texture._designatedSlot = this._activeChannel;
  11654. if (!isPartOfTextureArray) {
  11655. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  11656. }
  11657. }
  11658. };
  11659. Engine.prototype._bindTexture = function (channel, texture) {
  11660. if (channel < 0) {
  11661. return;
  11662. }
  11663. if (texture) {
  11664. channel = this._getCorrectTextureChannel(channel, texture);
  11665. }
  11666. this._activateTextureChannel(channel);
  11667. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11668. };
  11669. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11670. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11671. };
  11672. Engine.prototype.unbindAllTextures = function () {
  11673. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11674. this._activateTextureChannel(channel);
  11675. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11676. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11677. if (this.webGLVersion > 1) {
  11678. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11679. }
  11680. }
  11681. };
  11682. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11683. if (channel < 0) {
  11684. return;
  11685. }
  11686. if (uniform) {
  11687. this._boundUniforms[channel] = uniform;
  11688. }
  11689. this._setTexture(channel, texture);
  11690. };
  11691. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  11692. if (!internalTexture) {
  11693. return -1;
  11694. }
  11695. internalTexture._initialSlot = channel;
  11696. if (channel !== internalTexture._designatedSlot) {
  11697. if (internalTexture._designatedSlot > -1) {
  11698. channel = internalTexture._designatedSlot;
  11699. }
  11700. else {
  11701. if (this._nextFreeTextureSlot > -1) {
  11702. channel = this._nextFreeTextureSlot;
  11703. this._nextFreeTextureSlot++;
  11704. if (this._nextFreeTextureSlot >= this._caps.maxTexturesImageUnits) {
  11705. this._nextFreeTextureSlot = -1; // No more free slots, we will recycle
  11706. }
  11707. }
  11708. else {
  11709. channel = this._removeDesignatedSlot(this._boundTexturesOrder[0]);
  11710. }
  11711. }
  11712. }
  11713. return channel;
  11714. };
  11715. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  11716. var uniform = this._boundUniforms[sourceSlot];
  11717. this._gl.uniform1i(uniform, destination);
  11718. };
  11719. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  11720. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11721. // Not ready?
  11722. if (!texture) {
  11723. if (this._boundTexturesCache[channel] != null) {
  11724. this._activateTextureChannel(channel);
  11725. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11726. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11727. if (this.webGLVersion > 1) {
  11728. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11729. }
  11730. }
  11731. return false;
  11732. }
  11733. // Video
  11734. var alreadyActivated = false;
  11735. if (texture.video) {
  11736. this._activateTextureChannel(channel);
  11737. alreadyActivated = true;
  11738. texture.update();
  11739. }
  11740. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11741. texture.delayLoad();
  11742. return false;
  11743. }
  11744. var internalTexture;
  11745. if (texture.isReady()) {
  11746. internalTexture = texture.getInternalTexture();
  11747. }
  11748. else if (texture.isCube) {
  11749. internalTexture = this.emptyCubeTexture;
  11750. }
  11751. else if (texture.is3D) {
  11752. internalTexture = this.emptyTexture3D;
  11753. }
  11754. else {
  11755. internalTexture = this.emptyTexture;
  11756. }
  11757. if (!isPartOfTextureArray) {
  11758. channel = this._getCorrectTextureChannel(channel, internalTexture);
  11759. }
  11760. if (this._boundTexturesCache[channel] === internalTexture) {
  11761. this._moveBoundTextureOnTop(internalTexture);
  11762. if (!isPartOfTextureArray) {
  11763. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  11764. }
  11765. return false;
  11766. }
  11767. if (!alreadyActivated) {
  11768. this._activateTextureChannel(channel);
  11769. }
  11770. if (internalTexture && internalTexture.is3D) {
  11771. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  11772. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11773. internalTexture._cachedWrapU = texture.wrapU;
  11774. switch (texture.wrapU) {
  11775. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11776. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11777. break;
  11778. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11779. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11780. break;
  11781. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11782. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11783. break;
  11784. }
  11785. }
  11786. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11787. internalTexture._cachedWrapV = texture.wrapV;
  11788. switch (texture.wrapV) {
  11789. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11790. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11791. break;
  11792. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11793. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11794. break;
  11795. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11797. break;
  11798. }
  11799. }
  11800. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11801. internalTexture._cachedWrapR = texture.wrapR;
  11802. switch (texture.wrapV) {
  11803. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11804. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11805. break;
  11806. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11807. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11808. break;
  11809. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11811. break;
  11812. }
  11813. }
  11814. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11815. }
  11816. else if (internalTexture && internalTexture.isCube) {
  11817. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  11818. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11819. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11820. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11821. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11822. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11823. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11824. }
  11825. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11826. }
  11827. else {
  11828. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  11829. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11830. internalTexture._cachedWrapU = texture.wrapU;
  11831. switch (texture.wrapU) {
  11832. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11833. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11834. break;
  11835. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11836. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11837. break;
  11838. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11840. break;
  11841. }
  11842. }
  11843. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11844. internalTexture._cachedWrapV = texture.wrapV;
  11845. switch (texture.wrapV) {
  11846. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11848. break;
  11849. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11850. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11851. break;
  11852. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11853. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11854. break;
  11855. }
  11856. }
  11857. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11858. }
  11859. return true;
  11860. };
  11861. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11862. if (channel < 0 || !uniform) {
  11863. return;
  11864. }
  11865. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11866. this._textureUnits = new Int32Array(textures.length);
  11867. }
  11868. for (var i = 0; i < textures.length; i++) {
  11869. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  11870. }
  11871. this._gl.uniform1iv(uniform, this._textureUnits);
  11872. for (var index = 0; index < textures.length; index++) {
  11873. this._setTexture(this._textureUnits[index], textures[index], true);
  11874. }
  11875. };
  11876. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11877. var internalTexture = texture.getInternalTexture();
  11878. if (!internalTexture) {
  11879. return;
  11880. }
  11881. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11882. var value = texture.anisotropicFilteringLevel;
  11883. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11884. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11885. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11886. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11887. }
  11888. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11889. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11890. internalTexture._cachedAnisotropicFilteringLevel = value;
  11891. }
  11892. };
  11893. Engine.prototype.readPixels = function (x, y, width, height) {
  11894. var data = new Uint8Array(height * width * 4);
  11895. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11896. return data;
  11897. };
  11898. /**
  11899. * Add an externaly attached data from its key.
  11900. * This method call will fail and return false, if such key already exists.
  11901. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11902. * @param key the unique key that identifies the data
  11903. * @param data the data object to associate to the key for this Engine instance
  11904. * @return true if no such key were already present and the data was added successfully, false otherwise
  11905. */
  11906. Engine.prototype.addExternalData = function (key, data) {
  11907. if (!this._externalData) {
  11908. this._externalData = new BABYLON.StringDictionary();
  11909. }
  11910. return this._externalData.add(key, data);
  11911. };
  11912. /**
  11913. * Get an externaly attached data from its key
  11914. * @param key the unique key that identifies the data
  11915. * @return the associated data, if present (can be null), or undefined if not present
  11916. */
  11917. Engine.prototype.getExternalData = function (key) {
  11918. if (!this._externalData) {
  11919. this._externalData = new BABYLON.StringDictionary();
  11920. }
  11921. return this._externalData.get(key);
  11922. };
  11923. /**
  11924. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11925. * @param key the unique key that identifies the data
  11926. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11927. * @return the associated data, can be null if the factory returned null.
  11928. */
  11929. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11930. if (!this._externalData) {
  11931. this._externalData = new BABYLON.StringDictionary();
  11932. }
  11933. return this._externalData.getOrAddWithFactory(key, factory);
  11934. };
  11935. /**
  11936. * Remove an externaly attached data from the Engine instance
  11937. * @param key the unique key that identifies the data
  11938. * @return true if the data was successfully removed, false if it doesn't exist
  11939. */
  11940. Engine.prototype.removeExternalData = function (key) {
  11941. if (!this._externalData) {
  11942. this._externalData = new BABYLON.StringDictionary();
  11943. }
  11944. return this._externalData.remove(key);
  11945. };
  11946. Engine.prototype.unbindAllAttributes = function () {
  11947. if (this._mustWipeVertexAttributes) {
  11948. this._mustWipeVertexAttributes = false;
  11949. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11950. this._gl.disableVertexAttribArray(i);
  11951. this._vertexAttribArraysEnabled[i] = false;
  11952. this._currentBufferPointers[i].active = false;
  11953. }
  11954. return;
  11955. }
  11956. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11957. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11958. continue;
  11959. }
  11960. this._gl.disableVertexAttribArray(i);
  11961. this._vertexAttribArraysEnabled[i] = false;
  11962. this._currentBufferPointers[i].active = false;
  11963. }
  11964. };
  11965. Engine.prototype.releaseEffects = function () {
  11966. for (var name in this._compiledEffects) {
  11967. this._deleteProgram(this._compiledEffects[name]._program);
  11968. }
  11969. this._compiledEffects = {};
  11970. };
  11971. // Dispose
  11972. Engine.prototype.dispose = function () {
  11973. this.hideLoadingUI();
  11974. this.stopRenderLoop();
  11975. // Release postProcesses
  11976. while (this.postProcesses.length) {
  11977. this.postProcesses[0].dispose();
  11978. }
  11979. // Empty texture
  11980. if (this._emptyTexture) {
  11981. this._releaseTexture(this._emptyTexture);
  11982. this._emptyTexture = null;
  11983. }
  11984. if (this._emptyCubeTexture) {
  11985. this._releaseTexture(this._emptyCubeTexture);
  11986. this._emptyCubeTexture = null;
  11987. }
  11988. // Rescale PP
  11989. if (this._rescalePostProcess) {
  11990. this._rescalePostProcess.dispose();
  11991. }
  11992. // Release scenes
  11993. while (this.scenes.length) {
  11994. this.scenes[0].dispose();
  11995. }
  11996. // Release audio engine
  11997. if (Engine.audioEngine) {
  11998. Engine.audioEngine.dispose();
  11999. }
  12000. // Release effects
  12001. this.releaseEffects();
  12002. // Unbind
  12003. this.unbindAllAttributes();
  12004. if (this._dummyFramebuffer) {
  12005. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  12006. }
  12007. //WebVR
  12008. this.disableVR();
  12009. // Events
  12010. if (BABYLON.Tools.IsWindowObjectExist()) {
  12011. window.removeEventListener("blur", this._onBlur);
  12012. window.removeEventListener("focus", this._onFocus);
  12013. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  12014. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  12015. if (this._renderingCanvas) {
  12016. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  12017. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  12018. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  12019. if (!this._doNotHandleContextLost) {
  12020. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  12021. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  12022. }
  12023. }
  12024. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  12025. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  12026. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  12027. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  12028. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  12029. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  12030. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  12031. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  12032. if (this._onVrDisplayConnect) {
  12033. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12034. if (this._onVrDisplayDisconnect) {
  12035. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12036. }
  12037. if (this._onVrDisplayPresentChange) {
  12038. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12039. }
  12040. this._onVrDisplayConnect = null;
  12041. this._onVrDisplayDisconnect = null;
  12042. }
  12043. }
  12044. // Remove from Instances
  12045. var index = Engine.Instances.indexOf(this);
  12046. if (index >= 0) {
  12047. Engine.Instances.splice(index, 1);
  12048. }
  12049. this._workingCanvas = null;
  12050. this._workingContext = null;
  12051. this._currentBufferPointers = [];
  12052. this._renderingCanvas = null;
  12053. this._currentProgram = null;
  12054. this.onResizeObservable.clear();
  12055. this.onCanvasBlurObservable.clear();
  12056. this.onCanvasFocusObservable.clear();
  12057. this.onCanvasPointerOutObservable.clear();
  12058. this.onBeginFrameObservable.clear();
  12059. this.onEndFrameObservable.clear();
  12060. BABYLON.Effect.ResetCache();
  12061. };
  12062. // Loading screen
  12063. Engine.prototype.displayLoadingUI = function () {
  12064. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12065. return;
  12066. }
  12067. var loadingScreen = this.loadingScreen;
  12068. if (loadingScreen) {
  12069. loadingScreen.displayLoadingUI();
  12070. }
  12071. };
  12072. Engine.prototype.hideLoadingUI = function () {
  12073. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12074. return;
  12075. }
  12076. var loadingScreen = this.loadingScreen;
  12077. if (loadingScreen) {
  12078. loadingScreen.hideLoadingUI();
  12079. }
  12080. };
  12081. Object.defineProperty(Engine.prototype, "loadingScreen", {
  12082. get: function () {
  12083. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  12084. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  12085. return this._loadingScreen;
  12086. },
  12087. set: function (loadingScreen) {
  12088. this._loadingScreen = loadingScreen;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine.prototype, "loadingUIText", {
  12094. set: function (text) {
  12095. this.loadingScreen.loadingUIText = text;
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  12101. set: function (color) {
  12102. this.loadingScreen.loadingUIBackgroundColor = color;
  12103. },
  12104. enumerable: true,
  12105. configurable: true
  12106. });
  12107. Engine.prototype.attachContextLostEvent = function (callback) {
  12108. if (this._renderingCanvas) {
  12109. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  12110. }
  12111. };
  12112. Engine.prototype.attachContextRestoredEvent = function (callback) {
  12113. if (this._renderingCanvas) {
  12114. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  12115. }
  12116. };
  12117. Engine.prototype.getVertexShaderSource = function (program) {
  12118. var shaders = this._gl.getAttachedShaders(program);
  12119. if (!shaders) {
  12120. return null;
  12121. }
  12122. return this._gl.getShaderSource(shaders[0]);
  12123. };
  12124. Engine.prototype.getFragmentShaderSource = function (program) {
  12125. var shaders = this._gl.getAttachedShaders(program);
  12126. if (!shaders) {
  12127. return null;
  12128. }
  12129. return this._gl.getShaderSource(shaders[1]);
  12130. };
  12131. Engine.prototype.getError = function () {
  12132. return this._gl.getError();
  12133. };
  12134. // FPS
  12135. Engine.prototype.getFps = function () {
  12136. return this._fps;
  12137. };
  12138. Engine.prototype.getDeltaTime = function () {
  12139. return this._deltaTime;
  12140. };
  12141. Engine.prototype._measureFps = function () {
  12142. this._performanceMonitor.sampleFrame();
  12143. this._fps = this._performanceMonitor.averageFPS;
  12144. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12145. };
  12146. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12147. if (faceIndex === void 0) { faceIndex = -1; }
  12148. var gl = this._gl;
  12149. if (!this._dummyFramebuffer) {
  12150. var dummy = gl.createFramebuffer();
  12151. if (!dummy) {
  12152. throw new Error("Unable to create dummy framebuffer");
  12153. }
  12154. this._dummyFramebuffer = dummy;
  12155. }
  12156. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12157. if (faceIndex > -1) {
  12158. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12159. }
  12160. else {
  12161. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12162. }
  12163. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12164. var buffer;
  12165. switch (readType) {
  12166. case gl.UNSIGNED_BYTE:
  12167. buffer = new Uint8Array(4 * width * height);
  12168. readType = gl.UNSIGNED_BYTE;
  12169. break;
  12170. default:
  12171. buffer = new Float32Array(4 * width * height);
  12172. readType = gl.FLOAT;
  12173. break;
  12174. }
  12175. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12176. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12177. return buffer;
  12178. };
  12179. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12180. if (this._webGLVersion > 1) {
  12181. return this._caps.colorBufferFloat;
  12182. }
  12183. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  12184. };
  12185. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12186. if (this._webGLVersion > 1) {
  12187. return this._caps.colorBufferFloat;
  12188. }
  12189. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  12190. };
  12191. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12192. Engine.prototype._canRenderToFramebuffer = function (type) {
  12193. var gl = this._gl;
  12194. //clear existing errors
  12195. while (gl.getError() !== gl.NO_ERROR) { }
  12196. var successful = true;
  12197. var texture = gl.createTexture();
  12198. gl.bindTexture(gl.TEXTURE_2D, texture);
  12199. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12202. var fb = gl.createFramebuffer();
  12203. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12205. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12206. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12207. successful = successful && (gl.getError() === gl.NO_ERROR);
  12208. //try render by clearing frame buffer's color buffer
  12209. if (successful) {
  12210. gl.clear(gl.COLOR_BUFFER_BIT);
  12211. successful = successful && (gl.getError() === gl.NO_ERROR);
  12212. }
  12213. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12214. if (successful) {
  12215. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12216. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12217. var readFormat = gl.RGBA;
  12218. var readType = gl.UNSIGNED_BYTE;
  12219. var buffer = new Uint8Array(4);
  12220. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12221. successful = successful && (gl.getError() === gl.NO_ERROR);
  12222. }
  12223. //clean up
  12224. gl.deleteTexture(texture);
  12225. gl.deleteFramebuffer(fb);
  12226. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12227. //clear accumulated errors
  12228. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12229. return successful;
  12230. };
  12231. Engine.prototype._getWebGLTextureType = function (type) {
  12232. if (type === Engine.TEXTURETYPE_FLOAT) {
  12233. return this._gl.FLOAT;
  12234. }
  12235. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12236. // Add Half Float Constant.
  12237. return this._gl.HALF_FLOAT_OES;
  12238. }
  12239. return this._gl.UNSIGNED_BYTE;
  12240. };
  12241. ;
  12242. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12243. if (this._webGLVersion === 1) {
  12244. return this._gl.RGBA;
  12245. }
  12246. if (type === Engine.TEXTURETYPE_FLOAT) {
  12247. return this._gl.RGBA32F;
  12248. }
  12249. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12250. return this._gl.RGBA16F;
  12251. }
  12252. return this._gl.RGBA;
  12253. };
  12254. ;
  12255. Engine.prototype.createQuery = function () {
  12256. return this._gl.createQuery();
  12257. };
  12258. Engine.prototype.deleteQuery = function (query) {
  12259. this._gl.deleteQuery(query);
  12260. return this;
  12261. };
  12262. Engine.prototype.isQueryResultAvailable = function (query) {
  12263. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12264. };
  12265. Engine.prototype.getQueryResult = function (query) {
  12266. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12267. };
  12268. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12269. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12270. this._gl.beginQuery(glAlgorithm, query);
  12271. return this;
  12272. };
  12273. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12274. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12275. this._gl.endQuery(glAlgorithm);
  12276. return this;
  12277. };
  12278. /* Time queries */
  12279. Engine.prototype._createTimeQuery = function () {
  12280. var timerQuery = this._caps.timerQuery;
  12281. if (timerQuery.createQueryEXT) {
  12282. return timerQuery.createQueryEXT();
  12283. }
  12284. return this.createQuery();
  12285. };
  12286. Engine.prototype._deleteTimeQuery = function (query) {
  12287. var timerQuery = this._caps.timerQuery;
  12288. if (timerQuery.deleteQueryEXT) {
  12289. timerQuery.deleteQueryEXT(query);
  12290. return;
  12291. }
  12292. this.deleteQuery(query);
  12293. };
  12294. Engine.prototype._getTimeQueryResult = function (query) {
  12295. var timerQuery = this._caps.timerQuery;
  12296. if (timerQuery.getQueryObjectEXT) {
  12297. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12298. }
  12299. return this.getQueryResult(query);
  12300. };
  12301. Engine.prototype._getTimeQueryAvailability = function (query) {
  12302. var timerQuery = this._caps.timerQuery;
  12303. if (timerQuery.getQueryObjectEXT) {
  12304. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12305. }
  12306. return this.isQueryResultAvailable(query);
  12307. };
  12308. Engine.prototype.startTimeQuery = function () {
  12309. var timerQuery = this._caps.timerQuery;
  12310. if (!timerQuery) {
  12311. return null;
  12312. }
  12313. var token = new BABYLON._TimeToken();
  12314. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12315. if (this._caps.canUseTimestampForTimerQuery) {
  12316. token._startTimeQuery = this._createTimeQuery();
  12317. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12318. }
  12319. else {
  12320. if (this._currentNonTimestampToken) {
  12321. return this._currentNonTimestampToken;
  12322. }
  12323. token._timeElapsedQuery = this._createTimeQuery();
  12324. if (timerQuery.beginQueryEXT) {
  12325. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12326. }
  12327. else {
  12328. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12329. }
  12330. this._currentNonTimestampToken = token;
  12331. }
  12332. return token;
  12333. };
  12334. Engine.prototype.endTimeQuery = function (token) {
  12335. var timerQuery = this._caps.timerQuery;
  12336. if (!timerQuery || !token) {
  12337. return -1;
  12338. }
  12339. if (this._caps.canUseTimestampForTimerQuery) {
  12340. if (!token._startTimeQuery) {
  12341. return -1;
  12342. }
  12343. if (!token._endTimeQuery) {
  12344. token._endTimeQuery = this._createTimeQuery();
  12345. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12346. }
  12347. }
  12348. else if (!token._timeElapsedQueryEnded) {
  12349. if (!token._timeElapsedQuery) {
  12350. return -1;
  12351. }
  12352. if (timerQuery.endQueryEXT) {
  12353. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12354. }
  12355. else {
  12356. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12357. }
  12358. token._timeElapsedQueryEnded = true;
  12359. }
  12360. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12361. var available = false;
  12362. if (token._endTimeQuery) {
  12363. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12364. }
  12365. else if (token._timeElapsedQuery) {
  12366. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12367. }
  12368. if (available && !disjoint) {
  12369. var result = 0;
  12370. if (this._caps.canUseTimestampForTimerQuery) {
  12371. if (!token._startTimeQuery || !token._endTimeQuery) {
  12372. return -1;
  12373. }
  12374. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12375. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12376. result = timeEnd - timeStart;
  12377. this._deleteTimeQuery(token._startTimeQuery);
  12378. this._deleteTimeQuery(token._endTimeQuery);
  12379. token._startTimeQuery = null;
  12380. token._endTimeQuery = null;
  12381. }
  12382. else {
  12383. if (!token._timeElapsedQuery) {
  12384. return -1;
  12385. }
  12386. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12387. this._deleteTimeQuery(token._timeElapsedQuery);
  12388. token._timeElapsedQuery = null;
  12389. token._timeElapsedQueryEnded = false;
  12390. this._currentNonTimestampToken = null;
  12391. }
  12392. return result;
  12393. }
  12394. return -1;
  12395. };
  12396. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12397. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12398. };
  12399. // Transform feedback
  12400. Engine.prototype.createTransformFeedback = function () {
  12401. return this._gl.createTransformFeedback();
  12402. };
  12403. Engine.prototype.deleteTransformFeedback = function (value) {
  12404. this._gl.deleteTransformFeedback(value);
  12405. };
  12406. Engine.prototype.bindTransformFeedback = function (value) {
  12407. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12408. };
  12409. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12410. if (usePoints === void 0) { usePoints = true; }
  12411. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12412. };
  12413. Engine.prototype.endTransformFeedback = function () {
  12414. this._gl.endTransformFeedback();
  12415. };
  12416. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12417. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12418. };
  12419. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12420. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12421. };
  12422. // Statics
  12423. Engine.isSupported = function () {
  12424. try {
  12425. var tempcanvas = document.createElement("canvas");
  12426. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12427. return gl != null && !!window.WebGLRenderingContext;
  12428. }
  12429. catch (e) {
  12430. return false;
  12431. }
  12432. };
  12433. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  12434. Engine.WebGL2UniformBuffersExceptionList = ["Chrome/63"];
  12435. Engine.Instances = new Array();
  12436. // Const statics
  12437. Engine._ALPHA_DISABLE = 0;
  12438. Engine._ALPHA_ADD = 1;
  12439. Engine._ALPHA_COMBINE = 2;
  12440. Engine._ALPHA_SUBTRACT = 3;
  12441. Engine._ALPHA_MULTIPLY = 4;
  12442. Engine._ALPHA_MAXIMIZED = 5;
  12443. Engine._ALPHA_ONEONE = 6;
  12444. Engine._ALPHA_PREMULTIPLIED = 7;
  12445. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12446. Engine._ALPHA_INTERPOLATE = 9;
  12447. Engine._ALPHA_SCREENMODE = 10;
  12448. Engine._DELAYLOADSTATE_NONE = 0;
  12449. Engine._DELAYLOADSTATE_LOADED = 1;
  12450. Engine._DELAYLOADSTATE_LOADING = 2;
  12451. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12452. Engine._TEXTUREFORMAT_ALPHA = 0;
  12453. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12454. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12455. Engine._TEXTUREFORMAT_RGB = 4;
  12456. Engine._TEXTUREFORMAT_RGBA = 5;
  12457. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12458. Engine._TEXTURETYPE_FLOAT = 1;
  12459. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12460. // Depht or Stencil test Constants.
  12461. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12462. 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.
  12463. 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.
  12464. 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.
  12465. 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.
  12466. 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.
  12467. 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.
  12468. 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.
  12469. // Stencil Actions Constants.
  12470. Engine._KEEP = 0x1E00;
  12471. Engine._REPLACE = 0x1E01;
  12472. Engine._INCR = 0x1E02;
  12473. Engine._DECR = 0x1E03;
  12474. Engine._INVERT = 0x150A;
  12475. Engine._INCR_WRAP = 0x8507;
  12476. Engine._DECR_WRAP = 0x8508;
  12477. // Texture rescaling mode
  12478. Engine._SCALEMODE_FLOOR = 1;
  12479. Engine._SCALEMODE_NEAREST = 2;
  12480. Engine._SCALEMODE_CEILING = 3;
  12481. // Updatable statics so stick with vars here
  12482. Engine.CollisionsEpsilon = 0.001;
  12483. Engine.CodeRepository = "src/";
  12484. Engine.ShadersRepository = "src/Shaders/";
  12485. return Engine;
  12486. }());
  12487. BABYLON.Engine = Engine;
  12488. })(BABYLON || (BABYLON = {}));
  12489. //# sourceMappingURL=babylon.engine.js.map
  12490. var BABYLON;
  12491. (function (BABYLON) {
  12492. /**
  12493. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12494. */
  12495. var Node = /** @class */ (function () {
  12496. /**
  12497. * @constructor
  12498. * @param {string} name - the name and id to be given to this node
  12499. * @param {BABYLON.Scene} the scene this node will be added to
  12500. */
  12501. function Node(name, scene) {
  12502. if (scene === void 0) { scene = null; }
  12503. this.state = "";
  12504. this.metadata = null;
  12505. this.doNotSerialize = false;
  12506. this.animations = new Array();
  12507. this._ranges = {};
  12508. this._isEnabled = true;
  12509. this._isReady = true;
  12510. this._currentRenderId = -1;
  12511. this._parentRenderId = -1;
  12512. /**
  12513. * An event triggered when the mesh is disposed.
  12514. * @type {BABYLON.Observable}
  12515. */
  12516. this.onDisposeObservable = new BABYLON.Observable();
  12517. // Behaviors
  12518. this._behaviors = new Array();
  12519. this.name = name;
  12520. this.id = name;
  12521. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12522. this.uniqueId = this._scene.getUniqueId();
  12523. this._initCache();
  12524. }
  12525. Object.defineProperty(Node.prototype, "parent", {
  12526. get: function () {
  12527. return this._parentNode;
  12528. },
  12529. set: function (parent) {
  12530. if (this._parentNode === parent) {
  12531. return;
  12532. }
  12533. if (this._parentNode) {
  12534. var index = this._parentNode._children.indexOf(this);
  12535. if (index !== -1) {
  12536. this._parentNode._children.splice(index, 1);
  12537. }
  12538. }
  12539. this._parentNode = parent;
  12540. if (this._parentNode) {
  12541. if (!this._parentNode._children) {
  12542. this._parentNode._children = new Array();
  12543. }
  12544. this._parentNode._children.push(this);
  12545. }
  12546. },
  12547. enumerable: true,
  12548. configurable: true
  12549. });
  12550. Node.prototype.getClassName = function () {
  12551. return "Node";
  12552. };
  12553. Object.defineProperty(Node.prototype, "onDispose", {
  12554. set: function (callback) {
  12555. if (this._onDisposeObserver) {
  12556. this.onDisposeObservable.remove(this._onDisposeObserver);
  12557. }
  12558. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12559. },
  12560. enumerable: true,
  12561. configurable: true
  12562. });
  12563. Node.prototype.getScene = function () {
  12564. return this._scene;
  12565. };
  12566. Node.prototype.getEngine = function () {
  12567. return this._scene.getEngine();
  12568. };
  12569. Node.prototype.addBehavior = function (behavior) {
  12570. var _this = this;
  12571. var index = this._behaviors.indexOf(behavior);
  12572. if (index !== -1) {
  12573. return this;
  12574. }
  12575. behavior.init();
  12576. if (this._scene.isLoading) {
  12577. // We defer the attach when the scene will be loaded
  12578. var observer = this._scene.onDataLoadedObservable.add(function () {
  12579. behavior.attach(_this);
  12580. setTimeout(function () {
  12581. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  12582. _this._scene.onDataLoadedObservable.remove(observer);
  12583. }, 0);
  12584. });
  12585. }
  12586. else {
  12587. behavior.attach(this);
  12588. }
  12589. this._behaviors.push(behavior);
  12590. return this;
  12591. };
  12592. Node.prototype.removeBehavior = function (behavior) {
  12593. var index = this._behaviors.indexOf(behavior);
  12594. if (index === -1) {
  12595. return this;
  12596. }
  12597. this._behaviors[index].detach();
  12598. this._behaviors.splice(index, 1);
  12599. return this;
  12600. };
  12601. Object.defineProperty(Node.prototype, "behaviors", {
  12602. get: function () {
  12603. return this._behaviors;
  12604. },
  12605. enumerable: true,
  12606. configurable: true
  12607. });
  12608. Node.prototype.getBehaviorByName = function (name) {
  12609. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12610. var behavior = _a[_i];
  12611. if (behavior.name === name) {
  12612. return behavior;
  12613. }
  12614. }
  12615. return null;
  12616. };
  12617. // override it in derived class
  12618. Node.prototype.getWorldMatrix = function () {
  12619. return BABYLON.Matrix.Identity();
  12620. };
  12621. // override it in derived class if you add new variables to the cache
  12622. // and call the parent class method
  12623. Node.prototype._initCache = function () {
  12624. this._cache = {};
  12625. this._cache.parent = undefined;
  12626. };
  12627. Node.prototype.updateCache = function (force) {
  12628. if (!force && this.isSynchronized())
  12629. return;
  12630. this._cache.parent = this.parent;
  12631. this._updateCache();
  12632. };
  12633. // override it in derived class if you add new variables to the cache
  12634. // and call the parent class method if !ignoreParentClass
  12635. Node.prototype._updateCache = function (ignoreParentClass) {
  12636. };
  12637. // override it in derived class if you add new variables to the cache
  12638. Node.prototype._isSynchronized = function () {
  12639. return true;
  12640. };
  12641. Node.prototype._markSyncedWithParent = function () {
  12642. if (this.parent) {
  12643. this._parentRenderId = this.parent._currentRenderId;
  12644. }
  12645. };
  12646. Node.prototype.isSynchronizedWithParent = function () {
  12647. if (!this.parent) {
  12648. return true;
  12649. }
  12650. if (this._parentRenderId !== this.parent._currentRenderId) {
  12651. return false;
  12652. }
  12653. return this.parent.isSynchronized();
  12654. };
  12655. Node.prototype.isSynchronized = function (updateCache) {
  12656. var check = this.hasNewParent();
  12657. check = check || !this.isSynchronizedWithParent();
  12658. check = check || !this._isSynchronized();
  12659. if (updateCache)
  12660. this.updateCache(true);
  12661. return !check;
  12662. };
  12663. Node.prototype.hasNewParent = function (update) {
  12664. if (this._cache.parent === this.parent)
  12665. return false;
  12666. if (update)
  12667. this._cache.parent = this.parent;
  12668. return true;
  12669. };
  12670. /**
  12671. * Is this node ready to be used/rendered
  12672. * @return {boolean} is it ready
  12673. */
  12674. Node.prototype.isReady = function () {
  12675. return this._isReady;
  12676. };
  12677. /**
  12678. * Is this node enabled.
  12679. * If the node has a parent and is enabled, the parent will be inspected as well.
  12680. * @return {boolean} whether this node (and its parent) is enabled.
  12681. * @see setEnabled
  12682. */
  12683. Node.prototype.isEnabled = function () {
  12684. if (!this._isEnabled) {
  12685. return false;
  12686. }
  12687. if (this.parent) {
  12688. return this.parent.isEnabled();
  12689. }
  12690. return true;
  12691. };
  12692. /**
  12693. * Set the enabled state of this node.
  12694. * @param {boolean} value - the new enabled state
  12695. * @see isEnabled
  12696. */
  12697. Node.prototype.setEnabled = function (value) {
  12698. this._isEnabled = value;
  12699. };
  12700. /**
  12701. * Is this node a descendant of the given node.
  12702. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12703. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12704. * @see parent
  12705. */
  12706. Node.prototype.isDescendantOf = function (ancestor) {
  12707. if (this.parent) {
  12708. if (this.parent === ancestor) {
  12709. return true;
  12710. }
  12711. return this.parent.isDescendantOf(ancestor);
  12712. }
  12713. return false;
  12714. };
  12715. /**
  12716. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12717. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12718. * @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.
  12719. * @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.
  12720. */
  12721. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12722. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12723. if (!this._children) {
  12724. return;
  12725. }
  12726. for (var index = 0; index < this._children.length; index++) {
  12727. var item = this._children[index];
  12728. if (!predicate || predicate(item)) {
  12729. results.push(item);
  12730. }
  12731. if (!directDescendantsOnly) {
  12732. item._getDescendants(results, false, predicate);
  12733. }
  12734. }
  12735. };
  12736. /**
  12737. * Will return all nodes that have this node as ascendant.
  12738. * @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.
  12739. * @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.
  12740. * @return {BABYLON.Node[]} all children nodes of all types.
  12741. */
  12742. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12743. var results = new Array();
  12744. this._getDescendants(results, directDescendantsOnly, predicate);
  12745. return results;
  12746. };
  12747. /**
  12748. * Get all child-meshes of this node.
  12749. */
  12750. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12751. var results = [];
  12752. this._getDescendants(results, directDescendantsOnly, function (node) {
  12753. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12754. });
  12755. return results;
  12756. };
  12757. /**
  12758. * Get all child-transformNodes of this node.
  12759. */
  12760. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12761. var results = [];
  12762. this._getDescendants(results, directDescendantsOnly, function (node) {
  12763. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12764. });
  12765. return results;
  12766. };
  12767. /**
  12768. * Get all direct children of this node.
  12769. */
  12770. Node.prototype.getChildren = function (predicate) {
  12771. return this.getDescendants(true, predicate);
  12772. };
  12773. Node.prototype._setReady = function (state) {
  12774. if (state === this._isReady) {
  12775. return;
  12776. }
  12777. if (!state) {
  12778. this._isReady = false;
  12779. return;
  12780. }
  12781. this._isReady = true;
  12782. if (this.onReady) {
  12783. this.onReady(this);
  12784. }
  12785. };
  12786. Node.prototype.getAnimationByName = function (name) {
  12787. for (var i = 0; i < this.animations.length; i++) {
  12788. var animation = this.animations[i];
  12789. if (animation.name === name) {
  12790. return animation;
  12791. }
  12792. }
  12793. return null;
  12794. };
  12795. Node.prototype.createAnimationRange = function (name, from, to) {
  12796. // check name not already in use
  12797. if (!this._ranges[name]) {
  12798. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12799. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12800. if (this.animations[i]) {
  12801. this.animations[i].createRange(name, from, to);
  12802. }
  12803. }
  12804. }
  12805. };
  12806. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12807. if (deleteFrames === void 0) { deleteFrames = true; }
  12808. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12809. if (this.animations[i]) {
  12810. this.animations[i].deleteRange(name, deleteFrames);
  12811. }
  12812. }
  12813. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12814. };
  12815. Node.prototype.getAnimationRange = function (name) {
  12816. return this._ranges[name];
  12817. };
  12818. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12819. var range = this.getAnimationRange(name);
  12820. if (!range) {
  12821. return;
  12822. }
  12823. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12824. };
  12825. Node.prototype.serializeAnimationRanges = function () {
  12826. var serializationRanges = [];
  12827. for (var name in this._ranges) {
  12828. var localRange = this._ranges[name];
  12829. if (!localRange) {
  12830. continue;
  12831. }
  12832. var range = {};
  12833. range.name = name;
  12834. range.from = localRange.from;
  12835. range.to = localRange.to;
  12836. serializationRanges.push(range);
  12837. }
  12838. return serializationRanges;
  12839. };
  12840. // override it in derived class
  12841. Node.prototype.computeWorldMatrix = function (force) {
  12842. return BABYLON.Matrix.Identity();
  12843. };
  12844. Node.prototype.dispose = function () {
  12845. this.parent = null;
  12846. // Callback
  12847. this.onDisposeObservable.notifyObservers(this);
  12848. this.onDisposeObservable.clear();
  12849. // Behaviors
  12850. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12851. var behavior = _a[_i];
  12852. behavior.detach();
  12853. }
  12854. this._behaviors = [];
  12855. };
  12856. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12857. if (parsedNode.ranges) {
  12858. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12859. var data = parsedNode.ranges[index];
  12860. node.createAnimationRange(data.name, data.from, data.to);
  12861. }
  12862. }
  12863. };
  12864. __decorate([
  12865. BABYLON.serialize()
  12866. ], Node.prototype, "name", void 0);
  12867. __decorate([
  12868. BABYLON.serialize()
  12869. ], Node.prototype, "id", void 0);
  12870. __decorate([
  12871. BABYLON.serialize()
  12872. ], Node.prototype, "uniqueId", void 0);
  12873. __decorate([
  12874. BABYLON.serialize()
  12875. ], Node.prototype, "state", void 0);
  12876. __decorate([
  12877. BABYLON.serialize()
  12878. ], Node.prototype, "metadata", void 0);
  12879. return Node;
  12880. }());
  12881. BABYLON.Node = Node;
  12882. })(BABYLON || (BABYLON = {}));
  12883. //# sourceMappingURL=babylon.node.js.map
  12884. var BABYLON;
  12885. (function (BABYLON) {
  12886. var BoundingSphere = /** @class */ (function () {
  12887. function BoundingSphere(minimum, maximum) {
  12888. this.minimum = minimum;
  12889. this.maximum = maximum;
  12890. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12891. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12892. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12893. this.radius = distance * 0.5;
  12894. this.centerWorld = BABYLON.Vector3.Zero();
  12895. this._update(BABYLON.Matrix.Identity());
  12896. }
  12897. // Methods
  12898. BoundingSphere.prototype._update = function (world) {
  12899. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12900. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12901. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12902. };
  12903. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12904. for (var i = 0; i < 6; i++) {
  12905. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12906. return false;
  12907. }
  12908. return true;
  12909. };
  12910. BoundingSphere.prototype.intersectsPoint = function (point) {
  12911. var x = this.centerWorld.x - point.x;
  12912. var y = this.centerWorld.y - point.y;
  12913. var z = this.centerWorld.z - point.z;
  12914. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12915. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12916. return false;
  12917. return true;
  12918. };
  12919. // Statics
  12920. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12921. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12922. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12923. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12924. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12925. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12926. return false;
  12927. return true;
  12928. };
  12929. return BoundingSphere;
  12930. }());
  12931. BABYLON.BoundingSphere = BoundingSphere;
  12932. })(BABYLON || (BABYLON = {}));
  12933. //# sourceMappingURL=babylon.boundingSphere.js.map
  12934. var BABYLON;
  12935. (function (BABYLON) {
  12936. var BoundingBox = /** @class */ (function () {
  12937. function BoundingBox(minimum, maximum) {
  12938. this.minimum = minimum;
  12939. this.maximum = maximum;
  12940. this.vectors = new Array();
  12941. this.vectorsWorld = new Array();
  12942. // Bounding vectors
  12943. this.vectors.push(this.minimum.clone());
  12944. this.vectors.push(this.maximum.clone());
  12945. this.vectors.push(this.minimum.clone());
  12946. this.vectors[2].x = this.maximum.x;
  12947. this.vectors.push(this.minimum.clone());
  12948. this.vectors[3].y = this.maximum.y;
  12949. this.vectors.push(this.minimum.clone());
  12950. this.vectors[4].z = this.maximum.z;
  12951. this.vectors.push(this.maximum.clone());
  12952. this.vectors[5].z = this.minimum.z;
  12953. this.vectors.push(this.maximum.clone());
  12954. this.vectors[6].x = this.minimum.x;
  12955. this.vectors.push(this.maximum.clone());
  12956. this.vectors[7].y = this.minimum.y;
  12957. // OBB
  12958. this.center = this.maximum.add(this.minimum).scale(0.5);
  12959. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12960. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12961. // World
  12962. for (var index = 0; index < this.vectors.length; index++) {
  12963. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12964. }
  12965. this.minimumWorld = BABYLON.Vector3.Zero();
  12966. this.maximumWorld = BABYLON.Vector3.Zero();
  12967. this.centerWorld = BABYLON.Vector3.Zero();
  12968. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12969. this._update(BABYLON.Matrix.Identity());
  12970. }
  12971. // Methods
  12972. BoundingBox.prototype.getWorldMatrix = function () {
  12973. return this._worldMatrix;
  12974. };
  12975. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12976. this._worldMatrix.copyFrom(matrix);
  12977. return this;
  12978. };
  12979. BoundingBox.prototype._update = function (world) {
  12980. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12981. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12982. for (var index = 0; index < this.vectors.length; index++) {
  12983. var v = this.vectorsWorld[index];
  12984. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12985. if (v.x < this.minimumWorld.x)
  12986. this.minimumWorld.x = v.x;
  12987. if (v.y < this.minimumWorld.y)
  12988. this.minimumWorld.y = v.y;
  12989. if (v.z < this.minimumWorld.z)
  12990. this.minimumWorld.z = v.z;
  12991. if (v.x > this.maximumWorld.x)
  12992. this.maximumWorld.x = v.x;
  12993. if (v.y > this.maximumWorld.y)
  12994. this.maximumWorld.y = v.y;
  12995. if (v.z > this.maximumWorld.z)
  12996. this.maximumWorld.z = v.z;
  12997. }
  12998. // Extend
  12999. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  13000. this.extendSizeWorld.scaleInPlace(0.5);
  13001. // OBB
  13002. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  13003. this.centerWorld.scaleInPlace(0.5);
  13004. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  13005. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  13006. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  13007. this._worldMatrix = world;
  13008. };
  13009. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  13010. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  13011. };
  13012. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13013. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  13014. };
  13015. BoundingBox.prototype.intersectsPoint = function (point) {
  13016. var delta = -BABYLON.Epsilon;
  13017. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  13018. return false;
  13019. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  13020. return false;
  13021. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  13022. return false;
  13023. return true;
  13024. };
  13025. BoundingBox.prototype.intersectsSphere = function (sphere) {
  13026. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  13027. };
  13028. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  13029. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  13030. return false;
  13031. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  13032. return false;
  13033. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  13034. return false;
  13035. return true;
  13036. };
  13037. // Statics
  13038. BoundingBox.Intersects = function (box0, box1) {
  13039. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  13040. return false;
  13041. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  13042. return false;
  13043. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  13044. return false;
  13045. return true;
  13046. };
  13047. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  13048. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  13049. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  13050. return (num <= (sphereRadius * sphereRadius));
  13051. };
  13052. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  13053. for (var p = 0; p < 6; p++) {
  13054. for (var i = 0; i < 8; i++) {
  13055. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13056. return false;
  13057. }
  13058. }
  13059. }
  13060. return true;
  13061. };
  13062. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  13063. for (var p = 0; p < 6; p++) {
  13064. var inCount = 8;
  13065. for (var i = 0; i < 8; i++) {
  13066. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13067. --inCount;
  13068. }
  13069. else {
  13070. break;
  13071. }
  13072. }
  13073. if (inCount === 0)
  13074. return false;
  13075. }
  13076. return true;
  13077. };
  13078. return BoundingBox;
  13079. }());
  13080. BABYLON.BoundingBox = BoundingBox;
  13081. })(BABYLON || (BABYLON = {}));
  13082. //# sourceMappingURL=babylon.boundingBox.js.map
  13083. var BABYLON;
  13084. (function (BABYLON) {
  13085. var computeBoxExtents = function (axis, box) {
  13086. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  13087. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  13088. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  13089. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  13090. var r = r0 + r1 + r2;
  13091. return {
  13092. min: p - r,
  13093. max: p + r
  13094. };
  13095. };
  13096. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  13097. var axisOverlap = function (axis, box0, box1) {
  13098. var result0 = computeBoxExtents(axis, box0);
  13099. var result1 = computeBoxExtents(axis, box1);
  13100. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  13101. };
  13102. var BoundingInfo = /** @class */ (function () {
  13103. function BoundingInfo(minimum, maximum) {
  13104. this.minimum = minimum;
  13105. this.maximum = maximum;
  13106. this._isLocked = false;
  13107. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  13108. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  13109. }
  13110. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  13111. get: function () {
  13112. return this._isLocked;
  13113. },
  13114. set: function (value) {
  13115. this._isLocked = value;
  13116. },
  13117. enumerable: true,
  13118. configurable: true
  13119. });
  13120. // Methods
  13121. BoundingInfo.prototype.update = function (world) {
  13122. if (this._isLocked) {
  13123. return;
  13124. }
  13125. this.boundingBox._update(world);
  13126. this.boundingSphere._update(world);
  13127. };
  13128. /**
  13129. * Recreate the bounding info to be centered around a specific point given a specific extend.
  13130. * @param center New center of the bounding info
  13131. * @param extend New extend of the bounding info
  13132. */
  13133. BoundingInfo.prototype.centerOn = function (center, extend) {
  13134. this.minimum = center.subtract(extend);
  13135. this.maximum = center.add(extend);
  13136. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13137. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13138. return this;
  13139. };
  13140. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13141. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13142. return false;
  13143. return this.boundingBox.isInFrustum(frustumPlanes);
  13144. };
  13145. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13146. /**
  13147. * Gets the world distance between the min and max points of the bounding box
  13148. */
  13149. get: function () {
  13150. var boundingBox = this.boundingBox;
  13151. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13152. return size.length();
  13153. },
  13154. enumerable: true,
  13155. configurable: true
  13156. });
  13157. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13158. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13159. };
  13160. BoundingInfo.prototype._checkCollision = function (collider) {
  13161. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13162. };
  13163. BoundingInfo.prototype.intersectsPoint = function (point) {
  13164. if (!this.boundingSphere.centerWorld) {
  13165. return false;
  13166. }
  13167. if (!this.boundingSphere.intersectsPoint(point)) {
  13168. return false;
  13169. }
  13170. if (!this.boundingBox.intersectsPoint(point)) {
  13171. return false;
  13172. }
  13173. return true;
  13174. };
  13175. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13176. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13177. return false;
  13178. }
  13179. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13180. return false;
  13181. }
  13182. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13183. return false;
  13184. }
  13185. if (!precise) {
  13186. return true;
  13187. }
  13188. var box0 = this.boundingBox;
  13189. var box1 = boundingInfo.boundingBox;
  13190. if (!axisOverlap(box0.directions[0], box0, box1))
  13191. return false;
  13192. if (!axisOverlap(box0.directions[1], box0, box1))
  13193. return false;
  13194. if (!axisOverlap(box0.directions[2], box0, box1))
  13195. return false;
  13196. if (!axisOverlap(box1.directions[0], box0, box1))
  13197. return false;
  13198. if (!axisOverlap(box1.directions[1], box0, box1))
  13199. return false;
  13200. if (!axisOverlap(box1.directions[2], box0, box1))
  13201. return false;
  13202. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13203. return false;
  13204. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13205. return false;
  13206. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13207. return false;
  13208. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13209. return false;
  13210. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13211. return false;
  13212. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13213. return false;
  13214. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13215. return false;
  13216. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13217. return false;
  13218. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13219. return false;
  13220. return true;
  13221. };
  13222. return BoundingInfo;
  13223. }());
  13224. BABYLON.BoundingInfo = BoundingInfo;
  13225. })(BABYLON || (BABYLON = {}));
  13226. //# sourceMappingURL=babylon.boundingInfo.js.map
  13227. var BABYLON;
  13228. (function (BABYLON) {
  13229. var TransformNode = /** @class */ (function (_super) {
  13230. __extends(TransformNode, _super);
  13231. function TransformNode(name, scene, isPure) {
  13232. if (scene === void 0) { scene = null; }
  13233. if (isPure === void 0) { isPure = true; }
  13234. var _this = _super.call(this, name, scene) || this;
  13235. // Properties
  13236. _this._rotation = BABYLON.Vector3.Zero();
  13237. _this._scaling = BABYLON.Vector3.One();
  13238. _this._isDirty = false;
  13239. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13240. _this.scalingDeterminant = 1;
  13241. _this.infiniteDistance = false;
  13242. _this.position = BABYLON.Vector3.Zero();
  13243. _this._localWorld = BABYLON.Matrix.Zero();
  13244. _this._worldMatrix = BABYLON.Matrix.Zero();
  13245. _this._absolutePosition = BABYLON.Vector3.Zero();
  13246. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13247. _this._postMultiplyPivotMatrix = false;
  13248. _this._isWorldMatrixFrozen = false;
  13249. /**
  13250. * An event triggered after the world matrix is updated
  13251. * @type {BABYLON.Observable}
  13252. */
  13253. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13254. _this._nonUniformScaling = false;
  13255. if (isPure) {
  13256. _this.getScene().addTransformNode(_this);
  13257. }
  13258. return _this;
  13259. }
  13260. Object.defineProperty(TransformNode.prototype, "rotation", {
  13261. /**
  13262. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13263. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13264. * Default : (0.0, 0.0, 0.0)
  13265. */
  13266. get: function () {
  13267. return this._rotation;
  13268. },
  13269. set: function (newRotation) {
  13270. this._rotation = newRotation;
  13271. },
  13272. enumerable: true,
  13273. configurable: true
  13274. });
  13275. Object.defineProperty(TransformNode.prototype, "scaling", {
  13276. /**
  13277. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13278. * Default : (1.0, 1.0, 1.0)
  13279. */
  13280. get: function () {
  13281. return this._scaling;
  13282. },
  13283. /**
  13284. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13285. * Default : (1.0, 1.0, 1.0)
  13286. */
  13287. set: function (newScaling) {
  13288. this._scaling = newScaling;
  13289. },
  13290. enumerable: true,
  13291. configurable: true
  13292. });
  13293. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13294. /**
  13295. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13296. * It's null by default.
  13297. * 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)
  13298. */
  13299. get: function () {
  13300. return this._rotationQuaternion;
  13301. },
  13302. set: function (quaternion) {
  13303. this._rotationQuaternion = quaternion;
  13304. //reset the rotation vector.
  13305. if (quaternion && this.rotation.length()) {
  13306. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13307. }
  13308. },
  13309. enumerable: true,
  13310. configurable: true
  13311. });
  13312. /**
  13313. * Returns the latest update of the World matrix
  13314. * Returns a Matrix.
  13315. */
  13316. TransformNode.prototype.getWorldMatrix = function () {
  13317. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13318. this.computeWorldMatrix();
  13319. }
  13320. return this._worldMatrix;
  13321. };
  13322. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13323. /**
  13324. * Returns directly the latest state of the mesh World matrix.
  13325. * A Matrix is returned.
  13326. */
  13327. get: function () {
  13328. return this._worldMatrix;
  13329. },
  13330. enumerable: true,
  13331. configurable: true
  13332. });
  13333. /**
  13334. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13335. * Returns the AbstractMesh.
  13336. */
  13337. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13338. this._poseMatrix.copyFrom(matrix);
  13339. return this;
  13340. };
  13341. /**
  13342. * Returns the mesh Pose matrix.
  13343. * Returned object : Matrix
  13344. */
  13345. TransformNode.prototype.getPoseMatrix = function () {
  13346. return this._poseMatrix;
  13347. };
  13348. TransformNode.prototype._isSynchronized = function () {
  13349. if (this._isDirty) {
  13350. return false;
  13351. }
  13352. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13353. return false;
  13354. if (this._cache.pivotMatrixUpdated) {
  13355. return false;
  13356. }
  13357. if (this.infiniteDistance) {
  13358. return false;
  13359. }
  13360. if (!this._cache.position.equals(this.position))
  13361. return false;
  13362. if (this.rotationQuaternion) {
  13363. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13364. return false;
  13365. }
  13366. if (!this._cache.rotation.equals(this.rotation))
  13367. return false;
  13368. if (!this._cache.scaling.equals(this.scaling))
  13369. return false;
  13370. return true;
  13371. };
  13372. TransformNode.prototype._initCache = function () {
  13373. _super.prototype._initCache.call(this);
  13374. this._cache.localMatrixUpdated = false;
  13375. this._cache.position = BABYLON.Vector3.Zero();
  13376. this._cache.scaling = BABYLON.Vector3.Zero();
  13377. this._cache.rotation = BABYLON.Vector3.Zero();
  13378. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13379. this._cache.billboardMode = -1;
  13380. };
  13381. TransformNode.prototype.markAsDirty = function (property) {
  13382. if (property === "rotation") {
  13383. this.rotationQuaternion = null;
  13384. }
  13385. this._currentRenderId = Number.MAX_VALUE;
  13386. this._isDirty = true;
  13387. return this;
  13388. };
  13389. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13390. /**
  13391. * Returns the current mesh absolute position.
  13392. * Retuns a Vector3.
  13393. */
  13394. get: function () {
  13395. return this._absolutePosition;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. /**
  13401. * Sets a new pivot matrix to the mesh.
  13402. * Returns the AbstractMesh.
  13403. */
  13404. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13405. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13406. this._pivotMatrix = matrix.clone();
  13407. this._cache.pivotMatrixUpdated = true;
  13408. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13409. if (this._postMultiplyPivotMatrix) {
  13410. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13411. }
  13412. return this;
  13413. };
  13414. /**
  13415. * Returns the mesh pivot matrix.
  13416. * Default : Identity.
  13417. * A Matrix is returned.
  13418. */
  13419. TransformNode.prototype.getPivotMatrix = function () {
  13420. return this._pivotMatrix;
  13421. };
  13422. /**
  13423. * Prevents the World matrix to be computed any longer.
  13424. * Returns the AbstractMesh.
  13425. */
  13426. TransformNode.prototype.freezeWorldMatrix = function () {
  13427. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13428. this.computeWorldMatrix(true);
  13429. this._isWorldMatrixFrozen = true;
  13430. return this;
  13431. };
  13432. /**
  13433. * Allows back the World matrix computation.
  13434. * Returns the AbstractMesh.
  13435. */
  13436. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13437. this._isWorldMatrixFrozen = false;
  13438. this.computeWorldMatrix(true);
  13439. return this;
  13440. };
  13441. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13442. /**
  13443. * True if the World matrix has been frozen.
  13444. * Returns a boolean.
  13445. */
  13446. get: function () {
  13447. return this._isWorldMatrixFrozen;
  13448. },
  13449. enumerable: true,
  13450. configurable: true
  13451. });
  13452. /**
  13453. * Retuns the mesh absolute position in the World.
  13454. * Returns a Vector3.
  13455. */
  13456. TransformNode.prototype.getAbsolutePosition = function () {
  13457. this.computeWorldMatrix();
  13458. return this._absolutePosition;
  13459. };
  13460. /**
  13461. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13462. * Returns the AbstractMesh.
  13463. */
  13464. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13465. if (!absolutePosition) {
  13466. return this;
  13467. }
  13468. var absolutePositionX;
  13469. var absolutePositionY;
  13470. var absolutePositionZ;
  13471. if (absolutePosition.x === undefined) {
  13472. if (arguments.length < 3) {
  13473. return this;
  13474. }
  13475. absolutePositionX = arguments[0];
  13476. absolutePositionY = arguments[1];
  13477. absolutePositionZ = arguments[2];
  13478. }
  13479. else {
  13480. absolutePositionX = absolutePosition.x;
  13481. absolutePositionY = absolutePosition.y;
  13482. absolutePositionZ = absolutePosition.z;
  13483. }
  13484. if (this.parent) {
  13485. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13486. invertParentWorldMatrix.invert();
  13487. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13488. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13489. }
  13490. else {
  13491. this.position.x = absolutePositionX;
  13492. this.position.y = absolutePositionY;
  13493. this.position.z = absolutePositionZ;
  13494. }
  13495. return this;
  13496. };
  13497. /**
  13498. * Sets the mesh position in its local space.
  13499. * Returns the AbstractMesh.
  13500. */
  13501. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13502. this.computeWorldMatrix();
  13503. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13504. return this;
  13505. };
  13506. /**
  13507. * Returns the mesh position in the local space from the current World matrix values.
  13508. * Returns a new Vector3.
  13509. */
  13510. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13511. this.computeWorldMatrix();
  13512. var invLocalWorldMatrix = this._localWorld.clone();
  13513. invLocalWorldMatrix.invert();
  13514. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13515. };
  13516. /**
  13517. * Translates the mesh along the passed Vector3 in its local space.
  13518. * Returns the AbstractMesh.
  13519. */
  13520. TransformNode.prototype.locallyTranslate = function (vector3) {
  13521. this.computeWorldMatrix(true);
  13522. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13523. return this;
  13524. };
  13525. /**
  13526. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13527. * @param targetPoint the position (must be in same space as current mesh) to look at
  13528. * @param yawCor optional yaw (y-axis) correction in radians
  13529. * @param pitchCor optional pitch (x-axis) correction in radians
  13530. * @param rollCor optional roll (z-axis) correction in radians
  13531. * @param space the choosen space of the target
  13532. * @returns the TransformNode.
  13533. */
  13534. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13535. if (yawCor === void 0) { yawCor = 0; }
  13536. if (pitchCor === void 0) { pitchCor = 0; }
  13537. if (rollCor === void 0) { rollCor = 0; }
  13538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13539. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13540. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13541. targetPoint.subtractToRef(pos, dv);
  13542. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13543. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13544. var pitch = Math.atan2(dv.y, len);
  13545. if (this.rotationQuaternion) {
  13546. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13547. }
  13548. else {
  13549. this.rotation.x = pitch + pitchCor;
  13550. this.rotation.y = yaw + yawCor;
  13551. this.rotation.z = rollCor;
  13552. }
  13553. return this;
  13554. };
  13555. /**
  13556. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13557. * This Vector3 is expressed in the World space.
  13558. */
  13559. TransformNode.prototype.getDirection = function (localAxis) {
  13560. var result = BABYLON.Vector3.Zero();
  13561. this.getDirectionToRef(localAxis, result);
  13562. return result;
  13563. };
  13564. /**
  13565. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13566. * localAxis is expressed in the mesh local space.
  13567. * result is computed in the Wordl space from the mesh World matrix.
  13568. * Returns the AbstractMesh.
  13569. */
  13570. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13571. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13572. return this;
  13573. };
  13574. TransformNode.prototype.setPivotPoint = function (point, space) {
  13575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13576. if (this.getScene().getRenderId() == 0) {
  13577. this.computeWorldMatrix(true);
  13578. }
  13579. var wm = this.getWorldMatrix();
  13580. if (space == BABYLON.Space.WORLD) {
  13581. var tmat = BABYLON.Tmp.Matrix[0];
  13582. wm.invertToRef(tmat);
  13583. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13584. }
  13585. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13586. this._pivotMatrix.m[12] = -point.x;
  13587. this._pivotMatrix.m[13] = -point.y;
  13588. this._pivotMatrix.m[14] = -point.z;
  13589. this._cache.pivotMatrixUpdated = true;
  13590. return this;
  13591. };
  13592. /**
  13593. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13594. */
  13595. TransformNode.prototype.getPivotPoint = function () {
  13596. var point = BABYLON.Vector3.Zero();
  13597. this.getPivotPointToRef(point);
  13598. return point;
  13599. };
  13600. /**
  13601. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13602. * Returns the AbstractMesh.
  13603. */
  13604. TransformNode.prototype.getPivotPointToRef = function (result) {
  13605. result.x = -this._pivotMatrix.m[12];
  13606. result.y = -this._pivotMatrix.m[13];
  13607. result.z = -this._pivotMatrix.m[14];
  13608. return this;
  13609. };
  13610. /**
  13611. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13612. */
  13613. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13614. var point = BABYLON.Vector3.Zero();
  13615. this.getAbsolutePivotPointToRef(point);
  13616. return point;
  13617. };
  13618. /**
  13619. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13620. * Returns the AbstractMesh.
  13621. */
  13622. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13623. result.x = this._pivotMatrix.m[12];
  13624. result.y = this._pivotMatrix.m[13];
  13625. result.z = this._pivotMatrix.m[14];
  13626. this.getPivotPointToRef(result);
  13627. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13628. return this;
  13629. };
  13630. /**
  13631. * Defines the passed node as the parent of the current node.
  13632. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13633. * Returns the TransformNode.
  13634. */
  13635. TransformNode.prototype.setParent = function (node) {
  13636. if (node == null) {
  13637. var rotation = BABYLON.Tmp.Quaternion[0];
  13638. var position = BABYLON.Tmp.Vector3[0];
  13639. var scale = BABYLON.Tmp.Vector3[1];
  13640. if (this.parent && this.parent.computeWorldMatrix) {
  13641. this.parent.computeWorldMatrix(true);
  13642. }
  13643. this.computeWorldMatrix(true);
  13644. this.getWorldMatrix().decompose(scale, rotation, position);
  13645. if (this.rotationQuaternion) {
  13646. this.rotationQuaternion.copyFrom(rotation);
  13647. }
  13648. else {
  13649. rotation.toEulerAnglesToRef(this.rotation);
  13650. }
  13651. this.scaling.x = scale.x;
  13652. this.scaling.y = scale.y;
  13653. this.scaling.z = scale.z;
  13654. this.position.x = position.x;
  13655. this.position.y = position.y;
  13656. this.position.z = position.z;
  13657. }
  13658. else {
  13659. var rotation = BABYLON.Tmp.Quaternion[0];
  13660. var position = BABYLON.Tmp.Vector3[0];
  13661. var scale = BABYLON.Tmp.Vector3[1];
  13662. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13663. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13664. this.computeWorldMatrix(true);
  13665. node.computeWorldMatrix(true);
  13666. node.getWorldMatrix().invertToRef(invParentMatrix);
  13667. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13668. diffMatrix.decompose(scale, rotation, position);
  13669. if (this.rotationQuaternion) {
  13670. this.rotationQuaternion.copyFrom(rotation);
  13671. }
  13672. else {
  13673. rotation.toEulerAnglesToRef(this.rotation);
  13674. }
  13675. this.position.x = position.x;
  13676. this.position.y = position.y;
  13677. this.position.z = position.z;
  13678. this.scaling.x = scale.x;
  13679. this.scaling.y = scale.y;
  13680. this.scaling.z = scale.z;
  13681. }
  13682. this.parent = node;
  13683. return this;
  13684. };
  13685. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13686. get: function () {
  13687. return this._nonUniformScaling;
  13688. },
  13689. enumerable: true,
  13690. configurable: true
  13691. });
  13692. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13693. if (this._nonUniformScaling === value) {
  13694. return false;
  13695. }
  13696. this._nonUniformScaling = true;
  13697. return true;
  13698. };
  13699. /**
  13700. * Attach the current TransformNode to another TransformNode associated with a bone
  13701. * @param bone Bone affecting the TransformNode
  13702. * @param affectedTransformNode TransformNode associated with the bone
  13703. */
  13704. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13705. this._transformToBoneReferal = affectedTransformNode;
  13706. this.parent = bone;
  13707. if (bone.getWorldMatrix().determinant() < 0) {
  13708. this.scalingDeterminant *= -1;
  13709. }
  13710. return this;
  13711. };
  13712. TransformNode.prototype.detachFromBone = function () {
  13713. if (!this.parent) {
  13714. return this;
  13715. }
  13716. if (this.parent.getWorldMatrix().determinant() < 0) {
  13717. this.scalingDeterminant *= -1;
  13718. }
  13719. this._transformToBoneReferal = null;
  13720. this.parent = null;
  13721. return this;
  13722. };
  13723. /**
  13724. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13725. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13726. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13727. * The passed axis is also normalized.
  13728. * Returns the AbstractMesh.
  13729. */
  13730. TransformNode.prototype.rotate = function (axis, amount, space) {
  13731. axis.normalize();
  13732. if (!this.rotationQuaternion) {
  13733. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13734. this.rotation = BABYLON.Vector3.Zero();
  13735. }
  13736. var rotationQuaternion;
  13737. if (!space || space === BABYLON.Space.LOCAL) {
  13738. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13739. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13740. }
  13741. else {
  13742. if (this.parent) {
  13743. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13744. invertParentWorldMatrix.invert();
  13745. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13746. }
  13747. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13748. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13749. }
  13750. return this;
  13751. };
  13752. /**
  13753. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13754. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13755. * The passed axis is also normalized.
  13756. * Returns the AbstractMesh.
  13757. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13758. */
  13759. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13760. axis.normalize();
  13761. if (!this.rotationQuaternion) {
  13762. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13763. this.rotation.copyFromFloats(0, 0, 0);
  13764. }
  13765. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13766. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13767. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13768. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13769. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13770. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13771. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13772. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13773. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13774. return this;
  13775. };
  13776. /**
  13777. * Translates the mesh along the axis vector for the passed distance in the given space.
  13778. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13779. * Returns the AbstractMesh.
  13780. */
  13781. TransformNode.prototype.translate = function (axis, distance, space) {
  13782. var displacementVector = axis.scale(distance);
  13783. if (!space || space === BABYLON.Space.LOCAL) {
  13784. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13785. this.setPositionWithLocalVector(tempV3);
  13786. }
  13787. else {
  13788. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13789. }
  13790. return this;
  13791. };
  13792. /**
  13793. * Adds a rotation step to the mesh current rotation.
  13794. * x, y, z are Euler angles expressed in radians.
  13795. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13796. * This means this rotation is made in the mesh local space only.
  13797. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13798. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13799. * ```javascript
  13800. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13801. * ```
  13802. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13803. * 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.
  13804. * Returns the AbstractMesh.
  13805. */
  13806. TransformNode.prototype.addRotation = function (x, y, z) {
  13807. var rotationQuaternion;
  13808. if (this.rotationQuaternion) {
  13809. rotationQuaternion = this.rotationQuaternion;
  13810. }
  13811. else {
  13812. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13813. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13814. }
  13815. var accumulation = BABYLON.Tmp.Quaternion[0];
  13816. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13817. rotationQuaternion.multiplyInPlace(accumulation);
  13818. if (!this.rotationQuaternion) {
  13819. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13820. }
  13821. return this;
  13822. };
  13823. /**
  13824. * Computes the mesh World matrix and returns it.
  13825. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13826. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13827. * If the parameter `force`is set to `true`, the actual computation is done.
  13828. * Returns the mesh World Matrix.
  13829. */
  13830. TransformNode.prototype.computeWorldMatrix = function (force) {
  13831. if (this._isWorldMatrixFrozen) {
  13832. return this._worldMatrix;
  13833. }
  13834. if (!force && this.isSynchronized(true)) {
  13835. return this._worldMatrix;
  13836. }
  13837. this._cache.position.copyFrom(this.position);
  13838. this._cache.scaling.copyFrom(this.scaling);
  13839. this._cache.pivotMatrixUpdated = false;
  13840. this._cache.billboardMode = this.billboardMode;
  13841. this._currentRenderId = this.getScene().getRenderId();
  13842. this._isDirty = false;
  13843. // Scaling
  13844. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13845. // Rotation
  13846. //rotate, if quaternion is set and rotation was used
  13847. if (this.rotationQuaternion) {
  13848. var len = this.rotation.length();
  13849. if (len) {
  13850. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13851. this.rotation.copyFromFloats(0, 0, 0);
  13852. }
  13853. }
  13854. if (this.rotationQuaternion) {
  13855. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13856. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13857. }
  13858. else {
  13859. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13860. this._cache.rotation.copyFrom(this.rotation);
  13861. }
  13862. // Translation
  13863. var camera = this.getScene().activeCamera;
  13864. if (this.infiniteDistance && !this.parent && camera) {
  13865. var cameraWorldMatrix = camera.getWorldMatrix();
  13866. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13867. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13868. }
  13869. else {
  13870. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13871. }
  13872. // Composing transformations
  13873. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13874. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13875. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13876. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13877. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13878. // Need to decompose each rotation here
  13879. var currentPosition = BABYLON.Tmp.Vector3[3];
  13880. if (this.parent && this.parent.getWorldMatrix) {
  13881. if (this._transformToBoneReferal) {
  13882. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13883. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13884. }
  13885. else {
  13886. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13887. }
  13888. }
  13889. else {
  13890. currentPosition.copyFrom(this.position);
  13891. }
  13892. currentPosition.subtractInPlace(camera.globalPosition);
  13893. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13894. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13895. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13896. }
  13897. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13898. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13899. }
  13900. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13901. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13902. }
  13903. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13904. }
  13905. else {
  13906. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13907. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13908. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13909. }
  13910. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13911. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13912. }
  13913. // Local world
  13914. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13915. // Parent
  13916. if (this.parent && this.parent.getWorldMatrix) {
  13917. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13918. if (this._transformToBoneReferal) {
  13919. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13920. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13921. }
  13922. else {
  13923. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13924. }
  13925. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13926. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13927. this._worldMatrix.copyFrom(this._localWorld);
  13928. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13929. }
  13930. else {
  13931. if (this._transformToBoneReferal) {
  13932. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13933. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13934. }
  13935. else {
  13936. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13937. }
  13938. }
  13939. this._markSyncedWithParent();
  13940. }
  13941. else {
  13942. this._worldMatrix.copyFrom(this._localWorld);
  13943. }
  13944. // Post multiply inverse of pivotMatrix
  13945. if (this._postMultiplyPivotMatrix) {
  13946. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13947. }
  13948. // Normal matrix
  13949. if (this.scaling.isNonUniform) {
  13950. this._updateNonUniformScalingState(true);
  13951. }
  13952. else if (this.parent && this.parent._nonUniformScaling) {
  13953. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13954. }
  13955. else {
  13956. this._updateNonUniformScalingState(false);
  13957. }
  13958. this._afterComputeWorldMatrix();
  13959. // Absolute position
  13960. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13961. // Callbacks
  13962. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13963. if (!this._poseMatrix) {
  13964. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13965. }
  13966. return this._worldMatrix;
  13967. };
  13968. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13969. };
  13970. /**
  13971. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13972. * @param func: callback function to add
  13973. *
  13974. * Returns the TransformNode.
  13975. */
  13976. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13977. this.onAfterWorldMatrixUpdateObservable.add(func);
  13978. return this;
  13979. };
  13980. /**
  13981. * Removes a registered callback function.
  13982. * Returns the TransformNode.
  13983. */
  13984. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13985. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13986. return this;
  13987. };
  13988. /**
  13989. * Clone the current transform node
  13990. * Returns the new transform node
  13991. * @param name Name of the new clone
  13992. * @param newParent New parent for the clone
  13993. * @param doNotCloneChildren Do not clone children hierarchy
  13994. */
  13995. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13996. var _this = this;
  13997. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13998. result.name = name;
  13999. result.id = name;
  14000. if (newParent) {
  14001. result.parent = newParent;
  14002. }
  14003. if (!doNotCloneChildren) {
  14004. // Children
  14005. var directDescendants = this.getDescendants(true);
  14006. for (var index = 0; index < directDescendants.length; index++) {
  14007. var child = directDescendants[index];
  14008. if (child.clone) {
  14009. child.clone(name + "." + child.name, result);
  14010. }
  14011. }
  14012. }
  14013. return result;
  14014. };
  14015. TransformNode.prototype.serialize = function (currentSerializationObject) {
  14016. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  14017. serializationObject.type = this.getClassName();
  14018. // Parent
  14019. if (this.parent) {
  14020. serializationObject.parentId = this.parent.id;
  14021. }
  14022. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  14023. serializationObject.tags = BABYLON.Tags.GetTags(this);
  14024. }
  14025. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  14026. serializationObject.isEnabled = this.isEnabled();
  14027. // Parent
  14028. if (this.parent) {
  14029. serializationObject.parentId = this.parent.id;
  14030. }
  14031. return serializationObject;
  14032. };
  14033. // Statics
  14034. /**
  14035. * Returns a new TransformNode object parsed from the source provided.
  14036. * The parameter `parsedMesh` is the source.
  14037. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  14038. */
  14039. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  14040. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  14041. if (BABYLON.Tags) {
  14042. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  14043. }
  14044. if (parsedTransformNode.localMatrix) {
  14045. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  14046. }
  14047. else if (parsedTransformNode.pivotMatrix) {
  14048. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  14049. }
  14050. transformNode.setEnabled(parsedTransformNode.isEnabled);
  14051. // Parent
  14052. if (parsedTransformNode.parentId) {
  14053. transformNode._waitingParentId = parsedTransformNode.parentId;
  14054. }
  14055. return transformNode;
  14056. };
  14057. /**
  14058. * Disposes the TransformNode.
  14059. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14060. * Returns nothing.
  14061. */
  14062. TransformNode.prototype.dispose = function (doNotRecurse) {
  14063. // Animations
  14064. this.getScene().stopAnimation(this);
  14065. // Remove from scene
  14066. this.getScene().removeTransformNode(this);
  14067. this._cache = {};
  14068. if (!doNotRecurse) {
  14069. // Children
  14070. var objects = this.getDescendants(true);
  14071. for (var index = 0; index < objects.length; index++) {
  14072. objects[index].dispose();
  14073. }
  14074. }
  14075. else {
  14076. var childMeshes = this.getChildMeshes(true);
  14077. for (index = 0; index < childMeshes.length; index++) {
  14078. var child = childMeshes[index];
  14079. child.parent = null;
  14080. child.computeWorldMatrix(true);
  14081. }
  14082. }
  14083. this.onAfterWorldMatrixUpdateObservable.clear();
  14084. _super.prototype.dispose.call(this);
  14085. };
  14086. // Statics
  14087. TransformNode.BILLBOARDMODE_NONE = 0;
  14088. TransformNode.BILLBOARDMODE_X = 1;
  14089. TransformNode.BILLBOARDMODE_Y = 2;
  14090. TransformNode.BILLBOARDMODE_Z = 4;
  14091. TransformNode.BILLBOARDMODE_ALL = 7;
  14092. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14093. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  14094. __decorate([
  14095. BABYLON.serializeAsVector3()
  14096. ], TransformNode.prototype, "_rotation", void 0);
  14097. __decorate([
  14098. BABYLON.serializeAsQuaternion()
  14099. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  14100. __decorate([
  14101. BABYLON.serializeAsVector3()
  14102. ], TransformNode.prototype, "_scaling", void 0);
  14103. __decorate([
  14104. BABYLON.serialize()
  14105. ], TransformNode.prototype, "billboardMode", void 0);
  14106. __decorate([
  14107. BABYLON.serialize()
  14108. ], TransformNode.prototype, "scalingDeterminant", void 0);
  14109. __decorate([
  14110. BABYLON.serialize()
  14111. ], TransformNode.prototype, "infiniteDistance", void 0);
  14112. __decorate([
  14113. BABYLON.serializeAsVector3()
  14114. ], TransformNode.prototype, "position", void 0);
  14115. return TransformNode;
  14116. }(BABYLON.Node));
  14117. BABYLON.TransformNode = TransformNode;
  14118. })(BABYLON || (BABYLON = {}));
  14119. //# sourceMappingURL=babylon.transformNode.js.map
  14120. var BABYLON;
  14121. (function (BABYLON) {
  14122. var AbstractMesh = /** @class */ (function (_super) {
  14123. __extends(AbstractMesh, _super);
  14124. // Constructor
  14125. function AbstractMesh(name, scene) {
  14126. if (scene === void 0) { scene = null; }
  14127. var _this = _super.call(this, name, scene, false) || this;
  14128. _this._facetNb = 0; // facet number
  14129. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  14130. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  14131. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  14132. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  14133. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  14134. _this._subDiv = {
  14135. max: 1,
  14136. X: 1,
  14137. Y: 1,
  14138. Z: 1
  14139. };
  14140. _this._facetDepthSort = false; // is the facet depth sort to be computed
  14141. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  14142. // Events
  14143. /**
  14144. * An event triggered when this mesh collides with another one
  14145. * @type {BABYLON.Observable}
  14146. */
  14147. _this.onCollideObservable = new BABYLON.Observable();
  14148. /**
  14149. * An event triggered when the collision's position changes
  14150. * @type {BABYLON.Observable}
  14151. */
  14152. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14153. /**
  14154. * An event triggered when material is changed
  14155. * @type {BABYLON.Observable}
  14156. */
  14157. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14158. // Properties
  14159. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14160. /**
  14161. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14162. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14163. * or
  14164. * 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.
  14165. * for more info check WebGl documentations
  14166. */
  14167. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14168. /**
  14169. * 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:
  14170. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14171. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14172. * 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.
  14173. */
  14174. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14175. /**
  14176. * 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.
  14177. * The default value is -1 which means don't break the query and wait till the result.
  14178. */
  14179. _this.occlusionRetryCount = -1;
  14180. _this._occlusionInternalRetryCounter = 0;
  14181. _this._isOccluded = false;
  14182. _this._isOcclusionQueryInProgress = false;
  14183. _this.visibility = 1.0;
  14184. _this.alphaIndex = Number.MAX_VALUE;
  14185. _this.isVisible = true;
  14186. _this.isPickable = true;
  14187. _this.showBoundingBox = false;
  14188. _this.showSubMeshesBoundingBox = false;
  14189. _this.isBlocker = false;
  14190. _this.enablePointerMoveEvents = false;
  14191. _this.renderingGroupId = 0;
  14192. _this._receiveShadows = false;
  14193. _this.renderOutline = false;
  14194. _this.outlineColor = BABYLON.Color3.Red();
  14195. _this.outlineWidth = 0.02;
  14196. _this.renderOverlay = false;
  14197. _this.overlayColor = BABYLON.Color3.Red();
  14198. _this.overlayAlpha = 0.5;
  14199. _this._hasVertexAlpha = false;
  14200. _this._useVertexColors = true;
  14201. _this._computeBonesUsingShaders = true;
  14202. _this._numBoneInfluencers = 4;
  14203. _this._applyFog = true;
  14204. _this.useOctreeForRenderingSelection = true;
  14205. _this.useOctreeForPicking = true;
  14206. _this.useOctreeForCollisions = true;
  14207. _this._layerMask = 0x0FFFFFFF;
  14208. /**
  14209. * True if the mesh must be rendered in any case.
  14210. */
  14211. _this.alwaysSelectAsActiveMesh = false;
  14212. /**
  14213. * This scene's action manager
  14214. * @type {BABYLON.ActionManager}
  14215. */
  14216. _this.actionManager = null;
  14217. // Physics
  14218. _this.physicsImpostor = null;
  14219. // Collisions
  14220. _this._checkCollisions = false;
  14221. _this._collisionMask = -1;
  14222. _this._collisionGroup = -1;
  14223. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14224. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14225. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14226. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14227. // Edges
  14228. _this.edgesWidth = 1;
  14229. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14230. // Cache
  14231. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14232. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14233. _this._isDisposed = false;
  14234. _this._renderId = 0;
  14235. _this._intersectionsInProgress = new Array();
  14236. _this._unIndexed = false;
  14237. _this._lightSources = new Array();
  14238. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14239. if (collidedMesh === void 0) { collidedMesh = null; }
  14240. //TODO move this to the collision coordinator!
  14241. if (_this.getScene().workerCollisions)
  14242. newPosition.multiplyInPlace(_this._collider._radius);
  14243. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14244. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14245. _this.position.addInPlace(_this._diffPositionForCollisions);
  14246. }
  14247. if (collidedMesh) {
  14248. _this.onCollideObservable.notifyObservers(collidedMesh);
  14249. }
  14250. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14251. };
  14252. _this.getScene().addMesh(_this);
  14253. _this._resyncLightSources();
  14254. return _this;
  14255. }
  14256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14257. get: function () {
  14258. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14259. },
  14260. enumerable: true,
  14261. configurable: true
  14262. });
  14263. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14264. get: function () {
  14265. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14271. get: function () {
  14272. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14278. get: function () {
  14279. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14285. get: function () {
  14286. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14292. /**
  14293. * Read-only : the number of facets in the mesh
  14294. */
  14295. get: function () {
  14296. return this._facetNb;
  14297. },
  14298. enumerable: true,
  14299. configurable: true
  14300. });
  14301. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14302. /**
  14303. * The number (integer) of subdivisions per axis in the partioning space
  14304. */
  14305. get: function () {
  14306. return this._partitioningSubdivisions;
  14307. },
  14308. set: function (nb) {
  14309. this._partitioningSubdivisions = nb;
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14315. /**
  14316. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14317. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14318. */
  14319. get: function () {
  14320. return this._partitioningBBoxRatio;
  14321. },
  14322. set: function (ratio) {
  14323. this._partitioningBBoxRatio = ratio;
  14324. },
  14325. enumerable: true,
  14326. configurable: true
  14327. });
  14328. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14329. /**
  14330. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14331. * Works only for updatable meshes.
  14332. * Doesn't work with multi-materials.
  14333. */
  14334. get: function () {
  14335. return this._facetDepthSort;
  14336. },
  14337. set: function (sort) {
  14338. this._facetDepthSort = sort;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14344. /**
  14345. * The location (Vector3) where the facet depth sort must be computed from.
  14346. * By default, the active camera position.
  14347. * Used only when facet depth sort is enabled.
  14348. */
  14349. get: function () {
  14350. return this._facetDepthSortFrom;
  14351. },
  14352. set: function (location) {
  14353. this._facetDepthSortFrom = location;
  14354. },
  14355. enumerable: true,
  14356. configurable: true
  14357. });
  14358. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14359. /**
  14360. * Read-only boolean : is the feature facetData enabled ?
  14361. */
  14362. get: function () {
  14363. return this._facetDataEnabled;
  14364. },
  14365. enumerable: true,
  14366. configurable: true
  14367. });
  14368. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14369. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14370. return false;
  14371. }
  14372. this._markSubMeshesAsMiscDirty();
  14373. return true;
  14374. };
  14375. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14376. set: function (callback) {
  14377. if (this._onCollideObserver) {
  14378. this.onCollideObservable.remove(this._onCollideObserver);
  14379. }
  14380. this._onCollideObserver = this.onCollideObservable.add(callback);
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14386. set: function (callback) {
  14387. if (this._onCollisionPositionChangeObserver) {
  14388. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14389. }
  14390. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14396. /**
  14397. * 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.
  14398. */
  14399. get: function () {
  14400. return this._isOccluded;
  14401. },
  14402. set: function (value) {
  14403. this._isOccluded = value;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14409. /**
  14410. * Flag to check the progress status of the query
  14411. */
  14412. get: function () {
  14413. return this._isOcclusionQueryInProgress;
  14414. },
  14415. enumerable: true,
  14416. configurable: true
  14417. });
  14418. Object.defineProperty(AbstractMesh.prototype, "material", {
  14419. get: function () {
  14420. return this._material;
  14421. },
  14422. set: function (value) {
  14423. if (this._material === value) {
  14424. return;
  14425. }
  14426. this._material = value;
  14427. if (this.onMaterialChangedObservable.hasObservers) {
  14428. this.onMaterialChangedObservable.notifyObservers(this);
  14429. }
  14430. if (!this.subMeshes) {
  14431. return;
  14432. }
  14433. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14434. var subMesh = _a[_i];
  14435. subMesh.setEffect(null);
  14436. }
  14437. },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14442. get: function () {
  14443. return this._receiveShadows;
  14444. },
  14445. set: function (value) {
  14446. if (this._receiveShadows === value) {
  14447. return;
  14448. }
  14449. this._receiveShadows = value;
  14450. this._markSubMeshesAsLightDirty();
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14456. get: function () {
  14457. return this._hasVertexAlpha;
  14458. },
  14459. set: function (value) {
  14460. if (this._hasVertexAlpha === value) {
  14461. return;
  14462. }
  14463. this._hasVertexAlpha = value;
  14464. this._markSubMeshesAsAttributesDirty();
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14470. get: function () {
  14471. return this._useVertexColors;
  14472. },
  14473. set: function (value) {
  14474. if (this._useVertexColors === value) {
  14475. return;
  14476. }
  14477. this._useVertexColors = value;
  14478. this._markSubMeshesAsAttributesDirty();
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14484. get: function () {
  14485. return this._computeBonesUsingShaders;
  14486. },
  14487. set: function (value) {
  14488. if (this._computeBonesUsingShaders === value) {
  14489. return;
  14490. }
  14491. this._computeBonesUsingShaders = value;
  14492. this._markSubMeshesAsAttributesDirty();
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14498. get: function () {
  14499. return this._numBoneInfluencers;
  14500. },
  14501. set: function (value) {
  14502. if (this._numBoneInfluencers === value) {
  14503. return;
  14504. }
  14505. this._numBoneInfluencers = value;
  14506. this._markSubMeshesAsAttributesDirty();
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14512. get: function () {
  14513. return this._applyFog;
  14514. },
  14515. set: function (value) {
  14516. if (this._applyFog === value) {
  14517. return;
  14518. }
  14519. this._applyFog = value;
  14520. this._markSubMeshesAsMiscDirty();
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14526. get: function () {
  14527. return this._layerMask;
  14528. },
  14529. set: function (value) {
  14530. if (value === this._layerMask) {
  14531. return;
  14532. }
  14533. this._layerMask = value;
  14534. this._resyncLightSources();
  14535. },
  14536. enumerable: true,
  14537. configurable: true
  14538. });
  14539. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14540. get: function () {
  14541. return this._collisionMask;
  14542. },
  14543. set: function (mask) {
  14544. this._collisionMask = !isNaN(mask) ? mask : -1;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14550. get: function () {
  14551. return this._collisionGroup;
  14552. },
  14553. set: function (mask) {
  14554. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14555. },
  14556. enumerable: true,
  14557. configurable: true
  14558. });
  14559. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14560. get: function () {
  14561. return null;
  14562. },
  14563. enumerable: true,
  14564. configurable: true
  14565. });
  14566. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14567. get: function () {
  14568. return this._skeleton;
  14569. },
  14570. set: function (value) {
  14571. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14572. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14573. }
  14574. if (value && value.needInitialSkinMatrix) {
  14575. value._registerMeshWithPoseMatrix(this);
  14576. }
  14577. this._skeleton = value;
  14578. if (!this._skeleton) {
  14579. this._bonesTransformMatrices = null;
  14580. }
  14581. this._markSubMeshesAsAttributesDirty();
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. /**
  14587. * Boolean : true if the mesh has been disposed.
  14588. */
  14589. AbstractMesh.prototype.isDisposed = function () {
  14590. return this._isDisposed;
  14591. };
  14592. /**
  14593. * Returns the string "AbstractMesh"
  14594. */
  14595. AbstractMesh.prototype.getClassName = function () {
  14596. return "AbstractMesh";
  14597. };
  14598. /**
  14599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14600. */
  14601. AbstractMesh.prototype.toString = function (fullDetails) {
  14602. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14603. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14604. if (this._skeleton) {
  14605. ret += ", skeleton: " + this._skeleton.name;
  14606. }
  14607. if (fullDetails) {
  14608. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14609. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14610. }
  14611. return ret;
  14612. };
  14613. AbstractMesh.prototype._rebuild = function () {
  14614. if (this._occlusionQuery) {
  14615. this._occlusionQuery = null;
  14616. }
  14617. if (this._edgesRenderer) {
  14618. this._edgesRenderer._rebuild();
  14619. }
  14620. if (!this.subMeshes) {
  14621. return;
  14622. }
  14623. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14624. var subMesh = _a[_i];
  14625. subMesh._rebuild();
  14626. }
  14627. };
  14628. AbstractMesh.prototype._resyncLightSources = function () {
  14629. this._lightSources.length = 0;
  14630. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14631. var light = _a[_i];
  14632. if (!light.isEnabled()) {
  14633. continue;
  14634. }
  14635. if (light.canAffectMesh(this)) {
  14636. this._lightSources.push(light);
  14637. }
  14638. }
  14639. this._markSubMeshesAsLightDirty();
  14640. };
  14641. AbstractMesh.prototype._resyncLighSource = function (light) {
  14642. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14643. var index = this._lightSources.indexOf(light);
  14644. if (index === -1) {
  14645. if (!isIn) {
  14646. return;
  14647. }
  14648. this._lightSources.push(light);
  14649. }
  14650. else {
  14651. if (isIn) {
  14652. return;
  14653. }
  14654. this._lightSources.splice(index, 1);
  14655. }
  14656. this._markSubMeshesAsLightDirty();
  14657. };
  14658. AbstractMesh.prototype._removeLightSource = function (light) {
  14659. var index = this._lightSources.indexOf(light);
  14660. if (index === -1) {
  14661. return;
  14662. }
  14663. this._lightSources.splice(index, 1);
  14664. };
  14665. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14666. if (!this.subMeshes) {
  14667. return;
  14668. }
  14669. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14670. var subMesh = _a[_i];
  14671. if (subMesh._materialDefines) {
  14672. func(subMesh._materialDefines);
  14673. }
  14674. }
  14675. };
  14676. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14677. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14678. };
  14679. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14680. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14681. };
  14682. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14683. if (!this.subMeshes) {
  14684. return;
  14685. }
  14686. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14687. var subMesh = _a[_i];
  14688. var material = subMesh.getMaterial();
  14689. if (material) {
  14690. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14691. }
  14692. }
  14693. };
  14694. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14695. /**
  14696. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14697. * Default : (1.0, 1.0, 1.0)
  14698. */
  14699. get: function () {
  14700. return this._scaling;
  14701. },
  14702. /**
  14703. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14704. * Default : (1.0, 1.0, 1.0)
  14705. */
  14706. set: function (newScaling) {
  14707. this._scaling = newScaling;
  14708. if (this.physicsImpostor) {
  14709. this.physicsImpostor.forceUpdate();
  14710. }
  14711. },
  14712. enumerable: true,
  14713. configurable: true
  14714. });
  14715. // Methods
  14716. /**
  14717. * Disables the mesh edger rendering mode.
  14718. * Returns the AbstractMesh.
  14719. */
  14720. AbstractMesh.prototype.disableEdgesRendering = function () {
  14721. if (this._edgesRenderer) {
  14722. this._edgesRenderer.dispose();
  14723. this._edgesRenderer = null;
  14724. }
  14725. return this;
  14726. };
  14727. /**
  14728. * Enables the edge rendering mode on the mesh.
  14729. * This mode makes the mesh edges visible.
  14730. * Returns the AbstractMesh.
  14731. */
  14732. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14733. if (epsilon === void 0) { epsilon = 0.95; }
  14734. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14735. this.disableEdgesRendering();
  14736. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14737. return this;
  14738. };
  14739. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14740. /**
  14741. * Returns true if the mesh is blocked. Used by the class Mesh.
  14742. * Returns the boolean `false` by default.
  14743. */
  14744. get: function () {
  14745. return false;
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. /**
  14751. * Returns the mesh itself by default, used by the class Mesh.
  14752. * Returned type : AbstractMesh
  14753. */
  14754. AbstractMesh.prototype.getLOD = function (camera) {
  14755. return this;
  14756. };
  14757. /**
  14758. * Returns 0 by default, used by the class Mesh.
  14759. * Returns an integer.
  14760. */
  14761. AbstractMesh.prototype.getTotalVertices = function () {
  14762. return 0;
  14763. };
  14764. /**
  14765. * Returns null by default, used by the class Mesh.
  14766. * Returned type : integer array
  14767. */
  14768. AbstractMesh.prototype.getIndices = function () {
  14769. return null;
  14770. };
  14771. /**
  14772. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14773. * Returned type : float array or Float32Array
  14774. */
  14775. AbstractMesh.prototype.getVerticesData = function (kind) {
  14776. return null;
  14777. };
  14778. /**
  14779. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14780. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14781. * The `data` are either a numeric array either a Float32Array.
  14782. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14783. * 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).
  14784. * Note that a new underlying VertexBuffer object is created each call.
  14785. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14786. *
  14787. * Possible `kind` values :
  14788. * - BABYLON.VertexBuffer.PositionKind
  14789. * - BABYLON.VertexBuffer.UVKind
  14790. * - BABYLON.VertexBuffer.UV2Kind
  14791. * - BABYLON.VertexBuffer.UV3Kind
  14792. * - BABYLON.VertexBuffer.UV4Kind
  14793. * - BABYLON.VertexBuffer.UV5Kind
  14794. * - BABYLON.VertexBuffer.UV6Kind
  14795. * - BABYLON.VertexBuffer.ColorKind
  14796. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14797. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14798. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14799. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14800. *
  14801. * Returns the Mesh.
  14802. */
  14803. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14804. return this;
  14805. };
  14806. /**
  14807. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14808. * If the mesh has no geometry, it is simply returned as it is.
  14809. * The `data` are either a numeric array either a Float32Array.
  14810. * No new underlying VertexBuffer object is created.
  14811. * 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.
  14812. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14813. *
  14814. * Possible `kind` values :
  14815. * - BABYLON.VertexBuffer.PositionKind
  14816. * - BABYLON.VertexBuffer.UVKind
  14817. * - BABYLON.VertexBuffer.UV2Kind
  14818. * - BABYLON.VertexBuffer.UV3Kind
  14819. * - BABYLON.VertexBuffer.UV4Kind
  14820. * - BABYLON.VertexBuffer.UV5Kind
  14821. * - BABYLON.VertexBuffer.UV6Kind
  14822. * - BABYLON.VertexBuffer.ColorKind
  14823. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14824. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14825. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14826. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14827. *
  14828. * Returns the Mesh.
  14829. */
  14830. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14831. return this;
  14832. };
  14833. /**
  14834. * Sets the mesh indices.
  14835. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14836. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14837. * This method creates a new index buffer each call.
  14838. * Returns the Mesh.
  14839. */
  14840. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14841. return this;
  14842. };
  14843. /** Returns false by default, used by the class Mesh.
  14844. * Returns a boolean
  14845. */
  14846. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14847. return false;
  14848. };
  14849. /**
  14850. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14851. * Returns a BoundingInfo
  14852. */
  14853. AbstractMesh.prototype.getBoundingInfo = function () {
  14854. if (this._masterMesh) {
  14855. return this._masterMesh.getBoundingInfo();
  14856. }
  14857. if (!this._boundingInfo) {
  14858. // this._boundingInfo is being created here
  14859. this._updateBoundingInfo();
  14860. }
  14861. // cannot be null.
  14862. return this._boundingInfo;
  14863. };
  14864. /**
  14865. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14866. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14867. */
  14868. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14869. if (includeDescendants === void 0) { includeDescendants = true; }
  14870. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14871. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14872. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14873. if (maxDimension === 0) {
  14874. return this;
  14875. }
  14876. var scale = 1 / maxDimension;
  14877. this.scaling.scaleInPlace(scale);
  14878. return this;
  14879. };
  14880. /**
  14881. * Sets a mesh new object BoundingInfo.
  14882. * Returns the AbstractMesh.
  14883. */
  14884. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14885. this._boundingInfo = boundingInfo;
  14886. return this;
  14887. };
  14888. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14889. get: function () {
  14890. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14891. },
  14892. enumerable: true,
  14893. configurable: true
  14894. });
  14895. AbstractMesh.prototype._preActivate = function () {
  14896. };
  14897. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14898. };
  14899. AbstractMesh.prototype._activate = function (renderId) {
  14900. this._renderId = renderId;
  14901. };
  14902. /**
  14903. * Returns the latest update of the World matrix
  14904. * Returns a Matrix.
  14905. */
  14906. AbstractMesh.prototype.getWorldMatrix = function () {
  14907. if (this._masterMesh) {
  14908. return this._masterMesh.getWorldMatrix();
  14909. }
  14910. return _super.prototype.getWorldMatrix.call(this);
  14911. };
  14912. // ================================== Point of View Movement =================================
  14913. /**
  14914. * Perform relative position change from the point of view of behind the front of the mesh.
  14915. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14916. * Supports definition of mesh facing forward or backward.
  14917. * @param {number} amountRight
  14918. * @param {number} amountUp
  14919. * @param {number} amountForward
  14920. *
  14921. * Returns the AbstractMesh.
  14922. */
  14923. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14924. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14925. return this;
  14926. };
  14927. /**
  14928. * Calculate relative position change from the point of view of behind the front of the mesh.
  14929. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14930. * Supports definition of mesh facing forward or backward.
  14931. * @param {number} amountRight
  14932. * @param {number} amountUp
  14933. * @param {number} amountForward
  14934. *
  14935. * Returns a new Vector3.
  14936. */
  14937. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14938. var rotMatrix = new BABYLON.Matrix();
  14939. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14940. rotQuaternion.toRotationMatrix(rotMatrix);
  14941. var translationDelta = BABYLON.Vector3.Zero();
  14942. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14943. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14944. return translationDelta;
  14945. };
  14946. // ================================== Point of View Rotation =================================
  14947. /**
  14948. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14949. * Supports definition of mesh facing forward or backward.
  14950. * @param {number} flipBack
  14951. * @param {number} twirlClockwise
  14952. * @param {number} tiltRight
  14953. *
  14954. * Returns the AbstractMesh.
  14955. */
  14956. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14957. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14958. return this;
  14959. };
  14960. /**
  14961. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14962. * Supports definition of mesh facing forward or backward.
  14963. * @param {number} flipBack
  14964. * @param {number} twirlClockwise
  14965. * @param {number} tiltRight
  14966. *
  14967. * Returns a new Vector3.
  14968. */
  14969. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14970. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14971. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14972. };
  14973. /**
  14974. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14975. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14976. */
  14977. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14978. if (includeDescendants === void 0) { includeDescendants = true; }
  14979. this.computeWorldMatrix(true);
  14980. var min;
  14981. var max;
  14982. var boundingInfo = this.getBoundingInfo();
  14983. if (!this.subMeshes) {
  14984. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14985. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14986. }
  14987. else {
  14988. min = boundingInfo.boundingBox.minimumWorld;
  14989. max = boundingInfo.boundingBox.maximumWorld;
  14990. }
  14991. if (includeDescendants) {
  14992. var descendants = this.getDescendants(false);
  14993. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14994. var descendant = descendants_1[_i];
  14995. var childMesh = descendant;
  14996. childMesh.computeWorldMatrix(true);
  14997. var childBoundingInfo = childMesh.getBoundingInfo();
  14998. if (childMesh.getTotalVertices() === 0) {
  14999. continue;
  15000. }
  15001. var boundingBox = childBoundingInfo.boundingBox;
  15002. var minBox = boundingBox.minimumWorld;
  15003. var maxBox = boundingBox.maximumWorld;
  15004. BABYLON.Tools.CheckExtends(minBox, min, max);
  15005. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15006. }
  15007. }
  15008. return {
  15009. min: min,
  15010. max: max
  15011. };
  15012. };
  15013. /**
  15014. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  15015. * Returns the AbstractMesh.
  15016. */
  15017. AbstractMesh.prototype._updateBoundingInfo = function () {
  15018. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  15019. this._boundingInfo.update(this.worldMatrixFromCache);
  15020. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15021. return this;
  15022. };
  15023. /**
  15024. * Update a mesh's children BoundingInfo objects only.
  15025. * Returns the AbstractMesh.
  15026. */
  15027. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  15028. if (!this.subMeshes) {
  15029. return this;
  15030. }
  15031. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  15032. var subMesh = this.subMeshes[subIndex];
  15033. if (!subMesh.IsGlobal) {
  15034. subMesh.updateBoundingInfo(matrix);
  15035. }
  15036. }
  15037. return this;
  15038. };
  15039. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  15040. // Bounding info
  15041. this._updateBoundingInfo();
  15042. };
  15043. /**
  15044. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  15045. * A mesh is in the frustum if its bounding box intersects the frustum.
  15046. * Boolean returned.
  15047. */
  15048. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  15049. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  15050. };
  15051. /**
  15052. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  15053. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  15054. * Boolean returned.
  15055. */
  15056. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15057. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  15058. ;
  15059. };
  15060. /**
  15061. * True if the mesh intersects another mesh or a SolidParticle object.
  15062. * 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)
  15063. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  15064. * Returns a boolean.
  15065. */
  15066. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  15067. if (precise === void 0) { precise = false; }
  15068. if (!this._boundingInfo || !mesh._boundingInfo) {
  15069. return false;
  15070. }
  15071. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  15072. return true;
  15073. }
  15074. if (includeDescendants) {
  15075. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  15076. var child = _a[_i];
  15077. if (child.intersectsMesh(mesh, precise, true)) {
  15078. return true;
  15079. }
  15080. }
  15081. }
  15082. return false;
  15083. };
  15084. /**
  15085. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  15086. * Returns a boolean.
  15087. */
  15088. AbstractMesh.prototype.intersectsPoint = function (point) {
  15089. if (!this._boundingInfo) {
  15090. return false;
  15091. }
  15092. return this._boundingInfo.intersectsPoint(point);
  15093. };
  15094. AbstractMesh.prototype.getPhysicsImpostor = function () {
  15095. return this.physicsImpostor;
  15096. };
  15097. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  15098. if (camera === void 0) { camera = null; }
  15099. if (!camera) {
  15100. camera = this.getScene().activeCamera;
  15101. }
  15102. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  15103. };
  15104. /**
  15105. * Returns the distance from the mesh to the active camera.
  15106. * Returns a float.
  15107. */
  15108. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  15109. if (camera === void 0) { camera = null; }
  15110. if (!camera) {
  15111. camera = this.getScene().activeCamera;
  15112. }
  15113. return this.absolutePosition.subtract(camera.position).length();
  15114. };
  15115. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  15116. if (!this.physicsImpostor) {
  15117. return this;
  15118. }
  15119. this.physicsImpostor.applyImpulse(force, contactPoint);
  15120. return this;
  15121. };
  15122. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  15123. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  15124. return this;
  15125. }
  15126. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  15127. mainPivot: pivot1,
  15128. connectedPivot: pivot2,
  15129. nativeParams: options
  15130. });
  15131. return this;
  15132. };
  15133. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  15134. // Collisions
  15135. /**
  15136. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  15137. * Default `false`.
  15138. */
  15139. get: function () {
  15140. return this._checkCollisions;
  15141. },
  15142. set: function (collisionEnabled) {
  15143. this._checkCollisions = collisionEnabled;
  15144. if (this.getScene().workerCollisions) {
  15145. this.getScene().collisionCoordinator.onMeshUpdated(this);
  15146. }
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(AbstractMesh.prototype, "collider", {
  15152. /**
  15153. * Gets Collider object used to compute collisions (not physics)
  15154. */
  15155. get: function () {
  15156. return this._collider;
  15157. },
  15158. enumerable: true,
  15159. configurable: true
  15160. });
  15161. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15162. var globalPosition = this.getAbsolutePosition();
  15163. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  15164. if (!this._collider) {
  15165. this._collider = new BABYLON.Collider();
  15166. }
  15167. this._collider._radius = this.ellipsoid;
  15168. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15169. return this;
  15170. };
  15171. // Submeshes octree
  15172. /**
  15173. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15174. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15175. * Returns an Octree of submeshes.
  15176. */
  15177. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15178. if (maxCapacity === void 0) { maxCapacity = 64; }
  15179. if (maxDepth === void 0) { maxDepth = 2; }
  15180. if (!this._submeshesOctree) {
  15181. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15182. }
  15183. this.computeWorldMatrix(true);
  15184. var boundingInfo = this.getBoundingInfo();
  15185. // Update octree
  15186. var bbox = boundingInfo.boundingBox;
  15187. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15188. return this._submeshesOctree;
  15189. };
  15190. // Collisions
  15191. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15192. this._generatePointsArray();
  15193. if (!this._positions) {
  15194. return this;
  15195. }
  15196. // Transformation
  15197. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15198. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15199. subMesh._lastColliderWorldVertices = [];
  15200. subMesh._trianglePlanes = [];
  15201. var start = subMesh.verticesStart;
  15202. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15203. for (var i = start; i < end; i++) {
  15204. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15205. }
  15206. }
  15207. // Collide
  15208. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15209. if (collider.collisionFound) {
  15210. collider.collidedMesh = this;
  15211. }
  15212. return this;
  15213. };
  15214. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15215. var subMeshes;
  15216. var len;
  15217. // Octrees
  15218. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15219. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  15220. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  15221. len = intersections.length;
  15222. subMeshes = intersections.data;
  15223. }
  15224. else {
  15225. subMeshes = this.subMeshes;
  15226. len = subMeshes.length;
  15227. }
  15228. for (var index = 0; index < len; index++) {
  15229. var subMesh = subMeshes[index];
  15230. // Bounding test
  15231. if (len > 1 && !subMesh._checkCollision(collider))
  15232. continue;
  15233. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15234. }
  15235. return this;
  15236. };
  15237. AbstractMesh.prototype._checkCollision = function (collider) {
  15238. // Bounding box test
  15239. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15240. return this;
  15241. // Transformation matrix
  15242. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  15243. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15244. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15245. return this;
  15246. };
  15247. // Picking
  15248. AbstractMesh.prototype._generatePointsArray = function () {
  15249. return false;
  15250. };
  15251. /**
  15252. * Checks if the passed Ray intersects with the mesh.
  15253. * Returns an object PickingInfo.
  15254. */
  15255. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15256. var pickingInfo = new BABYLON.PickingInfo();
  15257. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15258. return pickingInfo;
  15259. }
  15260. if (!this._generatePointsArray()) {
  15261. return pickingInfo;
  15262. }
  15263. var intersectInfo = null;
  15264. // Octrees
  15265. var subMeshes;
  15266. var len;
  15267. if (this._submeshesOctree && this.useOctreeForPicking) {
  15268. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15269. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15270. len = intersections.length;
  15271. subMeshes = intersections.data;
  15272. }
  15273. else {
  15274. subMeshes = this.subMeshes;
  15275. len = subMeshes.length;
  15276. }
  15277. for (var index = 0; index < len; index++) {
  15278. var subMesh = subMeshes[index];
  15279. // Bounding test
  15280. if (len > 1 && !subMesh.canIntersects(ray))
  15281. continue;
  15282. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15283. if (currentIntersectInfo) {
  15284. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15285. intersectInfo = currentIntersectInfo;
  15286. intersectInfo.subMeshId = index;
  15287. if (fastCheck) {
  15288. break;
  15289. }
  15290. }
  15291. }
  15292. }
  15293. if (intersectInfo) {
  15294. // Get picked point
  15295. var world = this.getWorldMatrix();
  15296. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15297. var direction = ray.direction.clone();
  15298. direction = direction.scale(intersectInfo.distance);
  15299. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15300. var pickedPoint = worldOrigin.add(worldDirection);
  15301. // Return result
  15302. pickingInfo.hit = true;
  15303. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15304. pickingInfo.pickedPoint = pickedPoint;
  15305. pickingInfo.pickedMesh = this;
  15306. pickingInfo.bu = intersectInfo.bu || 0;
  15307. pickingInfo.bv = intersectInfo.bv || 0;
  15308. pickingInfo.faceId = intersectInfo.faceId;
  15309. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15310. return pickingInfo;
  15311. }
  15312. return pickingInfo;
  15313. };
  15314. /**
  15315. * Clones the mesh, used by the class Mesh.
  15316. * Just returns `null` for an AbstractMesh.
  15317. */
  15318. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15319. return null;
  15320. };
  15321. /**
  15322. * Disposes all the mesh submeshes.
  15323. * Returns the AbstractMesh.
  15324. */
  15325. AbstractMesh.prototype.releaseSubMeshes = function () {
  15326. if (this.subMeshes) {
  15327. while (this.subMeshes.length) {
  15328. this.subMeshes[0].dispose();
  15329. }
  15330. }
  15331. else {
  15332. this.subMeshes = new Array();
  15333. }
  15334. return this;
  15335. };
  15336. /**
  15337. * Disposes the AbstractMesh.
  15338. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15339. * Returns nothing.
  15340. */
  15341. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15342. var _this = this;
  15343. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15344. var index;
  15345. // Action manager
  15346. if (this.actionManager) {
  15347. this.actionManager.dispose();
  15348. this.actionManager = null;
  15349. }
  15350. // Skeleton
  15351. this.skeleton = null;
  15352. // Physics
  15353. if (this.physicsImpostor) {
  15354. this.physicsImpostor.dispose();
  15355. }
  15356. // Intersections in progress
  15357. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15358. var other = this._intersectionsInProgress[index];
  15359. var pos = other._intersectionsInProgress.indexOf(this);
  15360. other._intersectionsInProgress.splice(pos, 1);
  15361. }
  15362. this._intersectionsInProgress = [];
  15363. // Lights
  15364. var lights = this.getScene().lights;
  15365. lights.forEach(function (light) {
  15366. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15367. if (meshIndex !== -1) {
  15368. light.includedOnlyMeshes.splice(meshIndex, 1);
  15369. }
  15370. meshIndex = light.excludedMeshes.indexOf(_this);
  15371. if (meshIndex !== -1) {
  15372. light.excludedMeshes.splice(meshIndex, 1);
  15373. }
  15374. // Shadow generators
  15375. var generator = light.getShadowGenerator();
  15376. if (generator) {
  15377. var shadowMap = generator.getShadowMap();
  15378. if (shadowMap && shadowMap.renderList) {
  15379. meshIndex = shadowMap.renderList.indexOf(_this);
  15380. if (meshIndex !== -1) {
  15381. shadowMap.renderList.splice(meshIndex, 1);
  15382. }
  15383. }
  15384. }
  15385. });
  15386. // Edges
  15387. if (this._edgesRenderer) {
  15388. this._edgesRenderer.dispose();
  15389. this._edgesRenderer = null;
  15390. }
  15391. // SubMeshes
  15392. if (this.getClassName() !== "InstancedMesh") {
  15393. this.releaseSubMeshes();
  15394. }
  15395. // Octree
  15396. var sceneOctree = this.getScene().selectionOctree;
  15397. if (sceneOctree) {
  15398. var index = sceneOctree.dynamicContent.indexOf(this);
  15399. if (index !== -1) {
  15400. sceneOctree.dynamicContent.splice(index, 1);
  15401. }
  15402. }
  15403. // Query
  15404. var engine = this.getScene().getEngine();
  15405. if (this._occlusionQuery) {
  15406. this._isOcclusionQueryInProgress = false;
  15407. engine.deleteQuery(this._occlusionQuery);
  15408. this._occlusionQuery = null;
  15409. }
  15410. // Engine
  15411. engine.wipeCaches();
  15412. // Remove from scene
  15413. this.getScene().removeMesh(this);
  15414. if (disposeMaterialAndTextures) {
  15415. if (this.material) {
  15416. this.material.dispose(false, true);
  15417. }
  15418. }
  15419. if (!doNotRecurse) {
  15420. // Particles
  15421. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15422. if (this.getScene().particleSystems[index].emitter === this) {
  15423. this.getScene().particleSystems[index].dispose();
  15424. index--;
  15425. }
  15426. }
  15427. }
  15428. // facet data
  15429. if (this._facetDataEnabled) {
  15430. this.disableFacetData();
  15431. }
  15432. this.onAfterWorldMatrixUpdateObservable.clear();
  15433. this.onCollideObservable.clear();
  15434. this.onCollisionPositionChangeObservable.clear();
  15435. this._isDisposed = true;
  15436. _super.prototype.dispose.call(this, doNotRecurse);
  15437. };
  15438. /**
  15439. * Adds the passed mesh as a child to the current mesh.
  15440. * Returns the AbstractMesh.
  15441. */
  15442. AbstractMesh.prototype.addChild = function (mesh) {
  15443. mesh.setParent(this);
  15444. return this;
  15445. };
  15446. /**
  15447. * Removes the passed mesh from the current mesh children list.
  15448. * Returns the AbstractMesh.
  15449. */
  15450. AbstractMesh.prototype.removeChild = function (mesh) {
  15451. mesh.setParent(null);
  15452. return this;
  15453. };
  15454. // Facet data
  15455. /**
  15456. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15457. * Returns the AbstractMesh.
  15458. */
  15459. AbstractMesh.prototype._initFacetData = function () {
  15460. if (!this._facetNormals) {
  15461. this._facetNormals = new Array();
  15462. }
  15463. if (!this._facetPositions) {
  15464. this._facetPositions = new Array();
  15465. }
  15466. if (!this._facetPartitioning) {
  15467. this._facetPartitioning = new Array();
  15468. }
  15469. this._facetNb = (this.getIndices().length / 3) | 0;
  15470. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15471. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15472. for (var f = 0; f < this._facetNb; f++) {
  15473. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15474. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15475. }
  15476. this._facetDataEnabled = true;
  15477. return this;
  15478. };
  15479. /**
  15480. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15481. * This method can be called within the render loop.
  15482. * 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.
  15483. * Returns the AbstractMesh.
  15484. */
  15485. AbstractMesh.prototype.updateFacetData = function () {
  15486. if (!this._facetDataEnabled) {
  15487. this._initFacetData();
  15488. }
  15489. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15490. var indices = this.getIndices();
  15491. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15492. var bInfo = this.getBoundingInfo();
  15493. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15494. // init arrays, matrix and sort function on first call
  15495. this._facetDepthSortEnabled = true;
  15496. if (indices instanceof Uint16Array) {
  15497. this._depthSortedIndices = new Uint16Array(indices);
  15498. }
  15499. else if (indices instanceof Uint32Array) {
  15500. this._depthSortedIndices = new Uint32Array(indices);
  15501. }
  15502. else {
  15503. var needs32bits = false;
  15504. for (var i = 0; i < indices.length; i++) {
  15505. if (indices[i] > 65535) {
  15506. needs32bits = true;
  15507. break;
  15508. }
  15509. }
  15510. if (needs32bits) {
  15511. this._depthSortedIndices = new Uint32Array(indices);
  15512. }
  15513. else {
  15514. this._depthSortedIndices = new Uint16Array(indices);
  15515. }
  15516. }
  15517. this._facetDepthSortFunction = function (f1, f2) {
  15518. return (f2.sqDistance - f1.sqDistance);
  15519. };
  15520. if (!this._facetDepthSortFrom) {
  15521. var camera = this.getScene().activeCamera;
  15522. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15523. }
  15524. this._depthSortedFacets = [];
  15525. for (var f = 0; f < this._facetNb; f++) {
  15526. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15527. this._depthSortedFacets.push(depthSortedFacet);
  15528. }
  15529. this._invertedMatrix = BABYLON.Matrix.Identity();
  15530. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15531. }
  15532. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15533. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15534. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15535. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15536. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15537. this._subDiv.max = this._partitioningSubdivisions;
  15538. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15539. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15540. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15541. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15542. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15543. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15544. // set the parameters for ComputeNormals()
  15545. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15546. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15547. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15548. this._facetParameters.bInfo = bInfo;
  15549. this._facetParameters.bbSize = this._bbSize;
  15550. this._facetParameters.subDiv = this._subDiv;
  15551. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15552. this._facetParameters.depthSort = this._facetDepthSort;
  15553. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15554. this.computeWorldMatrix(true);
  15555. this._worldMatrix.invertToRef(this._invertedMatrix);
  15556. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15557. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15558. }
  15559. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15560. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15561. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15562. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15563. var l = (this._depthSortedIndices.length / 3) | 0;
  15564. for (var f = 0; f < l; f++) {
  15565. var sind = this._depthSortedFacets[f].ind;
  15566. this._depthSortedIndices[f * 3] = indices[sind];
  15567. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15568. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15569. }
  15570. this.updateIndices(this._depthSortedIndices);
  15571. }
  15572. return this;
  15573. };
  15574. /**
  15575. * Returns the facetLocalNormals array.
  15576. * The normals are expressed in the mesh local space.
  15577. */
  15578. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15579. if (!this._facetNormals) {
  15580. this.updateFacetData();
  15581. }
  15582. return this._facetNormals;
  15583. };
  15584. /**
  15585. * Returns the facetLocalPositions array.
  15586. * The facet positions are expressed in the mesh local space.
  15587. */
  15588. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15589. if (!this._facetPositions) {
  15590. this.updateFacetData();
  15591. }
  15592. return this._facetPositions;
  15593. };
  15594. /**
  15595. * Returns the facetLocalPartioning array.
  15596. */
  15597. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15598. if (!this._facetPartitioning) {
  15599. this.updateFacetData();
  15600. }
  15601. return this._facetPartitioning;
  15602. };
  15603. /**
  15604. * Returns the i-th facet position in the world system.
  15605. * This method allocates a new Vector3 per call.
  15606. */
  15607. AbstractMesh.prototype.getFacetPosition = function (i) {
  15608. var pos = BABYLON.Vector3.Zero();
  15609. this.getFacetPositionToRef(i, pos);
  15610. return pos;
  15611. };
  15612. /**
  15613. * Sets the reference Vector3 with the i-th facet position in the world system.
  15614. * Returns the AbstractMesh.
  15615. */
  15616. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15617. var localPos = (this.getFacetLocalPositions())[i];
  15618. var world = this.getWorldMatrix();
  15619. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15620. return this;
  15621. };
  15622. /**
  15623. * Returns the i-th facet normal in the world system.
  15624. * This method allocates a new Vector3 per call.
  15625. */
  15626. AbstractMesh.prototype.getFacetNormal = function (i) {
  15627. var norm = BABYLON.Vector3.Zero();
  15628. this.getFacetNormalToRef(i, norm);
  15629. return norm;
  15630. };
  15631. /**
  15632. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15633. * Returns the AbstractMesh.
  15634. */
  15635. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15636. var localNorm = (this.getFacetLocalNormals())[i];
  15637. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15638. return this;
  15639. };
  15640. /**
  15641. * 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).
  15642. */
  15643. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15644. var bInfo = this.getBoundingInfo();
  15645. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15646. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15647. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15648. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15649. return null;
  15650. }
  15651. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15652. };
  15653. /**
  15654. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15655. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15656. * 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.
  15657. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15658. * 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.
  15659. */
  15660. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15661. if (checkFace === void 0) { checkFace = false; }
  15662. if (facing === void 0) { facing = true; }
  15663. var world = this.getWorldMatrix();
  15664. var invMat = BABYLON.Tmp.Matrix[5];
  15665. world.invertToRef(invMat);
  15666. var invVect = BABYLON.Tmp.Vector3[8];
  15667. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15668. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15669. if (projected) {
  15670. // tranform the local computed projected vector to world coordinates
  15671. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15672. }
  15673. return closest;
  15674. };
  15675. /**
  15676. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15677. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15678. * 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.
  15679. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15680. * 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.
  15681. */
  15682. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15683. if (checkFace === void 0) { checkFace = false; }
  15684. if (facing === void 0) { facing = true; }
  15685. var closest = null;
  15686. var tmpx = 0.0;
  15687. var tmpy = 0.0;
  15688. var tmpz = 0.0;
  15689. var d = 0.0; // tmp dot facet normal * facet position
  15690. var t0 = 0.0;
  15691. var projx = 0.0;
  15692. var projy = 0.0;
  15693. var projz = 0.0;
  15694. // Get all the facets in the same partitioning block than (x, y, z)
  15695. var facetPositions = this.getFacetLocalPositions();
  15696. var facetNormals = this.getFacetLocalNormals();
  15697. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15698. if (!facetsInBlock) {
  15699. return null;
  15700. }
  15701. // Get the closest facet to (x, y, z)
  15702. var shortest = Number.MAX_VALUE; // init distance vars
  15703. var tmpDistance = shortest;
  15704. var fib; // current facet in the block
  15705. var norm; // current facet normal
  15706. var p0; // current facet barycenter position
  15707. // loop on all the facets in the current partitioning block
  15708. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15709. fib = facetsInBlock[idx];
  15710. norm = facetNormals[fib];
  15711. p0 = facetPositions[fib];
  15712. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15713. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15714. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15715. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15716. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15717. projx = x + norm.x * t0;
  15718. projy = y + norm.y * t0;
  15719. projz = z + norm.z * t0;
  15720. tmpx = projx - x;
  15721. tmpy = projy - y;
  15722. tmpz = projz - z;
  15723. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15724. if (tmpDistance < shortest) {
  15725. shortest = tmpDistance;
  15726. closest = fib;
  15727. if (projected) {
  15728. projected.x = projx;
  15729. projected.y = projy;
  15730. projected.z = projz;
  15731. }
  15732. }
  15733. }
  15734. }
  15735. return closest;
  15736. };
  15737. /**
  15738. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15739. */
  15740. AbstractMesh.prototype.getFacetDataParameters = function () {
  15741. return this._facetParameters;
  15742. };
  15743. /**
  15744. * Disables the feature FacetData and frees the related memory.
  15745. * Returns the AbstractMesh.
  15746. */
  15747. AbstractMesh.prototype.disableFacetData = function () {
  15748. if (this._facetDataEnabled) {
  15749. this._facetDataEnabled = false;
  15750. this._facetPositions = new Array();
  15751. this._facetNormals = new Array();
  15752. this._facetPartitioning = new Array();
  15753. this._facetParameters = null;
  15754. this._depthSortedIndices = new Uint32Array(0);
  15755. }
  15756. return this;
  15757. };
  15758. /**
  15759. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15760. * Returns the mesh.
  15761. */
  15762. AbstractMesh.prototype.updateIndices = function (indices) {
  15763. return this;
  15764. };
  15765. /**
  15766. * The mesh Geometry. Actually used by the Mesh object.
  15767. * Returns a blank geometry object.
  15768. */
  15769. /**
  15770. * Creates new normals data for the mesh.
  15771. * @param updatable.
  15772. */
  15773. AbstractMesh.prototype.createNormals = function (updatable) {
  15774. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15775. var indices = this.getIndices();
  15776. var normals;
  15777. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15778. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15779. }
  15780. else {
  15781. normals = [];
  15782. }
  15783. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15784. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15785. };
  15786. /**
  15787. * Align the mesh with a normal.
  15788. * Returns the mesh.
  15789. */
  15790. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  15791. if (!upDirection) {
  15792. upDirection = BABYLON.Axis.Y;
  15793. }
  15794. var axisX = BABYLON.Tmp.Vector3[0];
  15795. var axisZ = BABYLON.Tmp.Vector3[1];
  15796. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  15797. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  15798. if (this.rotationQuaternion) {
  15799. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  15800. }
  15801. else {
  15802. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  15803. }
  15804. return this;
  15805. };
  15806. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15807. var engine = this.getEngine();
  15808. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15809. this._isOccluded = false;
  15810. return;
  15811. }
  15812. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15813. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15814. if (isOcclusionQueryAvailable) {
  15815. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15816. this._isOcclusionQueryInProgress = false;
  15817. this._occlusionInternalRetryCounter = 0;
  15818. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15819. }
  15820. else {
  15821. this._occlusionInternalRetryCounter++;
  15822. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15823. this._isOcclusionQueryInProgress = false;
  15824. this._occlusionInternalRetryCounter = 0;
  15825. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15826. // if strict continue the last state of the object.
  15827. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15828. }
  15829. else {
  15830. return;
  15831. }
  15832. }
  15833. }
  15834. var scene = this.getScene();
  15835. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15836. if (!this._occlusionQuery) {
  15837. this._occlusionQuery = engine.createQuery();
  15838. }
  15839. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15840. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15841. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15842. this._isOcclusionQueryInProgress = true;
  15843. };
  15844. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15845. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15846. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15847. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15848. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15849. return AbstractMesh;
  15850. }(BABYLON.TransformNode));
  15851. BABYLON.AbstractMesh = AbstractMesh;
  15852. })(BABYLON || (BABYLON = {}));
  15853. //# sourceMappingURL=babylon.abstractMesh.js.map
  15854. var BABYLON;
  15855. (function (BABYLON) {
  15856. var Light = /** @class */ (function (_super) {
  15857. __extends(Light, _super);
  15858. /**
  15859. * Creates a Light object in the scene.
  15860. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15861. */
  15862. function Light(name, scene) {
  15863. var _this = _super.call(this, name, scene) || this;
  15864. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15865. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15866. _this.intensity = 1.0;
  15867. _this.range = Number.MAX_VALUE;
  15868. /**
  15869. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15870. * of light.
  15871. */
  15872. _this._photometricScale = 1.0;
  15873. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15874. _this._radius = 0.00001;
  15875. _this.renderPriority = 0;
  15876. /**
  15877. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15878. * the current shadow generator.
  15879. */
  15880. _this.shadowEnabled = true;
  15881. _this._excludeWithLayerMask = 0;
  15882. _this._includeOnlyWithLayerMask = 0;
  15883. _this._lightmapMode = 0;
  15884. _this._excludedMeshesIds = new Array();
  15885. _this._includedOnlyMeshesIds = new Array();
  15886. _this.getScene().addLight(_this);
  15887. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15888. _this._buildUniformLayout();
  15889. _this.includedOnlyMeshes = new Array();
  15890. _this.excludedMeshes = new Array();
  15891. _this._resyncMeshes();
  15892. return _this;
  15893. }
  15894. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15895. /**
  15896. * If every light affecting the material is in this lightmapMode,
  15897. * material.lightmapTexture adds or multiplies
  15898. * (depends on material.useLightmapAsShadowmap)
  15899. * after every other light calculations.
  15900. */
  15901. get: function () {
  15902. return Light._LIGHTMAP_DEFAULT;
  15903. },
  15904. enumerable: true,
  15905. configurable: true
  15906. });
  15907. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15908. /**
  15909. * material.lightmapTexture as only diffuse lighting from this light
  15910. * adds pnly specular lighting from this light
  15911. * adds dynamic shadows
  15912. */
  15913. get: function () {
  15914. return Light._LIGHTMAP_SPECULAR;
  15915. },
  15916. enumerable: true,
  15917. configurable: true
  15918. });
  15919. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15920. /**
  15921. * material.lightmapTexture as only lighting
  15922. * no light calculation from this light
  15923. * only adds dynamic shadows from this light
  15924. */
  15925. get: function () {
  15926. return Light._LIGHTMAP_SHADOWSONLY;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15932. /**
  15933. * Each light type uses the default quantity according to its type:
  15934. * point/spot lights use luminous intensity
  15935. * directional lights use illuminance
  15936. */
  15937. get: function () {
  15938. return Light._INTENSITYMODE_AUTOMATIC;
  15939. },
  15940. enumerable: true,
  15941. configurable: true
  15942. });
  15943. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15944. /**
  15945. * lumen (lm)
  15946. */
  15947. get: function () {
  15948. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15949. },
  15950. enumerable: true,
  15951. configurable: true
  15952. });
  15953. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15954. /**
  15955. * candela (lm/sr)
  15956. */
  15957. get: function () {
  15958. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15964. /**
  15965. * lux (lm/m^2)
  15966. */
  15967. get: function () {
  15968. return Light._INTENSITYMODE_ILLUMINANCE;
  15969. },
  15970. enumerable: true,
  15971. configurable: true
  15972. });
  15973. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15974. /**
  15975. * nit (cd/m^2)
  15976. */
  15977. get: function () {
  15978. return Light._INTENSITYMODE_LUMINANCE;
  15979. },
  15980. enumerable: true,
  15981. configurable: true
  15982. });
  15983. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15984. /**
  15985. * Light type const id of the point light.
  15986. */
  15987. get: function () {
  15988. return Light._LIGHTTYPEID_POINTLIGHT;
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15994. /**
  15995. * Light type const id of the directional light.
  15996. */
  15997. get: function () {
  15998. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15999. },
  16000. enumerable: true,
  16001. configurable: true
  16002. });
  16003. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  16004. /**
  16005. * Light type const id of the spot light.
  16006. */
  16007. get: function () {
  16008. return Light._LIGHTTYPEID_SPOTLIGHT;
  16009. },
  16010. enumerable: true,
  16011. configurable: true
  16012. });
  16013. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  16014. /**
  16015. * Light type const id of the hemispheric light.
  16016. */
  16017. get: function () {
  16018. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  16019. },
  16020. enumerable: true,
  16021. configurable: true
  16022. });
  16023. Object.defineProperty(Light.prototype, "intensityMode", {
  16024. /**
  16025. * Gets the photometric scale used to interpret the intensity.
  16026. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16027. */
  16028. get: function () {
  16029. return this._intensityMode;
  16030. },
  16031. /**
  16032. * Sets the photometric scale used to interpret the intensity.
  16033. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16034. */
  16035. set: function (value) {
  16036. this._intensityMode = value;
  16037. this._computePhotometricScale();
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. ;
  16043. ;
  16044. Object.defineProperty(Light.prototype, "radius", {
  16045. /**
  16046. * Gets the light radius used by PBR Materials to simulate soft area lights.
  16047. */
  16048. get: function () {
  16049. return this._radius;
  16050. },
  16051. /**
  16052. * sets the light radius used by PBR Materials to simulate soft area lights.
  16053. */
  16054. set: function (value) {
  16055. this._radius = value;
  16056. this._computePhotometricScale();
  16057. },
  16058. enumerable: true,
  16059. configurable: true
  16060. });
  16061. ;
  16062. ;
  16063. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  16064. get: function () {
  16065. return this._includedOnlyMeshes;
  16066. },
  16067. set: function (value) {
  16068. this._includedOnlyMeshes = value;
  16069. this._hookArrayForIncludedOnly(value);
  16070. },
  16071. enumerable: true,
  16072. configurable: true
  16073. });
  16074. Object.defineProperty(Light.prototype, "excludedMeshes", {
  16075. get: function () {
  16076. return this._excludedMeshes;
  16077. },
  16078. set: function (value) {
  16079. this._excludedMeshes = value;
  16080. this._hookArrayForExcluded(value);
  16081. },
  16082. enumerable: true,
  16083. configurable: true
  16084. });
  16085. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  16086. get: function () {
  16087. return this._excludeWithLayerMask;
  16088. },
  16089. set: function (value) {
  16090. this._excludeWithLayerMask = value;
  16091. this._resyncMeshes();
  16092. },
  16093. enumerable: true,
  16094. configurable: true
  16095. });
  16096. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  16097. get: function () {
  16098. return this._includeOnlyWithLayerMask;
  16099. },
  16100. set: function (value) {
  16101. this._includeOnlyWithLayerMask = value;
  16102. this._resyncMeshes();
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(Light.prototype, "lightmapMode", {
  16108. get: function () {
  16109. return this._lightmapMode;
  16110. },
  16111. set: function (value) {
  16112. if (this._lightmapMode === value) {
  16113. return;
  16114. }
  16115. this._lightmapMode = value;
  16116. this._markMeshesAsLightDirty();
  16117. },
  16118. enumerable: true,
  16119. configurable: true
  16120. });
  16121. Light.prototype._buildUniformLayout = function () {
  16122. // Overridden
  16123. };
  16124. /**
  16125. * Returns the string "Light".
  16126. */
  16127. Light.prototype.getClassName = function () {
  16128. return "Light";
  16129. };
  16130. /**
  16131. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16132. */
  16133. Light.prototype.toString = function (fullDetails) {
  16134. var ret = "Name: " + this.name;
  16135. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  16136. if (this.animations) {
  16137. for (var i = 0; i < this.animations.length; i++) {
  16138. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16139. }
  16140. }
  16141. if (fullDetails) {
  16142. }
  16143. return ret;
  16144. };
  16145. /**
  16146. * Set the enabled state of this node.
  16147. * @param {boolean} value - the new enabled state
  16148. * @see isEnabled
  16149. */
  16150. Light.prototype.setEnabled = function (value) {
  16151. _super.prototype.setEnabled.call(this, value);
  16152. this._resyncMeshes();
  16153. };
  16154. /**
  16155. * Returns the Light associated shadow generator.
  16156. */
  16157. Light.prototype.getShadowGenerator = function () {
  16158. return this._shadowGenerator;
  16159. };
  16160. /**
  16161. * Returns a Vector3, the absolute light position in the World.
  16162. */
  16163. Light.prototype.getAbsolutePosition = function () {
  16164. return BABYLON.Vector3.Zero();
  16165. };
  16166. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16167. };
  16168. Light.prototype._getWorldMatrix = function () {
  16169. return BABYLON.Matrix.Identity();
  16170. };
  16171. /**
  16172. * Boolean : True if the light will affect the passed mesh.
  16173. */
  16174. Light.prototype.canAffectMesh = function (mesh) {
  16175. if (!mesh) {
  16176. return true;
  16177. }
  16178. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16179. return false;
  16180. }
  16181. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16182. return false;
  16183. }
  16184. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16185. return false;
  16186. }
  16187. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16188. return false;
  16189. }
  16190. return true;
  16191. };
  16192. /**
  16193. * Returns the light World matrix.
  16194. */
  16195. Light.prototype.getWorldMatrix = function () {
  16196. this._currentRenderId = this.getScene().getRenderId();
  16197. var worldMatrix = this._getWorldMatrix();
  16198. if (this.parent && this.parent.getWorldMatrix) {
  16199. if (!this._parentedWorldMatrix) {
  16200. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16201. }
  16202. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16203. this._markSyncedWithParent();
  16204. return this._parentedWorldMatrix;
  16205. }
  16206. return worldMatrix;
  16207. };
  16208. /**
  16209. * Sort function to order lights for rendering.
  16210. * @param a First Light object to compare to second.
  16211. * @param b Second Light object to compare first.
  16212. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16213. */
  16214. Light.compareLightsPriority = function (a, b) {
  16215. //shadow-casting lights have priority over non-shadow-casting lights
  16216. //the renderPrioirty is a secondary sort criterion
  16217. if (a.shadowEnabled !== b.shadowEnabled) {
  16218. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16219. }
  16220. return b.renderPriority - a.renderPriority;
  16221. };
  16222. /**
  16223. * Disposes the light.
  16224. */
  16225. Light.prototype.dispose = function () {
  16226. if (this._shadowGenerator) {
  16227. this._shadowGenerator.dispose();
  16228. this._shadowGenerator = null;
  16229. }
  16230. // Animations
  16231. this.getScene().stopAnimation(this);
  16232. // Remove from meshes
  16233. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16234. var mesh = _a[_i];
  16235. mesh._removeLightSource(this);
  16236. }
  16237. this._uniformBuffer.dispose();
  16238. // Remove from scene
  16239. this.getScene().removeLight(this);
  16240. _super.prototype.dispose.call(this);
  16241. };
  16242. /**
  16243. * Returns the light type ID (integer).
  16244. */
  16245. Light.prototype.getTypeID = function () {
  16246. return 0;
  16247. };
  16248. /**
  16249. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16250. */
  16251. Light.prototype.getScaledIntensity = function () {
  16252. return this._photometricScale * this.intensity;
  16253. };
  16254. /**
  16255. * Returns a new Light object, named "name", from the current one.
  16256. */
  16257. Light.prototype.clone = function (name) {
  16258. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16259. if (!constructor) {
  16260. return null;
  16261. }
  16262. return BABYLON.SerializationHelper.Clone(constructor, this);
  16263. };
  16264. /**
  16265. * Serializes the current light into a Serialization object.
  16266. * Returns the serialized object.
  16267. */
  16268. Light.prototype.serialize = function () {
  16269. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16270. // Type
  16271. serializationObject.type = this.getTypeID();
  16272. // Parent
  16273. if (this.parent) {
  16274. serializationObject.parentId = this.parent.id;
  16275. }
  16276. // Inclusion / exclusions
  16277. if (this.excludedMeshes.length > 0) {
  16278. serializationObject.excludedMeshesIds = [];
  16279. this.excludedMeshes.forEach(function (mesh) {
  16280. serializationObject.excludedMeshesIds.push(mesh.id);
  16281. });
  16282. }
  16283. if (this.includedOnlyMeshes.length > 0) {
  16284. serializationObject.includedOnlyMeshesIds = [];
  16285. this.includedOnlyMeshes.forEach(function (mesh) {
  16286. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16287. });
  16288. }
  16289. // Animations
  16290. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16291. serializationObject.ranges = this.serializeAnimationRanges();
  16292. return serializationObject;
  16293. };
  16294. /**
  16295. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16296. * This new light is named "name" and added to the passed scene.
  16297. */
  16298. Light.GetConstructorFromName = function (type, name, scene) {
  16299. switch (type) {
  16300. case 0:
  16301. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16302. case 1:
  16303. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16304. case 2:
  16305. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16306. case 3:
  16307. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16308. }
  16309. return null;
  16310. };
  16311. /**
  16312. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16313. */
  16314. Light.Parse = function (parsedLight, scene) {
  16315. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16316. if (!constructor) {
  16317. return null;
  16318. }
  16319. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16320. // Inclusion / exclusions
  16321. if (parsedLight.excludedMeshesIds) {
  16322. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16323. }
  16324. if (parsedLight.includedOnlyMeshesIds) {
  16325. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16326. }
  16327. // Parent
  16328. if (parsedLight.parentId) {
  16329. light._waitingParentId = parsedLight.parentId;
  16330. }
  16331. // Animations
  16332. if (parsedLight.animations) {
  16333. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16334. var parsedAnimation = parsedLight.animations[animationIndex];
  16335. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16336. }
  16337. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16338. }
  16339. if (parsedLight.autoAnimate) {
  16340. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16341. }
  16342. return light;
  16343. };
  16344. Light.prototype._hookArrayForExcluded = function (array) {
  16345. var _this = this;
  16346. var oldPush = array.push;
  16347. array.push = function () {
  16348. var items = [];
  16349. for (var _i = 0; _i < arguments.length; _i++) {
  16350. items[_i] = arguments[_i];
  16351. }
  16352. var result = oldPush.apply(array, items);
  16353. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16354. var item = items_1[_a];
  16355. item._resyncLighSource(_this);
  16356. }
  16357. return result;
  16358. };
  16359. var oldSplice = array.splice;
  16360. array.splice = function (index, deleteCount) {
  16361. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16362. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16363. var item = deleted_1[_i];
  16364. item._resyncLighSource(_this);
  16365. }
  16366. return deleted;
  16367. };
  16368. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16369. var item = array_1[_i];
  16370. item._resyncLighSource(this);
  16371. }
  16372. };
  16373. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16374. var _this = this;
  16375. var oldPush = array.push;
  16376. array.push = function () {
  16377. var items = [];
  16378. for (var _i = 0; _i < arguments.length; _i++) {
  16379. items[_i] = arguments[_i];
  16380. }
  16381. var result = oldPush.apply(array, items);
  16382. _this._resyncMeshes();
  16383. return result;
  16384. };
  16385. var oldSplice = array.splice;
  16386. array.splice = function (index, deleteCount) {
  16387. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16388. _this._resyncMeshes();
  16389. return deleted;
  16390. };
  16391. this._resyncMeshes();
  16392. };
  16393. Light.prototype._resyncMeshes = function () {
  16394. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16395. var mesh = _a[_i];
  16396. mesh._resyncLighSource(this);
  16397. }
  16398. };
  16399. Light.prototype._markMeshesAsLightDirty = function () {
  16400. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16401. var mesh = _a[_i];
  16402. if (mesh._lightSources.indexOf(this) !== -1) {
  16403. mesh._markSubMeshesAsLightDirty();
  16404. }
  16405. }
  16406. };
  16407. /**
  16408. * Recomputes the cached photometric scale if needed.
  16409. */
  16410. Light.prototype._computePhotometricScale = function () {
  16411. this._photometricScale = this._getPhotometricScale();
  16412. this.getScene().resetCachedMaterial();
  16413. };
  16414. /**
  16415. * Returns the Photometric Scale according to the light type and intensity mode.
  16416. */
  16417. Light.prototype._getPhotometricScale = function () {
  16418. var photometricScale = 0.0;
  16419. var lightTypeID = this.getTypeID();
  16420. //get photometric mode
  16421. var photometricMode = this.intensityMode;
  16422. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16423. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16424. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16425. }
  16426. else {
  16427. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16428. }
  16429. }
  16430. //compute photometric scale
  16431. switch (lightTypeID) {
  16432. case Light.LIGHTTYPEID_POINTLIGHT:
  16433. case Light.LIGHTTYPEID_SPOTLIGHT:
  16434. switch (photometricMode) {
  16435. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16436. photometricScale = 1.0 / (4.0 * Math.PI);
  16437. break;
  16438. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16439. photometricScale = 1.0;
  16440. break;
  16441. case Light.INTENSITYMODE_LUMINANCE:
  16442. photometricScale = this.radius * this.radius;
  16443. break;
  16444. }
  16445. break;
  16446. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16447. switch (photometricMode) {
  16448. case Light.INTENSITYMODE_ILLUMINANCE:
  16449. photometricScale = 1.0;
  16450. break;
  16451. case Light.INTENSITYMODE_LUMINANCE:
  16452. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16453. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16454. var apexAngleRadians = this.radius;
  16455. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16456. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16457. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16458. photometricScale = solidAngle;
  16459. break;
  16460. }
  16461. break;
  16462. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16463. // No fall off in hemisperic light.
  16464. photometricScale = 1.0;
  16465. break;
  16466. }
  16467. return photometricScale;
  16468. };
  16469. Light.prototype._reorderLightsInScene = function () {
  16470. var scene = this.getScene();
  16471. if (this._renderPriority != 0) {
  16472. scene.requireLightSorting = true;
  16473. }
  16474. this.getScene().sortLightsByPriority();
  16475. };
  16476. //lightmapMode Consts
  16477. Light._LIGHTMAP_DEFAULT = 0;
  16478. Light._LIGHTMAP_SPECULAR = 1;
  16479. Light._LIGHTMAP_SHADOWSONLY = 2;
  16480. // Intensity Mode Consts
  16481. Light._INTENSITYMODE_AUTOMATIC = 0;
  16482. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16483. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16484. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16485. Light._INTENSITYMODE_LUMINANCE = 4;
  16486. // Light types ids const.
  16487. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16488. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16489. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16490. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16491. __decorate([
  16492. BABYLON.serializeAsColor3()
  16493. ], Light.prototype, "diffuse", void 0);
  16494. __decorate([
  16495. BABYLON.serializeAsColor3()
  16496. ], Light.prototype, "specular", void 0);
  16497. __decorate([
  16498. BABYLON.serialize()
  16499. ], Light.prototype, "intensity", void 0);
  16500. __decorate([
  16501. BABYLON.serialize()
  16502. ], Light.prototype, "range", void 0);
  16503. __decorate([
  16504. BABYLON.serialize()
  16505. ], Light.prototype, "intensityMode", null);
  16506. __decorate([
  16507. BABYLON.serialize()
  16508. ], Light.prototype, "radius", null);
  16509. __decorate([
  16510. BABYLON.serialize()
  16511. ], Light.prototype, "_renderPriority", void 0);
  16512. __decorate([
  16513. BABYLON.expandToProperty("_reorderLightsInScene")
  16514. ], Light.prototype, "renderPriority", void 0);
  16515. __decorate([
  16516. BABYLON.serialize()
  16517. ], Light.prototype, "shadowEnabled", void 0);
  16518. __decorate([
  16519. BABYLON.serialize("excludeWithLayerMask")
  16520. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16521. __decorate([
  16522. BABYLON.serialize("includeOnlyWithLayerMask")
  16523. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16524. __decorate([
  16525. BABYLON.serialize("lightmapMode")
  16526. ], Light.prototype, "_lightmapMode", void 0);
  16527. return Light;
  16528. }(BABYLON.Node));
  16529. BABYLON.Light = Light;
  16530. })(BABYLON || (BABYLON = {}));
  16531. //# sourceMappingURL=babylon.light.js.map
  16532. var BABYLON;
  16533. (function (BABYLON) {
  16534. var Camera = /** @class */ (function (_super) {
  16535. __extends(Camera, _super);
  16536. function Camera(name, position, scene) {
  16537. var _this = _super.call(this, name, scene) || this;
  16538. _this.upVector = BABYLON.Vector3.Up();
  16539. _this.orthoLeft = null;
  16540. _this.orthoRight = null;
  16541. _this.orthoBottom = null;
  16542. _this.orthoTop = null;
  16543. _this.fov = 0.8;
  16544. _this.minZ = 1;
  16545. _this.maxZ = 10000.0;
  16546. _this.inertia = 0.9;
  16547. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16548. _this.isIntermediate = false;
  16549. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16550. _this.layerMask = 0x0FFFFFFF;
  16551. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16552. // Camera rig members
  16553. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16554. _this._rigCameras = new Array();
  16555. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16556. _this._skipRendering = false;
  16557. _this.customRenderTargets = new Array();
  16558. // Observables
  16559. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16560. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16561. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16562. _this.onRestoreStateObservable = new BABYLON.Observable();
  16563. // Cache
  16564. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16565. _this._projectionMatrix = new BABYLON.Matrix();
  16566. _this._doNotComputeProjectionMatrix = false;
  16567. _this._postProcesses = new Array();
  16568. _this._transformMatrix = BABYLON.Matrix.Zero();
  16569. _this._activeMeshes = new BABYLON.SmartArray(256);
  16570. _this._globalPosition = BABYLON.Vector3.Zero();
  16571. _this._refreshFrustumPlanes = true;
  16572. _this.getScene().addCamera(_this);
  16573. if (!_this.getScene().activeCamera) {
  16574. _this.getScene().activeCamera = _this;
  16575. }
  16576. _this.position = position;
  16577. return _this;
  16578. }
  16579. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16580. get: function () {
  16581. return Camera._PERSPECTIVE_CAMERA;
  16582. },
  16583. enumerable: true,
  16584. configurable: true
  16585. });
  16586. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16587. get: function () {
  16588. return Camera._ORTHOGRAPHIC_CAMERA;
  16589. },
  16590. enumerable: true,
  16591. configurable: true
  16592. });
  16593. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16594. get: function () {
  16595. return Camera._FOVMODE_VERTICAL_FIXED;
  16596. },
  16597. enumerable: true,
  16598. configurable: true
  16599. });
  16600. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16601. get: function () {
  16602. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16603. },
  16604. enumerable: true,
  16605. configurable: true
  16606. });
  16607. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16608. get: function () {
  16609. return Camera._RIG_MODE_NONE;
  16610. },
  16611. enumerable: true,
  16612. configurable: true
  16613. });
  16614. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16615. get: function () {
  16616. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16617. },
  16618. enumerable: true,
  16619. configurable: true
  16620. });
  16621. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16622. get: function () {
  16623. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16624. },
  16625. enumerable: true,
  16626. configurable: true
  16627. });
  16628. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16629. get: function () {
  16630. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16631. },
  16632. enumerable: true,
  16633. configurable: true
  16634. });
  16635. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16636. get: function () {
  16637. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16638. },
  16639. enumerable: true,
  16640. configurable: true
  16641. });
  16642. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16643. get: function () {
  16644. return Camera._RIG_MODE_VR;
  16645. },
  16646. enumerable: true,
  16647. configurable: true
  16648. });
  16649. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16650. get: function () {
  16651. return Camera._RIG_MODE_WEBVR;
  16652. },
  16653. enumerable: true,
  16654. configurable: true
  16655. });
  16656. /**
  16657. * Store current camera state (fov, position, etc..)
  16658. */
  16659. Camera.prototype.storeState = function () {
  16660. this._stateStored = true;
  16661. this._storedFov = this.fov;
  16662. return this;
  16663. };
  16664. /**
  16665. * Restores the camera state values if it has been stored. You must call storeState() first
  16666. */
  16667. Camera.prototype._restoreStateValues = function () {
  16668. if (!this._stateStored) {
  16669. return false;
  16670. }
  16671. this.fov = this._storedFov;
  16672. return true;
  16673. };
  16674. /**
  16675. * Restored camera state. You must call storeState() first
  16676. */
  16677. Camera.prototype.restoreState = function () {
  16678. if (this._restoreStateValues()) {
  16679. this.onRestoreStateObservable.notifyObservers(this);
  16680. return true;
  16681. }
  16682. return false;
  16683. };
  16684. Camera.prototype.getClassName = function () {
  16685. return "Camera";
  16686. };
  16687. /**
  16688. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16689. */
  16690. Camera.prototype.toString = function (fullDetails) {
  16691. var ret = "Name: " + this.name;
  16692. ret += ", type: " + this.getClassName();
  16693. if (this.animations) {
  16694. for (var i = 0; i < this.animations.length; i++) {
  16695. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16696. }
  16697. }
  16698. if (fullDetails) {
  16699. }
  16700. return ret;
  16701. };
  16702. Object.defineProperty(Camera.prototype, "globalPosition", {
  16703. get: function () {
  16704. return this._globalPosition;
  16705. },
  16706. enumerable: true,
  16707. configurable: true
  16708. });
  16709. Camera.prototype.getActiveMeshes = function () {
  16710. return this._activeMeshes;
  16711. };
  16712. Camera.prototype.isActiveMesh = function (mesh) {
  16713. return (this._activeMeshes.indexOf(mesh) !== -1);
  16714. };
  16715. //Cache
  16716. Camera.prototype._initCache = function () {
  16717. _super.prototype._initCache.call(this);
  16718. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16719. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16720. this._cache.mode = undefined;
  16721. this._cache.minZ = undefined;
  16722. this._cache.maxZ = undefined;
  16723. this._cache.fov = undefined;
  16724. this._cache.fovMode = undefined;
  16725. this._cache.aspectRatio = undefined;
  16726. this._cache.orthoLeft = undefined;
  16727. this._cache.orthoRight = undefined;
  16728. this._cache.orthoBottom = undefined;
  16729. this._cache.orthoTop = undefined;
  16730. this._cache.renderWidth = undefined;
  16731. this._cache.renderHeight = undefined;
  16732. };
  16733. Camera.prototype._updateCache = function (ignoreParentClass) {
  16734. if (!ignoreParentClass) {
  16735. _super.prototype._updateCache.call(this);
  16736. }
  16737. this._cache.position.copyFrom(this.position);
  16738. this._cache.upVector.copyFrom(this.upVector);
  16739. };
  16740. // Synchronized
  16741. Camera.prototype._isSynchronized = function () {
  16742. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16743. };
  16744. Camera.prototype._isSynchronizedViewMatrix = function () {
  16745. if (!_super.prototype._isSynchronized.call(this))
  16746. return false;
  16747. return this._cache.position.equals(this.position)
  16748. && this._cache.upVector.equals(this.upVector)
  16749. && this.isSynchronizedWithParent();
  16750. };
  16751. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16752. var check = this._cache.mode === this.mode
  16753. && this._cache.minZ === this.minZ
  16754. && this._cache.maxZ === this.maxZ;
  16755. if (!check) {
  16756. return false;
  16757. }
  16758. var engine = this.getEngine();
  16759. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16760. check = this._cache.fov === this.fov
  16761. && this._cache.fovMode === this.fovMode
  16762. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16763. }
  16764. else {
  16765. check = this._cache.orthoLeft === this.orthoLeft
  16766. && this._cache.orthoRight === this.orthoRight
  16767. && this._cache.orthoBottom === this.orthoBottom
  16768. && this._cache.orthoTop === this.orthoTop
  16769. && this._cache.renderWidth === engine.getRenderWidth()
  16770. && this._cache.renderHeight === engine.getRenderHeight();
  16771. }
  16772. return check;
  16773. };
  16774. // Controls
  16775. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16776. };
  16777. Camera.prototype.detachControl = function (element) {
  16778. };
  16779. Camera.prototype.update = function () {
  16780. this._checkInputs();
  16781. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16782. this._updateRigCameras();
  16783. }
  16784. };
  16785. Camera.prototype._checkInputs = function () {
  16786. this.onAfterCheckInputsObservable.notifyObservers(this);
  16787. };
  16788. Object.defineProperty(Camera.prototype, "rigCameras", {
  16789. get: function () {
  16790. return this._rigCameras;
  16791. },
  16792. enumerable: true,
  16793. configurable: true
  16794. });
  16795. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16796. get: function () {
  16797. return this._rigPostProcess;
  16798. },
  16799. enumerable: true,
  16800. configurable: true
  16801. });
  16802. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16803. // invalidate framebuffer
  16804. if (this._postProcesses.length > 0) {
  16805. this._postProcesses[0].markTextureDirty();
  16806. }
  16807. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16808. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16809. var cam = this._rigCameras[i];
  16810. var rigPostProcess = cam._rigPostProcess;
  16811. // for VR rig, there does not have to be a post process
  16812. if (rigPostProcess) {
  16813. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16814. if (isPass) {
  16815. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16816. cam.isIntermediate = this._postProcesses.length === 0;
  16817. }
  16818. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16819. rigPostProcess.markTextureDirty();
  16820. }
  16821. else {
  16822. cam._postProcesses = this._postProcesses.slice(0);
  16823. }
  16824. }
  16825. };
  16826. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16827. if (insertAt === void 0) { insertAt = null; }
  16828. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16829. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16830. return 0;
  16831. }
  16832. if (insertAt == null || insertAt < 0) {
  16833. this._postProcesses.push(postProcess);
  16834. }
  16835. else {
  16836. this._postProcesses.splice(insertAt, 0, postProcess);
  16837. }
  16838. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16839. return this._postProcesses.indexOf(postProcess);
  16840. };
  16841. Camera.prototype.detachPostProcess = function (postProcess) {
  16842. var idx = this._postProcesses.indexOf(postProcess);
  16843. if (idx !== -1) {
  16844. this._postProcesses.splice(idx, 1);
  16845. }
  16846. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16847. };
  16848. Camera.prototype.getWorldMatrix = function () {
  16849. if (!this._worldMatrix) {
  16850. this._worldMatrix = BABYLON.Matrix.Identity();
  16851. }
  16852. var viewMatrix = this.getViewMatrix();
  16853. viewMatrix.invertToRef(this._worldMatrix);
  16854. return this._worldMatrix;
  16855. };
  16856. Camera.prototype._getViewMatrix = function () {
  16857. return BABYLON.Matrix.Identity();
  16858. };
  16859. Camera.prototype.getViewMatrix = function (force) {
  16860. if (!force && this._isSynchronizedViewMatrix()) {
  16861. return this._computedViewMatrix;
  16862. }
  16863. this.updateCache();
  16864. this._computedViewMatrix = this._getViewMatrix();
  16865. this._currentRenderId = this.getScene().getRenderId();
  16866. this._refreshFrustumPlanes = true;
  16867. if (!this.parent || !this.parent.getWorldMatrix) {
  16868. this._globalPosition.copyFrom(this.position);
  16869. }
  16870. else {
  16871. if (!this._worldMatrix) {
  16872. this._worldMatrix = BABYLON.Matrix.Identity();
  16873. }
  16874. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16875. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16876. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16877. this._computedViewMatrix.invert();
  16878. this._markSyncedWithParent();
  16879. }
  16880. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16881. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16882. }
  16883. this.onViewMatrixChangedObservable.notifyObservers(this);
  16884. return this._computedViewMatrix;
  16885. };
  16886. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16887. this._doNotComputeProjectionMatrix = true;
  16888. if (projection !== undefined) {
  16889. this._projectionMatrix = projection;
  16890. }
  16891. };
  16892. ;
  16893. Camera.prototype.unfreezeProjectionMatrix = function () {
  16894. this._doNotComputeProjectionMatrix = false;
  16895. };
  16896. ;
  16897. Camera.prototype.getProjectionMatrix = function (force) {
  16898. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16899. return this._projectionMatrix;
  16900. }
  16901. // Cache
  16902. this._cache.mode = this.mode;
  16903. this._cache.minZ = this.minZ;
  16904. this._cache.maxZ = this.maxZ;
  16905. // Matrix
  16906. this._refreshFrustumPlanes = true;
  16907. var engine = this.getEngine();
  16908. var scene = this.getScene();
  16909. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16910. this._cache.fov = this.fov;
  16911. this._cache.fovMode = this.fovMode;
  16912. this._cache.aspectRatio = engine.getAspectRatio(this);
  16913. if (this.minZ <= 0) {
  16914. this.minZ = 0.1;
  16915. }
  16916. if (scene.useRightHandedSystem) {
  16917. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16918. }
  16919. else {
  16920. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16921. }
  16922. }
  16923. else {
  16924. var halfWidth = engine.getRenderWidth() / 2.0;
  16925. var halfHeight = engine.getRenderHeight() / 2.0;
  16926. if (scene.useRightHandedSystem) {
  16927. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16928. }
  16929. else {
  16930. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16931. }
  16932. this._cache.orthoLeft = this.orthoLeft;
  16933. this._cache.orthoRight = this.orthoRight;
  16934. this._cache.orthoBottom = this.orthoBottom;
  16935. this._cache.orthoTop = this.orthoTop;
  16936. this._cache.renderWidth = engine.getRenderWidth();
  16937. this._cache.renderHeight = engine.getRenderHeight();
  16938. }
  16939. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16940. return this._projectionMatrix;
  16941. };
  16942. Camera.prototype.getTranformationMatrix = function () {
  16943. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16944. return this._transformMatrix;
  16945. };
  16946. Camera.prototype.updateFrustumPlanes = function () {
  16947. if (!this._refreshFrustumPlanes) {
  16948. return;
  16949. }
  16950. this.getTranformationMatrix();
  16951. if (!this._frustumPlanes) {
  16952. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16953. }
  16954. else {
  16955. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16956. }
  16957. this._refreshFrustumPlanes = false;
  16958. };
  16959. Camera.prototype.isInFrustum = function (target) {
  16960. this.updateFrustumPlanes();
  16961. return target.isInFrustum(this._frustumPlanes);
  16962. };
  16963. Camera.prototype.isCompletelyInFrustum = function (target) {
  16964. this.updateFrustumPlanes();
  16965. return target.isCompletelyInFrustum(this._frustumPlanes);
  16966. };
  16967. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16968. if (length === void 0) { length = 100; }
  16969. if (!transform) {
  16970. transform = this.getWorldMatrix();
  16971. }
  16972. if (!origin) {
  16973. origin = this.position;
  16974. }
  16975. var forward = new BABYLON.Vector3(0, 0, 1);
  16976. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16977. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16978. return new BABYLON.Ray(origin, direction, length);
  16979. };
  16980. Camera.prototype.dispose = function () {
  16981. // Observables
  16982. this.onViewMatrixChangedObservable.clear();
  16983. this.onProjectionMatrixChangedObservable.clear();
  16984. this.onAfterCheckInputsObservable.clear();
  16985. this.onRestoreStateObservable.clear();
  16986. // Inputs
  16987. if (this.inputs) {
  16988. this.inputs.clear();
  16989. }
  16990. // Animations
  16991. this.getScene().stopAnimation(this);
  16992. // Remove from scene
  16993. this.getScene().removeCamera(this);
  16994. while (this._rigCameras.length > 0) {
  16995. var camera = this._rigCameras.pop();
  16996. if (camera) {
  16997. camera.dispose();
  16998. }
  16999. }
  17000. // Postprocesses
  17001. if (this._rigPostProcess) {
  17002. this._rigPostProcess.dispose(this);
  17003. this._rigPostProcess = null;
  17004. this._postProcesses = [];
  17005. }
  17006. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17007. this._rigPostProcess = null;
  17008. this._postProcesses = [];
  17009. }
  17010. else {
  17011. var i = this._postProcesses.length;
  17012. while (--i >= 0) {
  17013. this._postProcesses[i].dispose(this);
  17014. }
  17015. }
  17016. // Render targets
  17017. var i = this.customRenderTargets.length;
  17018. while (--i >= 0) {
  17019. this.customRenderTargets[i].dispose();
  17020. }
  17021. this.customRenderTargets = [];
  17022. // Active Meshes
  17023. this._activeMeshes.dispose();
  17024. _super.prototype.dispose.call(this);
  17025. };
  17026. Object.defineProperty(Camera.prototype, "leftCamera", {
  17027. // ---- Camera rigs section ----
  17028. get: function () {
  17029. if (this._rigCameras.length < 1) {
  17030. return null;
  17031. }
  17032. return this._rigCameras[0];
  17033. },
  17034. enumerable: true,
  17035. configurable: true
  17036. });
  17037. Object.defineProperty(Camera.prototype, "rightCamera", {
  17038. get: function () {
  17039. if (this._rigCameras.length < 2) {
  17040. return null;
  17041. }
  17042. return this._rigCameras[1];
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. Camera.prototype.getLeftTarget = function () {
  17048. if (this._rigCameras.length < 1) {
  17049. return null;
  17050. }
  17051. return this._rigCameras[0].getTarget();
  17052. };
  17053. Camera.prototype.getRightTarget = function () {
  17054. if (this._rigCameras.length < 2) {
  17055. return null;
  17056. }
  17057. return this._rigCameras[1].getTarget();
  17058. };
  17059. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  17060. if (this.cameraRigMode === mode) {
  17061. return;
  17062. }
  17063. while (this._rigCameras.length > 0) {
  17064. var camera = this._rigCameras.pop();
  17065. if (camera) {
  17066. camera.dispose();
  17067. }
  17068. }
  17069. this.cameraRigMode = mode;
  17070. this._cameraRigParams = {};
  17071. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  17072. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  17073. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  17074. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  17075. // create the rig cameras, unless none
  17076. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17077. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  17078. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  17079. if (leftCamera && rightCamera) {
  17080. this._rigCameras.push(leftCamera);
  17081. this._rigCameras.push(rightCamera);
  17082. }
  17083. }
  17084. switch (this.cameraRigMode) {
  17085. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17086. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17087. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  17088. break;
  17089. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17090. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17091. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17092. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17093. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17094. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  17095. break;
  17096. case Camera.RIG_MODE_VR:
  17097. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  17098. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  17099. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17100. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17101. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  17102. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  17103. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  17104. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  17105. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17106. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17107. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  17108. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  17109. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  17110. if (metrics.compensateDistortion) {
  17111. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  17112. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  17113. }
  17114. break;
  17115. case Camera.RIG_MODE_WEBVR:
  17116. if (rigParams.vrDisplay) {
  17117. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  17118. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  17119. //Left eye
  17120. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17121. this._rigCameras[0].setCameraRigParameter("left", true);
  17122. //leaving this for future reference
  17123. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  17124. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  17125. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  17126. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17127. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17128. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17129. this._rigCameras[0].parent = this;
  17130. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  17131. //Right eye
  17132. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17133. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  17134. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  17135. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  17136. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17137. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17138. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17139. this._rigCameras[1].parent = this;
  17140. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  17141. if (Camera.UseAlternateWebVRRendering) {
  17142. this._rigCameras[1]._skipRendering = true;
  17143. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  17144. }
  17145. }
  17146. break;
  17147. }
  17148. this._cascadePostProcessesToRigCams();
  17149. this.update();
  17150. };
  17151. Camera.prototype._getVRProjectionMatrix = function () {
  17152. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  17153. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  17154. return this._projectionMatrix;
  17155. };
  17156. Camera.prototype._updateCameraRotationMatrix = function () {
  17157. //Here for WebVR
  17158. };
  17159. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17160. //Here for WebVR
  17161. };
  17162. /**
  17163. * This function MUST be overwritten by the different WebVR cameras available.
  17164. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17165. */
  17166. Camera.prototype._getWebVRProjectionMatrix = function () {
  17167. return BABYLON.Matrix.Identity();
  17168. };
  17169. /**
  17170. * This function MUST be overwritten by the different WebVR cameras available.
  17171. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17172. */
  17173. Camera.prototype._getWebVRViewMatrix = function () {
  17174. return BABYLON.Matrix.Identity();
  17175. };
  17176. Camera.prototype.setCameraRigParameter = function (name, value) {
  17177. if (!this._cameraRigParams) {
  17178. this._cameraRigParams = {};
  17179. }
  17180. this._cameraRigParams[name] = value;
  17181. //provisionnally:
  17182. if (name === "interaxialDistance") {
  17183. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17184. }
  17185. };
  17186. /**
  17187. * needs to be overridden by children so sub has required properties to be copied
  17188. */
  17189. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17190. return null;
  17191. };
  17192. /**
  17193. * May need to be overridden by children
  17194. */
  17195. Camera.prototype._updateRigCameras = function () {
  17196. for (var i = 0; i < this._rigCameras.length; i++) {
  17197. this._rigCameras[i].minZ = this.minZ;
  17198. this._rigCameras[i].maxZ = this.maxZ;
  17199. this._rigCameras[i].fov = this.fov;
  17200. }
  17201. // only update viewport when ANAGLYPH
  17202. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17203. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17204. }
  17205. };
  17206. Camera.prototype._setupInputs = function () {
  17207. };
  17208. Camera.prototype.serialize = function () {
  17209. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17210. // Type
  17211. serializationObject.type = this.getClassName();
  17212. // Parent
  17213. if (this.parent) {
  17214. serializationObject.parentId = this.parent.id;
  17215. }
  17216. if (this.inputs) {
  17217. this.inputs.serialize(serializationObject);
  17218. }
  17219. // Animations
  17220. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17221. serializationObject.ranges = this.serializeAnimationRanges();
  17222. return serializationObject;
  17223. };
  17224. Camera.prototype.clone = function (name) {
  17225. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17226. };
  17227. Camera.prototype.getDirection = function (localAxis) {
  17228. var result = BABYLON.Vector3.Zero();
  17229. this.getDirectionToRef(localAxis, result);
  17230. return result;
  17231. };
  17232. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17233. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17234. };
  17235. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17236. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17237. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17238. switch (type) {
  17239. case "ArcRotateCamera":
  17240. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17241. case "DeviceOrientationCamera":
  17242. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17243. case "FollowCamera":
  17244. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17245. case "ArcFollowCamera":
  17246. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17247. case "GamepadCamera":
  17248. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17249. case "TouchCamera":
  17250. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17251. case "VirtualJoysticksCamera":
  17252. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17253. case "WebVRFreeCamera":
  17254. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17255. case "WebVRGamepadCamera":
  17256. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17257. case "VRDeviceOrientationFreeCamera":
  17258. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17259. case "VRDeviceOrientationGamepadCamera":
  17260. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17261. case "AnaglyphArcRotateCamera":
  17262. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17263. case "AnaglyphFreeCamera":
  17264. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17265. case "AnaglyphGamepadCamera":
  17266. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17267. case "AnaglyphUniversalCamera":
  17268. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17269. case "StereoscopicArcRotateCamera":
  17270. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17271. case "StereoscopicFreeCamera":
  17272. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17273. case "StereoscopicGamepadCamera":
  17274. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17275. case "StereoscopicUniversalCamera":
  17276. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17277. case "FreeCamera":// Forcing Universal here
  17278. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17279. default:// Universal Camera is the default value
  17280. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17281. }
  17282. };
  17283. Camera.prototype.computeWorldMatrix = function () {
  17284. return this.getWorldMatrix();
  17285. };
  17286. Camera.Parse = function (parsedCamera, scene) {
  17287. var type = parsedCamera.type;
  17288. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17289. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17290. // Parent
  17291. if (parsedCamera.parentId) {
  17292. camera._waitingParentId = parsedCamera.parentId;
  17293. }
  17294. //If camera has an input manager, let it parse inputs settings
  17295. if (camera.inputs) {
  17296. camera.inputs.parse(parsedCamera);
  17297. camera._setupInputs();
  17298. }
  17299. if (camera.setPosition) {
  17300. camera.position.copyFromFloats(0, 0, 0);
  17301. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17302. }
  17303. // Target
  17304. if (parsedCamera.target) {
  17305. if (camera.setTarget) {
  17306. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17307. }
  17308. }
  17309. // Apply 3d rig, when found
  17310. if (parsedCamera.cameraRigMode) {
  17311. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17312. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17313. }
  17314. // Animations
  17315. if (parsedCamera.animations) {
  17316. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17317. var parsedAnimation = parsedCamera.animations[animationIndex];
  17318. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17319. }
  17320. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17321. }
  17322. if (parsedCamera.autoAnimate) {
  17323. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17324. }
  17325. return camera;
  17326. };
  17327. // Statics
  17328. Camera._PERSPECTIVE_CAMERA = 0;
  17329. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17330. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17331. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17332. Camera._RIG_MODE_NONE = 0;
  17333. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17334. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17335. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17336. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17337. Camera._RIG_MODE_VR = 20;
  17338. Camera._RIG_MODE_WEBVR = 21;
  17339. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17340. Camera.UseAlternateWebVRRendering = false;
  17341. __decorate([
  17342. BABYLON.serializeAsVector3()
  17343. ], Camera.prototype, "position", void 0);
  17344. __decorate([
  17345. BABYLON.serializeAsVector3()
  17346. ], Camera.prototype, "upVector", void 0);
  17347. __decorate([
  17348. BABYLON.serialize()
  17349. ], Camera.prototype, "orthoLeft", void 0);
  17350. __decorate([
  17351. BABYLON.serialize()
  17352. ], Camera.prototype, "orthoRight", void 0);
  17353. __decorate([
  17354. BABYLON.serialize()
  17355. ], Camera.prototype, "orthoBottom", void 0);
  17356. __decorate([
  17357. BABYLON.serialize()
  17358. ], Camera.prototype, "orthoTop", void 0);
  17359. __decorate([
  17360. BABYLON.serialize()
  17361. ], Camera.prototype, "fov", void 0);
  17362. __decorate([
  17363. BABYLON.serialize()
  17364. ], Camera.prototype, "minZ", void 0);
  17365. __decorate([
  17366. BABYLON.serialize()
  17367. ], Camera.prototype, "maxZ", void 0);
  17368. __decorate([
  17369. BABYLON.serialize()
  17370. ], Camera.prototype, "inertia", void 0);
  17371. __decorate([
  17372. BABYLON.serialize()
  17373. ], Camera.prototype, "mode", void 0);
  17374. __decorate([
  17375. BABYLON.serialize()
  17376. ], Camera.prototype, "layerMask", void 0);
  17377. __decorate([
  17378. BABYLON.serialize()
  17379. ], Camera.prototype, "fovMode", void 0);
  17380. __decorate([
  17381. BABYLON.serialize()
  17382. ], Camera.prototype, "cameraRigMode", void 0);
  17383. __decorate([
  17384. BABYLON.serialize()
  17385. ], Camera.prototype, "interaxialDistance", void 0);
  17386. __decorate([
  17387. BABYLON.serialize()
  17388. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17389. return Camera;
  17390. }(BABYLON.Node));
  17391. BABYLON.Camera = Camera;
  17392. })(BABYLON || (BABYLON = {}));
  17393. //# sourceMappingURL=babylon.camera.js.map
  17394. var BABYLON;
  17395. (function (BABYLON) {
  17396. var RenderingManager = /** @class */ (function () {
  17397. function RenderingManager(scene) {
  17398. this._renderingGroups = new Array();
  17399. this._autoClearDepthStencil = {};
  17400. this._customOpaqueSortCompareFn = {};
  17401. this._customAlphaTestSortCompareFn = {};
  17402. this._customTransparentSortCompareFn = {};
  17403. this._renderinGroupInfo = null;
  17404. this._scene = scene;
  17405. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17406. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17407. }
  17408. }
  17409. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17410. if (depth === void 0) { depth = true; }
  17411. if (stencil === void 0) { stencil = true; }
  17412. if (this._depthStencilBufferAlreadyCleaned) {
  17413. return;
  17414. }
  17415. this._scene.getEngine().clear(null, false, depth, stencil);
  17416. this._depthStencilBufferAlreadyCleaned = true;
  17417. };
  17418. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17419. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17420. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17421. var info = null;
  17422. if (observable) {
  17423. if (!this._renderinGroupInfo) {
  17424. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17425. }
  17426. info = this._renderinGroupInfo;
  17427. info.scene = this._scene;
  17428. info.camera = this._scene.activeCamera;
  17429. }
  17430. // Dispatch sprites
  17431. if (renderSprites) {
  17432. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17433. var manager = this._scene.spriteManagers[index];
  17434. this.dispatchSprites(manager);
  17435. }
  17436. }
  17437. // Render
  17438. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17439. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17440. var renderingGroup = this._renderingGroups[index];
  17441. if (!renderingGroup && !observable)
  17442. continue;
  17443. var renderingGroupMask = 0;
  17444. // Fire PRECLEAR stage
  17445. if (observable && info) {
  17446. renderingGroupMask = Math.pow(2, index);
  17447. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17448. info.renderingGroupId = index;
  17449. observable.notifyObservers(info, renderingGroupMask);
  17450. }
  17451. // Clear depth/stencil if needed
  17452. if (RenderingManager.AUTOCLEAR) {
  17453. var autoClear = this._autoClearDepthStencil[index];
  17454. if (autoClear && autoClear.autoClear) {
  17455. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17456. }
  17457. }
  17458. if (observable && info) {
  17459. // Fire PREOPAQUE stage
  17460. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17461. observable.notifyObservers(info, renderingGroupMask);
  17462. // Fire PRETRANSPARENT stage
  17463. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17464. observable.notifyObservers(info, renderingGroupMask);
  17465. }
  17466. if (renderingGroup)
  17467. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17468. // Fire POSTTRANSPARENT stage
  17469. if (observable && info) {
  17470. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17471. observable.notifyObservers(info, renderingGroupMask);
  17472. }
  17473. }
  17474. };
  17475. RenderingManager.prototype.reset = function () {
  17476. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17477. var renderingGroup = this._renderingGroups[index];
  17478. if (renderingGroup) {
  17479. renderingGroup.prepare();
  17480. }
  17481. }
  17482. };
  17483. RenderingManager.prototype.dispose = function () {
  17484. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17485. var renderingGroup = this._renderingGroups[index];
  17486. if (renderingGroup) {
  17487. renderingGroup.dispose();
  17488. }
  17489. }
  17490. this._renderingGroups.length = 0;
  17491. };
  17492. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17493. if (!this._renderingGroups[renderingGroupId]) {
  17494. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17495. }
  17496. };
  17497. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17498. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17499. this._prepareRenderingGroup(renderingGroupId);
  17500. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17501. };
  17502. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17503. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17504. this._prepareRenderingGroup(renderingGroupId);
  17505. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17506. };
  17507. RenderingManager.prototype.dispatch = function (subMesh) {
  17508. var mesh = subMesh.getMesh();
  17509. var renderingGroupId = mesh.renderingGroupId || 0;
  17510. this._prepareRenderingGroup(renderingGroupId);
  17511. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17512. };
  17513. /**
  17514. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17515. * This allowed control for front to back rendering or reversly depending of the special needs.
  17516. *
  17517. * @param renderingGroupId The rendering group id corresponding to its index
  17518. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17519. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17520. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17521. */
  17522. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17523. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17524. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17525. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17526. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17527. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17528. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17529. if (this._renderingGroups[renderingGroupId]) {
  17530. var group = this._renderingGroups[renderingGroupId];
  17531. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17532. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17533. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17534. }
  17535. };
  17536. /**
  17537. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17538. *
  17539. * @param renderingGroupId The rendering group id corresponding to its index
  17540. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17541. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17542. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17543. */
  17544. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17545. if (depth === void 0) { depth = true; }
  17546. if (stencil === void 0) { stencil = true; }
  17547. this._autoClearDepthStencil[renderingGroupId] = {
  17548. autoClear: autoClearDepthStencil,
  17549. depth: depth,
  17550. stencil: stencil
  17551. };
  17552. };
  17553. /**
  17554. * The max id used for rendering groups (not included)
  17555. */
  17556. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17557. /**
  17558. * The min id used for rendering groups (included)
  17559. */
  17560. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17561. /**
  17562. * Used to globally prevent autoclearing scenes.
  17563. */
  17564. RenderingManager.AUTOCLEAR = true;
  17565. return RenderingManager;
  17566. }());
  17567. BABYLON.RenderingManager = RenderingManager;
  17568. })(BABYLON || (BABYLON = {}));
  17569. //# sourceMappingURL=babylon.renderingManager.js.map
  17570. var BABYLON;
  17571. (function (BABYLON) {
  17572. var RenderingGroup = /** @class */ (function () {
  17573. /**
  17574. * Creates a new rendering group.
  17575. * @param index The rendering group index
  17576. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17577. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17578. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17579. */
  17580. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17581. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17582. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17583. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17584. this.index = index;
  17585. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17586. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17587. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17588. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17589. this._particleSystems = new BABYLON.SmartArray(256);
  17590. this._spriteManagers = new BABYLON.SmartArray(256);
  17591. this._edgesRenderers = new BABYLON.SmartArray(16);
  17592. this._scene = scene;
  17593. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17594. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17595. this.transparentSortCompareFn = transparentSortCompareFn;
  17596. }
  17597. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17598. /**
  17599. * Set the opaque sort comparison function.
  17600. * If null the sub meshes will be render in the order they were created
  17601. */
  17602. set: function (value) {
  17603. this._opaqueSortCompareFn = value;
  17604. if (value) {
  17605. this._renderOpaque = this.renderOpaqueSorted;
  17606. }
  17607. else {
  17608. this._renderOpaque = RenderingGroup.renderUnsorted;
  17609. }
  17610. },
  17611. enumerable: true,
  17612. configurable: true
  17613. });
  17614. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17615. /**
  17616. * Set the alpha test sort comparison function.
  17617. * If null the sub meshes will be render in the order they were created
  17618. */
  17619. set: function (value) {
  17620. this._alphaTestSortCompareFn = value;
  17621. if (value) {
  17622. this._renderAlphaTest = this.renderAlphaTestSorted;
  17623. }
  17624. else {
  17625. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17626. }
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17632. /**
  17633. * Set the transparent sort comparison function.
  17634. * If null the sub meshes will be render in the order they were created
  17635. */
  17636. set: function (value) {
  17637. if (value) {
  17638. this._transparentSortCompareFn = value;
  17639. }
  17640. else {
  17641. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17642. }
  17643. this._renderTransparent = this.renderTransparentSorted;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. /**
  17649. * Render all the sub meshes contained in the group.
  17650. * @param customRenderFunction Used to override the default render behaviour of the group.
  17651. * @returns true if rendered some submeshes.
  17652. */
  17653. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17654. if (customRenderFunction) {
  17655. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17656. return;
  17657. }
  17658. var engine = this._scene.getEngine();
  17659. // Depth only
  17660. if (this._depthOnlySubMeshes.length !== 0) {
  17661. engine.setAlphaTesting(true);
  17662. engine.setColorWrite(false);
  17663. this._renderAlphaTest(this._depthOnlySubMeshes);
  17664. engine.setAlphaTesting(false);
  17665. engine.setColorWrite(true);
  17666. }
  17667. // Opaque
  17668. if (this._opaqueSubMeshes.length !== 0) {
  17669. this._renderOpaque(this._opaqueSubMeshes);
  17670. }
  17671. // Alpha test
  17672. if (this._alphaTestSubMeshes.length !== 0) {
  17673. engine.setAlphaTesting(true);
  17674. this._renderAlphaTest(this._alphaTestSubMeshes);
  17675. engine.setAlphaTesting(false);
  17676. }
  17677. var stencilState = engine.getStencilBuffer();
  17678. engine.setStencilBuffer(false);
  17679. // Sprites
  17680. if (renderSprites) {
  17681. this._renderSprites();
  17682. }
  17683. // Particles
  17684. if (renderParticles) {
  17685. this._renderParticles(activeMeshes);
  17686. }
  17687. if (this.onBeforeTransparentRendering) {
  17688. this.onBeforeTransparentRendering();
  17689. }
  17690. // Transparent
  17691. if (this._transparentSubMeshes.length !== 0) {
  17692. this._renderTransparent(this._transparentSubMeshes);
  17693. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17694. }
  17695. // Set back stencil to false in case it changes before the edge renderer.
  17696. engine.setStencilBuffer(false);
  17697. // Edges
  17698. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17699. this._edgesRenderers.data[edgesRendererIndex].render();
  17700. }
  17701. // Restore Stencil state.
  17702. engine.setStencilBuffer(stencilState);
  17703. };
  17704. /**
  17705. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17706. * @param subMeshes The submeshes to render
  17707. */
  17708. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17709. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17710. };
  17711. /**
  17712. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17713. * @param subMeshes The submeshes to render
  17714. */
  17715. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17716. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17717. };
  17718. /**
  17719. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17720. * @param subMeshes The submeshes to render
  17721. */
  17722. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17723. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17724. };
  17725. /**
  17726. * Renders the submeshes in a specified order.
  17727. * @param subMeshes The submeshes to sort before render
  17728. * @param sortCompareFn The comparison function use to sort
  17729. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17730. * @param transparent Specifies to activate blending if true
  17731. */
  17732. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17733. var subIndex = 0;
  17734. var subMesh;
  17735. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17736. for (; subIndex < subMeshes.length; subIndex++) {
  17737. subMesh = subMeshes.data[subIndex];
  17738. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17739. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17740. }
  17741. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17742. if (sortCompareFn) {
  17743. sortedArray.sort(sortCompareFn);
  17744. }
  17745. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17746. subMesh = sortedArray[subIndex];
  17747. if (transparent) {
  17748. var material = subMesh.getMaterial();
  17749. if (material && material.needDepthPrePass) {
  17750. var engine = material.getScene().getEngine();
  17751. engine.setColorWrite(false);
  17752. engine.setAlphaTesting(true);
  17753. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17754. subMesh.render(false);
  17755. engine.setAlphaTesting(false);
  17756. engine.setColorWrite(true);
  17757. }
  17758. }
  17759. subMesh.render(transparent);
  17760. }
  17761. };
  17762. /**
  17763. * Renders the submeshes in the order they were dispatched (no sort applied).
  17764. * @param subMeshes The submeshes to render
  17765. */
  17766. RenderingGroup.renderUnsorted = function (subMeshes) {
  17767. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17768. var submesh = subMeshes.data[subIndex];
  17769. submesh.render(false);
  17770. }
  17771. };
  17772. /**
  17773. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17774. * are rendered back to front if in the same alpha index.
  17775. *
  17776. * @param a The first submesh
  17777. * @param b The second submesh
  17778. * @returns The result of the comparison
  17779. */
  17780. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17781. // Alpha index first
  17782. if (a._alphaIndex > b._alphaIndex) {
  17783. return 1;
  17784. }
  17785. if (a._alphaIndex < b._alphaIndex) {
  17786. return -1;
  17787. }
  17788. // Then distance to camera
  17789. return RenderingGroup.backToFrontSortCompare(a, b);
  17790. };
  17791. /**
  17792. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17793. * are rendered back to front.
  17794. *
  17795. * @param a The first submesh
  17796. * @param b The second submesh
  17797. * @returns The result of the comparison
  17798. */
  17799. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17800. // Then distance to camera
  17801. if (a._distanceToCamera < b._distanceToCamera) {
  17802. return 1;
  17803. }
  17804. if (a._distanceToCamera > b._distanceToCamera) {
  17805. return -1;
  17806. }
  17807. return 0;
  17808. };
  17809. /**
  17810. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17811. * are rendered front to back (prevent overdraw).
  17812. *
  17813. * @param a The first submesh
  17814. * @param b The second submesh
  17815. * @returns The result of the comparison
  17816. */
  17817. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17818. // Then distance to camera
  17819. if (a._distanceToCamera < b._distanceToCamera) {
  17820. return -1;
  17821. }
  17822. if (a._distanceToCamera > b._distanceToCamera) {
  17823. return 1;
  17824. }
  17825. return 0;
  17826. };
  17827. /**
  17828. * Resets the different lists of submeshes to prepare a new frame.
  17829. */
  17830. RenderingGroup.prototype.prepare = function () {
  17831. this._opaqueSubMeshes.reset();
  17832. this._transparentSubMeshes.reset();
  17833. this._alphaTestSubMeshes.reset();
  17834. this._depthOnlySubMeshes.reset();
  17835. this._particleSystems.reset();
  17836. this._spriteManagers.reset();
  17837. this._edgesRenderers.reset();
  17838. };
  17839. RenderingGroup.prototype.dispose = function () {
  17840. this._opaqueSubMeshes.dispose();
  17841. this._transparentSubMeshes.dispose();
  17842. this._alphaTestSubMeshes.dispose();
  17843. this._depthOnlySubMeshes.dispose();
  17844. this._particleSystems.dispose();
  17845. this._spriteManagers.dispose();
  17846. this._edgesRenderers.dispose();
  17847. };
  17848. /**
  17849. * Inserts the submesh in its correct queue depending on its material.
  17850. * @param subMesh The submesh to dispatch
  17851. */
  17852. RenderingGroup.prototype.dispatch = function (subMesh) {
  17853. var material = subMesh.getMaterial();
  17854. var mesh = subMesh.getMesh();
  17855. if (!material) {
  17856. return;
  17857. }
  17858. if (material.needAlphaBlendingForMesh(mesh)) {
  17859. this._transparentSubMeshes.push(subMesh);
  17860. }
  17861. else if (material.needAlphaTesting()) {
  17862. if (material.needDepthPrePass) {
  17863. this._depthOnlySubMeshes.push(subMesh);
  17864. }
  17865. this._alphaTestSubMeshes.push(subMesh);
  17866. }
  17867. else {
  17868. if (material.needDepthPrePass) {
  17869. this._depthOnlySubMeshes.push(subMesh);
  17870. }
  17871. this._opaqueSubMeshes.push(subMesh); // Opaque
  17872. }
  17873. if (mesh._edgesRenderer) {
  17874. this._edgesRenderers.push(mesh._edgesRenderer);
  17875. }
  17876. };
  17877. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17878. this._spriteManagers.push(spriteManager);
  17879. };
  17880. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17881. this._particleSystems.push(particleSystem);
  17882. };
  17883. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17884. if (this._particleSystems.length === 0) {
  17885. return;
  17886. }
  17887. // Particles
  17888. var activeCamera = this._scene.activeCamera;
  17889. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17890. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17891. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17892. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17893. continue;
  17894. }
  17895. var emitter = particleSystem.emitter;
  17896. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17897. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17898. }
  17899. }
  17900. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17901. };
  17902. RenderingGroup.prototype._renderSprites = function () {
  17903. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17904. return;
  17905. }
  17906. // Sprites
  17907. var activeCamera = this._scene.activeCamera;
  17908. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17909. for (var id = 0; id < this._spriteManagers.length; id++) {
  17910. var spriteManager = this._spriteManagers.data[id];
  17911. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17912. spriteManager.render();
  17913. }
  17914. }
  17915. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17916. };
  17917. return RenderingGroup;
  17918. }());
  17919. BABYLON.RenderingGroup = RenderingGroup;
  17920. })(BABYLON || (BABYLON = {}));
  17921. //# sourceMappingURL=babylon.renderingGroup.js.map
  17922. var BABYLON;
  17923. (function (BABYLON) {
  17924. var ClickInfo = /** @class */ (function () {
  17925. function ClickInfo() {
  17926. this._singleClick = false;
  17927. this._doubleClick = false;
  17928. this._hasSwiped = false;
  17929. this._ignore = false;
  17930. }
  17931. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17932. get: function () {
  17933. return this._singleClick;
  17934. },
  17935. set: function (b) {
  17936. this._singleClick = b;
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17942. get: function () {
  17943. return this._doubleClick;
  17944. },
  17945. set: function (b) {
  17946. this._doubleClick = b;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17952. get: function () {
  17953. return this._hasSwiped;
  17954. },
  17955. set: function (b) {
  17956. this._hasSwiped = b;
  17957. },
  17958. enumerable: true,
  17959. configurable: true
  17960. });
  17961. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17962. get: function () {
  17963. return this._ignore;
  17964. },
  17965. set: function (b) {
  17966. this._ignore = b;
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. return ClickInfo;
  17972. }());
  17973. /**
  17974. * This class is used by the onRenderingGroupObservable
  17975. */
  17976. var RenderingGroupInfo = /** @class */ (function () {
  17977. function RenderingGroupInfo() {
  17978. }
  17979. /**
  17980. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17981. * This stage will be fired no matter what
  17982. */
  17983. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17984. /**
  17985. * Called before opaque object are rendered.
  17986. * This stage will be fired only if there's 3D Opaque content to render
  17987. */
  17988. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17989. /**
  17990. * Called after the opaque objects are rendered and before the transparent ones
  17991. * This stage will be fired only if there's 3D transparent content to render
  17992. */
  17993. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17994. /**
  17995. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17996. * This stage will be fired no matter what
  17997. */
  17998. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17999. return RenderingGroupInfo;
  18000. }());
  18001. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  18002. /**
  18003. * Represents a scene to be rendered by the engine.
  18004. * @see http://doc.babylonjs.com/page.php?p=21911
  18005. */
  18006. var Scene = /** @class */ (function () {
  18007. /**
  18008. * @constructor
  18009. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  18010. */
  18011. function Scene(engine) {
  18012. // Members
  18013. this.autoClear = true;
  18014. this.autoClearDepthAndStencil = true;
  18015. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  18016. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18017. this.forceWireframe = false;
  18018. this._forcePointsCloud = false;
  18019. this.forceShowBoundingBoxes = false;
  18020. this.animationsEnabled = true;
  18021. this.useConstantAnimationDeltaTime = false;
  18022. this.constantlyUpdateMeshUnderPointer = false;
  18023. this.hoverCursor = "pointer";
  18024. this.defaultCursor = "";
  18025. /**
  18026. * This is used to call preventDefault() on pointer down
  18027. * in order to block unwanted artifacts like system double clicks
  18028. */
  18029. this.preventDefaultOnPointerDown = true;
  18030. // Metadata
  18031. this.metadata = null;
  18032. /**
  18033. * An event triggered when the scene is disposed.
  18034. * @type {BABYLON.Observable}
  18035. */
  18036. this.onDisposeObservable = new BABYLON.Observable();
  18037. /**
  18038. * An event triggered before rendering the scene (right after animations and physics)
  18039. * @type {BABYLON.Observable}
  18040. */
  18041. this.onBeforeRenderObservable = new BABYLON.Observable();
  18042. /**
  18043. * An event triggered after rendering the scene
  18044. * @type {BABYLON.Observable}
  18045. */
  18046. this.onAfterRenderObservable = new BABYLON.Observable();
  18047. /**
  18048. * An event triggered before animating the scene
  18049. * @type {BABYLON.Observable}
  18050. */
  18051. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  18052. /**
  18053. * An event triggered after animations processing
  18054. * @type {BABYLON.Observable}
  18055. */
  18056. this.onAfterAnimationsObservable = new BABYLON.Observable();
  18057. /**
  18058. * An event triggered before draw calls are ready to be sent
  18059. * @type {BABYLON.Observable}
  18060. */
  18061. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  18062. /**
  18063. * An event triggered after draw calls have been sent
  18064. * @type {BABYLON.Observable}
  18065. */
  18066. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  18067. /**
  18068. * An event triggered when physic simulation is about to be run
  18069. * @type {BABYLON.Observable}
  18070. */
  18071. this.onBeforePhysicsObservable = new BABYLON.Observable();
  18072. /**
  18073. * An event triggered when physic simulation has been done
  18074. * @type {BABYLON.Observable}
  18075. */
  18076. this.onAfterPhysicsObservable = new BABYLON.Observable();
  18077. /**
  18078. * An event triggered when the scene is ready
  18079. * @type {BABYLON.Observable}
  18080. */
  18081. this.onReadyObservable = new BABYLON.Observable();
  18082. /**
  18083. * An event triggered before rendering a camera
  18084. * @type {BABYLON.Observable}
  18085. */
  18086. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  18087. /**
  18088. * An event triggered after rendering a camera
  18089. * @type {BABYLON.Observable}
  18090. */
  18091. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  18092. /**
  18093. * An event triggered when active meshes evaluation is about to start
  18094. * @type {BABYLON.Observable}
  18095. */
  18096. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18097. /**
  18098. * An event triggered when active meshes evaluation is done
  18099. * @type {BABYLON.Observable}
  18100. */
  18101. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18102. /**
  18103. * An event triggered when particles rendering is about to start
  18104. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18105. * @type {BABYLON.Observable}
  18106. */
  18107. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  18108. /**
  18109. * An event triggered when particles rendering is done
  18110. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18111. * @type {BABYLON.Observable}
  18112. */
  18113. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  18114. /**
  18115. * An event triggered when sprites rendering is about to start
  18116. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18117. * @type {BABYLON.Observable}
  18118. */
  18119. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  18120. /**
  18121. * An event triggered when sprites rendering is done
  18122. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18123. * @type {BABYLON.Observable}
  18124. */
  18125. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  18126. /**
  18127. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  18128. * @type {BABYLON.Observable}
  18129. */
  18130. this.onDataLoadedObservable = new BABYLON.Observable();
  18131. /**
  18132. * An event triggered when a camera is created
  18133. * @type {BABYLON.Observable}
  18134. */
  18135. this.onNewCameraAddedObservable = new BABYLON.Observable();
  18136. /**
  18137. * An event triggered when a camera is removed
  18138. * @type {BABYLON.Observable}
  18139. */
  18140. this.onCameraRemovedObservable = new BABYLON.Observable();
  18141. /**
  18142. * An event triggered when a light is created
  18143. * @type {BABYLON.Observable}
  18144. */
  18145. this.onNewLightAddedObservable = new BABYLON.Observable();
  18146. /**
  18147. * An event triggered when a light is removed
  18148. * @type {BABYLON.Observable}
  18149. */
  18150. this.onLightRemovedObservable = new BABYLON.Observable();
  18151. /**
  18152. * An event triggered when a geometry is created
  18153. * @type {BABYLON.Observable}
  18154. */
  18155. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  18156. /**
  18157. * An event triggered when a geometry is removed
  18158. * @type {BABYLON.Observable}
  18159. */
  18160. this.onGeometryRemovedObservable = new BABYLON.Observable();
  18161. /**
  18162. * An event triggered when a transform node is created
  18163. * @type {BABYLON.Observable}
  18164. */
  18165. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18166. /**
  18167. * An event triggered when a transform node is removed
  18168. * @type {BABYLON.Observable}
  18169. */
  18170. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18171. /**
  18172. * An event triggered when a mesh is created
  18173. * @type {BABYLON.Observable}
  18174. */
  18175. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18176. /**
  18177. * An event triggered when a mesh is removed
  18178. * @type {BABYLON.Observable}
  18179. */
  18180. this.onMeshRemovedObservable = new BABYLON.Observable();
  18181. /**
  18182. * An event triggered when render targets are about to be rendered
  18183. * Can happen multiple times per frame.
  18184. * @type {BABYLON.Observable}
  18185. */
  18186. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18187. /**
  18188. * An event triggered when render targets were rendered.
  18189. * Can happen multiple times per frame.
  18190. * @type {BABYLON.Observable}
  18191. */
  18192. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18193. /**
  18194. * An event triggered before calculating deterministic simulation step
  18195. * @type {BABYLON.Observable}
  18196. */
  18197. this.onBeforeStepObservable = new BABYLON.Observable();
  18198. /**
  18199. * An event triggered after calculating deterministic simulation step
  18200. * @type {BABYLON.Observable}
  18201. */
  18202. this.onAfterStepObservable = new BABYLON.Observable();
  18203. /**
  18204. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18205. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18206. * 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)
  18207. */
  18208. this.onRenderingGroupObservable = new BABYLON.Observable();
  18209. // Animations
  18210. this.animations = [];
  18211. /**
  18212. * 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).
  18213. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18214. */
  18215. this.onPrePointerObservable = new BABYLON.Observable();
  18216. /**
  18217. * Observable event triggered each time an input event is received from the rendering canvas
  18218. */
  18219. this.onPointerObservable = new BABYLON.Observable();
  18220. this._meshPickProceed = false;
  18221. this._currentPickResult = null;
  18222. this._previousPickResult = null;
  18223. this._totalPointersPressed = 0;
  18224. this._doubleClickOccured = false;
  18225. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18226. this.cameraToUseForPointers = null;
  18227. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18228. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18229. this._startingPointerTime = 0;
  18230. this._previousStartingPointerTime = 0;
  18231. // Deterministic lockstep
  18232. this._timeAccumulator = 0;
  18233. this._currentStepId = 0;
  18234. this._currentInternalStep = 0;
  18235. // Keyboard
  18236. /**
  18237. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18238. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18239. */
  18240. this.onPreKeyboardObservable = new BABYLON.Observable();
  18241. /**
  18242. * Observable event triggered each time an keyboard event is received from the hosting window
  18243. */
  18244. this.onKeyboardObservable = new BABYLON.Observable();
  18245. // Coordinate system
  18246. /**
  18247. * use right-handed coordinate system on this scene.
  18248. * @type {boolean}
  18249. */
  18250. this._useRightHandedSystem = false;
  18251. // Fog
  18252. this._fogEnabled = true;
  18253. this._fogMode = Scene.FOGMODE_NONE;
  18254. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18255. this.fogDensity = 0.1;
  18256. this.fogStart = 0;
  18257. this.fogEnd = 1000.0;
  18258. // Lights
  18259. /**
  18260. * is shadow enabled on this scene.
  18261. * @type {boolean}
  18262. */
  18263. this._shadowsEnabled = true;
  18264. /**
  18265. * is light enabled on this scene.
  18266. * @type {boolean}
  18267. */
  18268. this._lightsEnabled = true;
  18269. /**
  18270. * All of the lights added to this scene.
  18271. * @see BABYLON.Light
  18272. * @type {BABYLON.Light[]}
  18273. */
  18274. this.lights = new Array();
  18275. // Cameras
  18276. /** All of the cameras added to this scene. */
  18277. this.cameras = new Array();
  18278. /** All of the active cameras added to this scene. */
  18279. this.activeCameras = new Array();
  18280. // Meshes
  18281. /**
  18282. * All of the tranform nodes added to this scene.
  18283. * @see BABYLON.TransformNode
  18284. * @type {BABYLON.TransformNode[]}
  18285. */
  18286. this.transformNodes = new Array();
  18287. /**
  18288. * All of the (abstract) meshes added to this scene.
  18289. * @see BABYLON.AbstractMesh
  18290. * @type {BABYLON.AbstractMesh[]}
  18291. */
  18292. this.meshes = new Array();
  18293. // Geometries
  18294. this._geometries = new Array();
  18295. this.materials = new Array();
  18296. this.multiMaterials = new Array();
  18297. // Textures
  18298. this._texturesEnabled = true;
  18299. this.textures = new Array();
  18300. // Particles
  18301. this.particlesEnabled = true;
  18302. this.particleSystems = new Array();
  18303. // Sprites
  18304. this.spritesEnabled = true;
  18305. this.spriteManagers = new Array();
  18306. // Layers
  18307. this.layers = new Array();
  18308. this.highlightLayers = new Array();
  18309. // Skeletons
  18310. this._skeletonsEnabled = true;
  18311. this.skeletons = new Array();
  18312. // Morph targets
  18313. this.morphTargetManagers = new Array();
  18314. // Lens flares
  18315. this.lensFlaresEnabled = true;
  18316. this.lensFlareSystems = new Array();
  18317. // Collisions
  18318. this.collisionsEnabled = true;
  18319. /** Defines the gravity applied to this scene */
  18320. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18321. // Postprocesses
  18322. this.postProcesses = new Array();
  18323. this.postProcessesEnabled = true;
  18324. // Customs render targets
  18325. this.renderTargetsEnabled = true;
  18326. this.dumpNextRenderTargets = false;
  18327. this.customRenderTargets = new Array();
  18328. // Imported meshes
  18329. this.importedMeshesFiles = new Array();
  18330. // Probes
  18331. this.probesEnabled = true;
  18332. this.reflectionProbes = new Array();
  18333. this._actionManagers = new Array();
  18334. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18335. // Procedural textures
  18336. this.proceduralTexturesEnabled = true;
  18337. this._proceduralTextures = new Array();
  18338. this.soundTracks = new Array();
  18339. this._audioEnabled = true;
  18340. this._headphone = false;
  18341. // Performance counters
  18342. this._totalVertices = new BABYLON.PerfCounter();
  18343. this._activeIndices = new BABYLON.PerfCounter();
  18344. this._activeParticles = new BABYLON.PerfCounter();
  18345. this._activeBones = new BABYLON.PerfCounter();
  18346. this._animationTime = 0;
  18347. this.animationTimeScale = 1;
  18348. this._renderId = 0;
  18349. this._executeWhenReadyTimeoutId = -1;
  18350. this._intermediateRendering = false;
  18351. this._viewUpdateFlag = -1;
  18352. this._projectionUpdateFlag = -1;
  18353. this._alternateViewUpdateFlag = -1;
  18354. this._alternateProjectionUpdateFlag = -1;
  18355. this._toBeDisposed = new BABYLON.SmartArray(256);
  18356. this._pendingData = new Array();
  18357. this._isDisposed = false;
  18358. this._activeMeshes = new BABYLON.SmartArray(256);
  18359. this._processedMaterials = new BABYLON.SmartArray(256);
  18360. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18361. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18362. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18363. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18364. this._activeAnimatables = new Array();
  18365. this._transformMatrix = BABYLON.Matrix.Zero();
  18366. this._useAlternateCameraConfiguration = false;
  18367. this._alternateRendering = false;
  18368. this.requireLightSorting = false;
  18369. this._activeMeshesFrozen = false;
  18370. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18371. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18372. this._engine.scenes.push(this);
  18373. this._uid = null;
  18374. this._renderingManager = new BABYLON.RenderingManager(this);
  18375. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18376. if (BABYLON.OutlineRenderer) {
  18377. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18378. }
  18379. if (BABYLON.Tools.IsWindowObjectExist()) {
  18380. this.attachControl();
  18381. }
  18382. //simplification queue
  18383. if (BABYLON.SimplificationQueue) {
  18384. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18385. }
  18386. //collision coordinator initialization. For now legacy per default.
  18387. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18388. // Uniform Buffer
  18389. this._createUbo();
  18390. // Default Image processing definition.
  18391. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18392. }
  18393. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18394. /** The fog is deactivated */
  18395. get: function () {
  18396. return Scene._FOGMODE_NONE;
  18397. },
  18398. enumerable: true,
  18399. configurable: true
  18400. });
  18401. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18402. /** The fog density is following an exponential function */
  18403. get: function () {
  18404. return Scene._FOGMODE_EXP;
  18405. },
  18406. enumerable: true,
  18407. configurable: true
  18408. });
  18409. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18410. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18411. get: function () {
  18412. return Scene._FOGMODE_EXP2;
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18418. /** The fog density is following a linear function. */
  18419. get: function () {
  18420. return Scene._FOGMODE_LINEAR;
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18426. /**
  18427. * Texture used in all pbr material as the reflection texture.
  18428. * As in the majority of the scene they are the same (exception for multi room and so on),
  18429. * this is easier to reference from here than from all the materials.
  18430. */
  18431. get: function () {
  18432. return this._environmentTexture;
  18433. },
  18434. /**
  18435. * Texture used in all pbr material as the reflection texture.
  18436. * As in the majority of the scene they are the same (exception for multi room and so on),
  18437. * this is easier to set here than in all the materials.
  18438. */
  18439. set: function (value) {
  18440. if (this._environmentTexture === value) {
  18441. return;
  18442. }
  18443. this._environmentTexture = value;
  18444. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18445. },
  18446. enumerable: true,
  18447. configurable: true
  18448. });
  18449. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18450. /**
  18451. * Default image processing configuration used either in the rendering
  18452. * Forward main pass or through the imageProcessingPostProcess if present.
  18453. * As in the majority of the scene they are the same (exception for multi camera),
  18454. * this is easier to reference from here than from all the materials and post process.
  18455. *
  18456. * No setter as we it is a shared configuration, you can set the values instead.
  18457. */
  18458. get: function () {
  18459. return this._imageProcessingConfiguration;
  18460. },
  18461. enumerable: true,
  18462. configurable: true
  18463. });
  18464. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18465. get: function () {
  18466. return this._forcePointsCloud;
  18467. },
  18468. set: function (value) {
  18469. if (this._forcePointsCloud === value) {
  18470. return;
  18471. }
  18472. this._forcePointsCloud = value;
  18473. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18474. },
  18475. enumerable: true,
  18476. configurable: true
  18477. });
  18478. Object.defineProperty(Scene.prototype, "onDispose", {
  18479. /** A function to be executed when this scene is disposed. */
  18480. set: function (callback) {
  18481. if (this._onDisposeObserver) {
  18482. this.onDisposeObservable.remove(this._onDisposeObserver);
  18483. }
  18484. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18485. },
  18486. enumerable: true,
  18487. configurable: true
  18488. });
  18489. Object.defineProperty(Scene.prototype, "beforeRender", {
  18490. /** A function to be executed before rendering this scene */
  18491. set: function (callback) {
  18492. if (this._onBeforeRenderObserver) {
  18493. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18494. }
  18495. if (callback) {
  18496. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18497. }
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. Object.defineProperty(Scene.prototype, "afterRender", {
  18503. /** A function to be executed after rendering this scene */
  18504. set: function (callback) {
  18505. if (this._onAfterRenderObserver) {
  18506. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18507. }
  18508. if (callback) {
  18509. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18510. }
  18511. },
  18512. enumerable: true,
  18513. configurable: true
  18514. });
  18515. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18516. set: function (callback) {
  18517. if (this._onBeforeCameraRenderObserver) {
  18518. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18519. }
  18520. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18521. },
  18522. enumerable: true,
  18523. configurable: true
  18524. });
  18525. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18526. set: function (callback) {
  18527. if (this._onAfterCameraRenderObserver) {
  18528. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18529. }
  18530. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18531. },
  18532. enumerable: true,
  18533. configurable: true
  18534. });
  18535. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18536. get: function () {
  18537. if (!this._gamepadManager) {
  18538. this._gamepadManager = new BABYLON.GamepadManager(this);
  18539. }
  18540. return this._gamepadManager;
  18541. },
  18542. enumerable: true,
  18543. configurable: true
  18544. });
  18545. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18546. get: function () {
  18547. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18548. },
  18549. enumerable: true,
  18550. configurable: true
  18551. });
  18552. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18553. get: function () {
  18554. return this._useRightHandedSystem;
  18555. },
  18556. set: function (value) {
  18557. if (this._useRightHandedSystem === value) {
  18558. return;
  18559. }
  18560. this._useRightHandedSystem = value;
  18561. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Scene.prototype.setStepId = function (newStepId) {
  18567. this._currentStepId = newStepId;
  18568. };
  18569. ;
  18570. Scene.prototype.getStepId = function () {
  18571. return this._currentStepId;
  18572. };
  18573. ;
  18574. Scene.prototype.getInternalStep = function () {
  18575. return this._currentInternalStep;
  18576. };
  18577. ;
  18578. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18579. get: function () {
  18580. return this._fogEnabled;
  18581. },
  18582. /**
  18583. * is fog enabled on this scene.
  18584. */
  18585. set: function (value) {
  18586. if (this._fogEnabled === value) {
  18587. return;
  18588. }
  18589. this._fogEnabled = value;
  18590. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18591. },
  18592. enumerable: true,
  18593. configurable: true
  18594. });
  18595. Object.defineProperty(Scene.prototype, "fogMode", {
  18596. get: function () {
  18597. return this._fogMode;
  18598. },
  18599. set: function (value) {
  18600. if (this._fogMode === value) {
  18601. return;
  18602. }
  18603. this._fogMode = value;
  18604. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18610. get: function () {
  18611. return this._shadowsEnabled;
  18612. },
  18613. set: function (value) {
  18614. if (this._shadowsEnabled === value) {
  18615. return;
  18616. }
  18617. this._shadowsEnabled = value;
  18618. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18619. },
  18620. enumerable: true,
  18621. configurable: true
  18622. });
  18623. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18624. get: function () {
  18625. return this._lightsEnabled;
  18626. },
  18627. set: function (value) {
  18628. if (this._lightsEnabled === value) {
  18629. return;
  18630. }
  18631. this._lightsEnabled = value;
  18632. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18633. },
  18634. enumerable: true,
  18635. configurable: true
  18636. });
  18637. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18638. /** The default material used on meshes when no material is affected */
  18639. get: function () {
  18640. if (!this._defaultMaterial) {
  18641. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18642. }
  18643. return this._defaultMaterial;
  18644. },
  18645. /** The default material used on meshes when no material is affected */
  18646. set: function (value) {
  18647. this._defaultMaterial = value;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18653. get: function () {
  18654. return this._texturesEnabled;
  18655. },
  18656. set: function (value) {
  18657. if (this._texturesEnabled === value) {
  18658. return;
  18659. }
  18660. this._texturesEnabled = value;
  18661. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18662. },
  18663. enumerable: true,
  18664. configurable: true
  18665. });
  18666. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18667. get: function () {
  18668. return this._skeletonsEnabled;
  18669. },
  18670. set: function (value) {
  18671. if (this._skeletonsEnabled === value) {
  18672. return;
  18673. }
  18674. this._skeletonsEnabled = value;
  18675. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18676. },
  18677. enumerable: true,
  18678. configurable: true
  18679. });
  18680. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18681. get: function () {
  18682. if (!this._postProcessRenderPipelineManager) {
  18683. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18684. }
  18685. return this._postProcessRenderPipelineManager;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18691. get: function () {
  18692. if (!this._mainSoundTrack) {
  18693. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18694. }
  18695. return this._mainSoundTrack;
  18696. },
  18697. enumerable: true,
  18698. configurable: true
  18699. });
  18700. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18701. get: function () {
  18702. return this._alternateRendering;
  18703. },
  18704. enumerable: true,
  18705. configurable: true
  18706. });
  18707. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18708. get: function () {
  18709. return this._frustumPlanes;
  18710. },
  18711. enumerable: true,
  18712. configurable: true
  18713. });
  18714. Object.defineProperty(Scene.prototype, "debugLayer", {
  18715. // Properties
  18716. get: function () {
  18717. if (!this._debugLayer) {
  18718. this._debugLayer = new BABYLON.DebugLayer(this);
  18719. }
  18720. return this._debugLayer;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18726. get: function () {
  18727. return this._workerCollisions;
  18728. },
  18729. set: function (enabled) {
  18730. if (!BABYLON.CollisionCoordinatorLegacy) {
  18731. return;
  18732. }
  18733. enabled = (enabled && !!Worker);
  18734. this._workerCollisions = enabled;
  18735. if (this.collisionCoordinator) {
  18736. this.collisionCoordinator.destroy();
  18737. }
  18738. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18739. this.collisionCoordinator.init(this);
  18740. },
  18741. enumerable: true,
  18742. configurable: true
  18743. });
  18744. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18745. get: function () {
  18746. return this._selectionOctree;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18752. /**
  18753. * The mesh that is currently under the pointer.
  18754. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18755. */
  18756. get: function () {
  18757. return this._pointerOverMesh;
  18758. },
  18759. enumerable: true,
  18760. configurable: true
  18761. });
  18762. Object.defineProperty(Scene.prototype, "pointerX", {
  18763. /**
  18764. * Current on-screen X position of the pointer
  18765. * @return {number} X position of the pointer
  18766. */
  18767. get: function () {
  18768. return this._pointerX;
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. Object.defineProperty(Scene.prototype, "pointerY", {
  18774. /**
  18775. * Current on-screen Y position of the pointer
  18776. * @return {number} Y position of the pointer
  18777. */
  18778. get: function () {
  18779. return this._pointerY;
  18780. },
  18781. enumerable: true,
  18782. configurable: true
  18783. });
  18784. Scene.prototype.getCachedMaterial = function () {
  18785. return this._cachedMaterial;
  18786. };
  18787. Scene.prototype.getCachedEffect = function () {
  18788. return this._cachedEffect;
  18789. };
  18790. Scene.prototype.getCachedVisibility = function () {
  18791. return this._cachedVisibility;
  18792. };
  18793. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18794. if (visibility === void 0) { visibility = 1; }
  18795. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18796. };
  18797. Scene.prototype.getBoundingBoxRenderer = function () {
  18798. if (!this._boundingBoxRenderer) {
  18799. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18800. }
  18801. return this._boundingBoxRenderer;
  18802. };
  18803. Scene.prototype.getOutlineRenderer = function () {
  18804. return this._outlineRenderer;
  18805. };
  18806. Scene.prototype.getEngine = function () {
  18807. return this._engine;
  18808. };
  18809. Scene.prototype.getTotalVertices = function () {
  18810. return this._totalVertices.current;
  18811. };
  18812. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18813. get: function () {
  18814. return this._totalVertices;
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Scene.prototype.getActiveIndices = function () {
  18820. return this._activeIndices.current;
  18821. };
  18822. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18823. get: function () {
  18824. return this._activeIndices;
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. Scene.prototype.getActiveParticles = function () {
  18830. return this._activeParticles.current;
  18831. };
  18832. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18833. get: function () {
  18834. return this._activeParticles;
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Scene.prototype.getActiveBones = function () {
  18840. return this._activeBones.current;
  18841. };
  18842. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18843. get: function () {
  18844. return this._activeBones;
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. // Stats
  18850. Scene.prototype.getInterFramePerfCounter = function () {
  18851. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18852. return 0;
  18853. };
  18854. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18855. get: function () {
  18856. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18857. return null;
  18858. },
  18859. enumerable: true,
  18860. configurable: true
  18861. });
  18862. Scene.prototype.getLastFrameDuration = function () {
  18863. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18864. return 0;
  18865. };
  18866. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18867. get: function () {
  18868. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18869. return null;
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18875. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18876. return 0;
  18877. };
  18878. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18879. get: function () {
  18880. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18881. return null;
  18882. },
  18883. enumerable: true,
  18884. configurable: true
  18885. });
  18886. Scene.prototype.getActiveMeshes = function () {
  18887. return this._activeMeshes;
  18888. };
  18889. Scene.prototype.getRenderTargetsDuration = function () {
  18890. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18891. return 0;
  18892. };
  18893. Scene.prototype.getRenderDuration = function () {
  18894. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18895. return 0;
  18896. };
  18897. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18898. get: function () {
  18899. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18900. return null;
  18901. },
  18902. enumerable: true,
  18903. configurable: true
  18904. });
  18905. Scene.prototype.getParticlesDuration = function () {
  18906. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18907. return 0;
  18908. };
  18909. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18910. get: function () {
  18911. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18912. return null;
  18913. },
  18914. enumerable: true,
  18915. configurable: true
  18916. });
  18917. Scene.prototype.getSpritesDuration = function () {
  18918. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18919. return 0;
  18920. };
  18921. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18922. get: function () {
  18923. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18924. return null;
  18925. },
  18926. enumerable: true,
  18927. configurable: true
  18928. });
  18929. Scene.prototype.getAnimationRatio = function () {
  18930. return this._animationRatio;
  18931. };
  18932. Scene.prototype.getRenderId = function () {
  18933. return this._renderId;
  18934. };
  18935. Scene.prototype.incrementRenderId = function () {
  18936. this._renderId++;
  18937. };
  18938. Scene.prototype._updatePointerPosition = function (evt) {
  18939. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18940. if (!canvasRect) {
  18941. return;
  18942. }
  18943. this._pointerX = evt.clientX - canvasRect.left;
  18944. this._pointerY = evt.clientY - canvasRect.top;
  18945. this._unTranslatedPointerX = this._pointerX;
  18946. this._unTranslatedPointerY = this._pointerY;
  18947. };
  18948. Scene.prototype._createUbo = function () {
  18949. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18950. this._sceneUbo.addUniform("viewProjection", 16);
  18951. this._sceneUbo.addUniform("view", 16);
  18952. };
  18953. Scene.prototype._createAlternateUbo = function () {
  18954. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18955. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18956. this._alternateSceneUbo.addUniform("view", 16);
  18957. };
  18958. // Pointers handling
  18959. /**
  18960. * Use this method to simulate a pointer move on a mesh
  18961. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18962. */
  18963. Scene.prototype.simulatePointerMove = function (pickResult) {
  18964. var evt = new PointerEvent("pointermove");
  18965. return this._processPointerMove(pickResult, evt);
  18966. };
  18967. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18968. var canvas = this._engine.getRenderingCanvas();
  18969. if (!canvas) {
  18970. return this;
  18971. }
  18972. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18973. this.setPointerOverSprite(null);
  18974. this.setPointerOverMesh(pickResult.pickedMesh);
  18975. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18976. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18977. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18978. }
  18979. else {
  18980. canvas.style.cursor = this.hoverCursor;
  18981. }
  18982. }
  18983. else {
  18984. canvas.style.cursor = this.defaultCursor;
  18985. }
  18986. }
  18987. else {
  18988. this.setPointerOverMesh(null);
  18989. // Sprites
  18990. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18991. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18992. this.setPointerOverSprite(pickResult.pickedSprite);
  18993. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18994. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18995. }
  18996. else {
  18997. canvas.style.cursor = this.hoverCursor;
  18998. }
  18999. }
  19000. else {
  19001. this.setPointerOverSprite(null);
  19002. // Restore pointer
  19003. canvas.style.cursor = this.defaultCursor;
  19004. }
  19005. }
  19006. if (pickResult) {
  19007. if (this.onPointerMove) {
  19008. this.onPointerMove(evt, pickResult);
  19009. }
  19010. if (this.onPointerObservable.hasObservers()) {
  19011. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19012. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19013. this.onPointerObservable.notifyObservers(pi, type);
  19014. }
  19015. }
  19016. return this;
  19017. };
  19018. /**
  19019. * Use this method to simulate a pointer down on a mesh
  19020. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19021. */
  19022. Scene.prototype.simulatePointerDown = function (pickResult) {
  19023. var evt = new PointerEvent("pointerdown");
  19024. return this._processPointerDown(pickResult, evt);
  19025. };
  19026. Scene.prototype._processPointerDown = function (pickResult, evt) {
  19027. var _this = this;
  19028. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19029. this._pickedDownMesh = pickResult.pickedMesh;
  19030. var actionManager = pickResult.pickedMesh.actionManager;
  19031. if (actionManager) {
  19032. if (actionManager.hasPickTriggers) {
  19033. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19034. switch (evt.button) {
  19035. case 0:
  19036. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19037. break;
  19038. case 1:
  19039. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19040. break;
  19041. case 2:
  19042. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19043. break;
  19044. }
  19045. }
  19046. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19047. window.setTimeout(function () {
  19048. 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);
  19049. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  19050. if (_this._totalPointersPressed !== 0 &&
  19051. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  19052. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  19053. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  19054. _this._startingPointerTime = 0;
  19055. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19056. }
  19057. }
  19058. }, Scene.LongPressDelay);
  19059. }
  19060. }
  19061. }
  19062. if (pickResult) {
  19063. if (this.onPointerDown) {
  19064. this.onPointerDown(evt, pickResult);
  19065. }
  19066. if (this.onPointerObservable.hasObservers()) {
  19067. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19068. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19069. this.onPointerObservable.notifyObservers(pi, type);
  19070. }
  19071. }
  19072. return this;
  19073. };
  19074. /**
  19075. * Use this method to simulate a pointer up on a mesh
  19076. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19077. */
  19078. Scene.prototype.simulatePointerUp = function (pickResult) {
  19079. var evt = new PointerEvent("pointerup");
  19080. var clickInfo = new ClickInfo();
  19081. clickInfo.singleClick = true;
  19082. clickInfo.ignore = true;
  19083. return this._processPointerUp(pickResult, evt, clickInfo);
  19084. };
  19085. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  19086. if (pickResult && pickResult && pickResult.pickedMesh) {
  19087. this._pickedUpMesh = pickResult.pickedMesh;
  19088. if (this._pickedDownMesh === this._pickedUpMesh) {
  19089. if (this.onPointerPick) {
  19090. this.onPointerPick(evt, pickResult);
  19091. }
  19092. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  19093. var type = BABYLON.PointerEventTypes.POINTERPICK;
  19094. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19095. this.onPointerObservable.notifyObservers(pi, type);
  19096. }
  19097. }
  19098. if (pickResult.pickedMesh.actionManager) {
  19099. if (clickInfo.ignore) {
  19100. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19101. }
  19102. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  19103. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19104. }
  19105. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19106. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19107. }
  19108. }
  19109. }
  19110. if (this._pickedDownMesh &&
  19111. this._pickedDownMesh.actionManager &&
  19112. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  19113. this._pickedDownMesh !== this._pickedUpMesh) {
  19114. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  19115. }
  19116. if (this.onPointerUp) {
  19117. this.onPointerUp(evt, pickResult);
  19118. }
  19119. if (this.onPointerObservable.hasObservers()) {
  19120. if (!clickInfo.ignore) {
  19121. if (!clickInfo.hasSwiped) {
  19122. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19123. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19124. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19125. this.onPointerObservable.notifyObservers(pi, type);
  19126. }
  19127. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19128. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19129. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19130. this.onPointerObservable.notifyObservers(pi, type);
  19131. }
  19132. }
  19133. }
  19134. else {
  19135. var type = BABYLON.PointerEventTypes.POINTERUP;
  19136. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19137. this.onPointerObservable.notifyObservers(pi, type);
  19138. }
  19139. }
  19140. return this;
  19141. };
  19142. /**
  19143. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19144. * @param attachUp defines if you want to attach events to pointerup
  19145. * @param attachDown defines if you want to attach events to pointerdown
  19146. * @param attachMove defines if you want to attach events to pointermove
  19147. */
  19148. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19149. var _this = this;
  19150. if (attachUp === void 0) { attachUp = true; }
  19151. if (attachDown === void 0) { attachDown = true; }
  19152. if (attachMove === void 0) { attachMove = true; }
  19153. this._initActionManager = function (act, clickInfo) {
  19154. if (!_this._meshPickProceed) {
  19155. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19156. _this._currentPickResult = pickResult;
  19157. if (pickResult) {
  19158. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  19159. }
  19160. _this._meshPickProceed = true;
  19161. }
  19162. return act;
  19163. };
  19164. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  19165. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19166. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19167. btn !== _this._previousButtonPressed) {
  19168. _this._doubleClickOccured = false;
  19169. clickInfo.singleClick = true;
  19170. clickInfo.ignore = false;
  19171. cb(clickInfo, _this._currentPickResult);
  19172. }
  19173. };
  19174. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19175. var clickInfo = new ClickInfo();
  19176. _this._currentPickResult = null;
  19177. var act = null;
  19178. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19179. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19180. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19181. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19182. act = _this._initActionManager(act, clickInfo);
  19183. if (act)
  19184. checkPicking = act.hasPickTriggers;
  19185. }
  19186. if (checkPicking) {
  19187. var btn = evt.button;
  19188. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19189. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19190. if (!clickInfo.hasSwiped) {
  19191. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19192. if (!checkSingleClickImmediately) {
  19193. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19194. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19195. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19196. act = _this._initActionManager(act, clickInfo);
  19197. if (act)
  19198. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19199. }
  19200. }
  19201. if (checkSingleClickImmediately) {
  19202. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19203. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19204. btn !== _this._previousButtonPressed) {
  19205. clickInfo.singleClick = true;
  19206. cb(clickInfo, _this._currentPickResult);
  19207. }
  19208. }
  19209. else {
  19210. // wait that no double click has been raised during the double click delay
  19211. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19212. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19213. }
  19214. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19215. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19216. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19217. act = _this._initActionManager(act, clickInfo);
  19218. if (act)
  19219. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19220. }
  19221. if (checkDoubleClick) {
  19222. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19223. if (btn === _this._previousButtonPressed &&
  19224. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19225. !_this._doubleClickOccured) {
  19226. // pointer has not moved for 2 clicks, it's a double click
  19227. if (!clickInfo.hasSwiped &&
  19228. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19229. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19230. _this._previousStartingPointerTime = 0;
  19231. _this._doubleClickOccured = true;
  19232. clickInfo.doubleClick = true;
  19233. clickInfo.ignore = false;
  19234. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19235. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19236. }
  19237. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19238. cb(clickInfo, _this._currentPickResult);
  19239. }
  19240. else {
  19241. _this._doubleClickOccured = false;
  19242. _this._previousStartingPointerTime = _this._startingPointerTime;
  19243. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19244. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19245. _this._previousButtonPressed = btn;
  19246. if (Scene.ExclusiveDoubleClickMode) {
  19247. if (_this._previousDelayedSimpleClickTimeout) {
  19248. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19249. }
  19250. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19251. cb(clickInfo, _this._previousPickResult);
  19252. }
  19253. else {
  19254. cb(clickInfo, _this._currentPickResult);
  19255. }
  19256. }
  19257. }
  19258. else {
  19259. _this._doubleClickOccured = false;
  19260. _this._previousStartingPointerTime = _this._startingPointerTime;
  19261. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19262. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19263. _this._previousButtonPressed = btn;
  19264. }
  19265. }
  19266. }
  19267. }
  19268. clickInfo.ignore = true;
  19269. cb(clickInfo, _this._currentPickResult);
  19270. };
  19271. this._spritePredicate = function (sprite) {
  19272. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19273. };
  19274. this._onPointerMove = function (evt) {
  19275. _this._updatePointerPosition(evt);
  19276. // PreObservable support
  19277. if (_this.onPrePointerObservable.hasObservers()) {
  19278. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19279. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19280. _this.onPrePointerObservable.notifyObservers(pi, type);
  19281. if (pi.skipOnPointerObservable) {
  19282. return;
  19283. }
  19284. }
  19285. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19286. return;
  19287. }
  19288. if (!_this.pointerMovePredicate) {
  19289. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19290. }
  19291. // Meshes
  19292. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19293. _this._processPointerMove(pickResult, evt);
  19294. };
  19295. this._onPointerDown = function (evt) {
  19296. _this._totalPointersPressed++;
  19297. _this._pickedDownMesh = null;
  19298. _this._meshPickProceed = false;
  19299. _this._updatePointerPosition(evt);
  19300. if (_this.preventDefaultOnPointerDown && canvas) {
  19301. evt.preventDefault();
  19302. canvas.focus();
  19303. }
  19304. // PreObservable support
  19305. if (_this.onPrePointerObservable.hasObservers()) {
  19306. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19307. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19308. _this.onPrePointerObservable.notifyObservers(pi, type);
  19309. if (pi.skipOnPointerObservable) {
  19310. return;
  19311. }
  19312. }
  19313. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19314. return;
  19315. }
  19316. _this._startingPointerPosition.x = _this._pointerX;
  19317. _this._startingPointerPosition.y = _this._pointerY;
  19318. _this._startingPointerTime = new Date().getTime();
  19319. if (!_this.pointerDownPredicate) {
  19320. _this.pointerDownPredicate = function (mesh) {
  19321. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19322. };
  19323. }
  19324. // Meshes
  19325. _this._pickedDownMesh = null;
  19326. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19327. _this._processPointerDown(pickResult, evt);
  19328. // Sprites
  19329. _this._pickedDownSprite = null;
  19330. if (_this.spriteManagers.length > 0) {
  19331. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19332. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19333. if (pickResult.pickedSprite.actionManager) {
  19334. _this._pickedDownSprite = pickResult.pickedSprite;
  19335. switch (evt.button) {
  19336. case 0:
  19337. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19338. break;
  19339. case 1:
  19340. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19341. break;
  19342. case 2:
  19343. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19344. break;
  19345. }
  19346. if (pickResult.pickedSprite.actionManager) {
  19347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19348. }
  19349. }
  19350. }
  19351. }
  19352. };
  19353. this._onPointerUp = function (evt) {
  19354. if (_this._totalPointersPressed === 0) {
  19355. return; // So we need to test it the pointer down was pressed before.
  19356. }
  19357. _this._totalPointersPressed--;
  19358. _this._pickedUpMesh = null;
  19359. _this._meshPickProceed = false;
  19360. _this._updatePointerPosition(evt);
  19361. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19362. // PreObservable support
  19363. if (_this.onPrePointerObservable.hasObservers()) {
  19364. if (!clickInfo.ignore) {
  19365. if (!clickInfo.hasSwiped) {
  19366. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19367. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19368. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19369. _this.onPrePointerObservable.notifyObservers(pi, type);
  19370. if (pi.skipOnPointerObservable) {
  19371. return;
  19372. }
  19373. }
  19374. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19375. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19376. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19377. _this.onPrePointerObservable.notifyObservers(pi, type);
  19378. if (pi.skipOnPointerObservable) {
  19379. return;
  19380. }
  19381. }
  19382. }
  19383. }
  19384. else {
  19385. var type = BABYLON.PointerEventTypes.POINTERUP;
  19386. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19387. _this.onPrePointerObservable.notifyObservers(pi, type);
  19388. if (pi.skipOnPointerObservable) {
  19389. return;
  19390. }
  19391. }
  19392. }
  19393. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19394. return;
  19395. }
  19396. if (!_this.pointerUpPredicate) {
  19397. _this.pointerUpPredicate = function (mesh) {
  19398. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19399. };
  19400. }
  19401. // Meshes
  19402. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19403. _this._initActionManager(null, clickInfo);
  19404. }
  19405. if (!pickResult) {
  19406. pickResult = _this._currentPickResult;
  19407. }
  19408. _this._processPointerUp(pickResult, evt, clickInfo);
  19409. // Sprites
  19410. if (_this.spriteManagers.length > 0) {
  19411. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19412. if (spritePickResult) {
  19413. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19414. if (spritePickResult.pickedSprite.actionManager) {
  19415. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19416. if (spritePickResult.pickedSprite.actionManager) {
  19417. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19418. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19419. }
  19420. }
  19421. }
  19422. }
  19423. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19424. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19425. }
  19426. }
  19427. }
  19428. _this._previousPickResult = _this._currentPickResult;
  19429. });
  19430. };
  19431. this._onKeyDown = function (evt) {
  19432. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19433. if (_this.onPreKeyboardObservable.hasObservers()) {
  19434. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19435. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19436. if (pi.skipOnPointerObservable) {
  19437. return;
  19438. }
  19439. }
  19440. if (_this.onKeyboardObservable.hasObservers()) {
  19441. var pi = new BABYLON.KeyboardInfo(type, evt);
  19442. _this.onKeyboardObservable.notifyObservers(pi, type);
  19443. }
  19444. if (_this.actionManager) {
  19445. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19446. }
  19447. };
  19448. this._onKeyUp = function (evt) {
  19449. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19450. if (_this.onPreKeyboardObservable.hasObservers()) {
  19451. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19452. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19453. if (pi.skipOnPointerObservable) {
  19454. return;
  19455. }
  19456. }
  19457. if (_this.onKeyboardObservable.hasObservers()) {
  19458. var pi = new BABYLON.KeyboardInfo(type, evt);
  19459. _this.onKeyboardObservable.notifyObservers(pi, type);
  19460. }
  19461. if (_this.actionManager) {
  19462. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19463. }
  19464. };
  19465. var engine = this.getEngine();
  19466. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19467. if (!canvas) {
  19468. return;
  19469. }
  19470. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19471. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19472. });
  19473. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19474. if (!canvas) {
  19475. return;
  19476. }
  19477. canvas.removeEventListener("keydown", _this._onKeyDown);
  19478. canvas.removeEventListener("keyup", _this._onKeyUp);
  19479. });
  19480. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19481. var canvas = this._engine.getRenderingCanvas();
  19482. if (!canvas) {
  19483. return;
  19484. }
  19485. if (attachMove) {
  19486. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19487. // Wheel
  19488. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19489. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19490. }
  19491. if (attachDown) {
  19492. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19493. }
  19494. if (attachUp) {
  19495. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19496. }
  19497. canvas.tabIndex = 1;
  19498. };
  19499. Scene.prototype.detachControl = function () {
  19500. var engine = this.getEngine();
  19501. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19502. var canvas = engine.getRenderingCanvas();
  19503. if (!canvas) {
  19504. return;
  19505. }
  19506. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19507. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19508. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19509. if (this._onCanvasBlurObserver) {
  19510. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19511. }
  19512. if (this._onCanvasFocusObserver) {
  19513. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19514. }
  19515. // Wheel
  19516. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19517. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19518. // Keyboard
  19519. canvas.removeEventListener("keydown", this._onKeyDown);
  19520. canvas.removeEventListener("keyup", this._onKeyUp);
  19521. // Observables
  19522. this.onKeyboardObservable.clear();
  19523. this.onPreKeyboardObservable.clear();
  19524. this.onPointerObservable.clear();
  19525. this.onPrePointerObservable.clear();
  19526. };
  19527. // Ready
  19528. Scene.prototype.isReady = function () {
  19529. if (this._isDisposed) {
  19530. return false;
  19531. }
  19532. if (this._pendingData.length > 0) {
  19533. return false;
  19534. }
  19535. var index;
  19536. // Geometries
  19537. for (index = 0; index < this._geometries.length; index++) {
  19538. var geometry = this._geometries[index];
  19539. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19540. return false;
  19541. }
  19542. }
  19543. // Meshes
  19544. for (index = 0; index < this.meshes.length; index++) {
  19545. var mesh = this.meshes[index];
  19546. if (!mesh.isEnabled()) {
  19547. continue;
  19548. }
  19549. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19550. continue;
  19551. }
  19552. if (!mesh.isReady()) {
  19553. return false;
  19554. }
  19555. var mat = mesh.material;
  19556. if (mat) {
  19557. if (!mat.isReady(mesh)) {
  19558. return false;
  19559. }
  19560. }
  19561. }
  19562. return true;
  19563. };
  19564. Scene.prototype.resetCachedMaterial = function () {
  19565. this._cachedMaterial = null;
  19566. this._cachedEffect = null;
  19567. this._cachedVisibility = null;
  19568. };
  19569. Scene.prototype.registerBeforeRender = function (func) {
  19570. this.onBeforeRenderObservable.add(func);
  19571. };
  19572. Scene.prototype.unregisterBeforeRender = function (func) {
  19573. this.onBeforeRenderObservable.removeCallback(func);
  19574. };
  19575. Scene.prototype.registerAfterRender = function (func) {
  19576. this.onAfterRenderObservable.add(func);
  19577. };
  19578. Scene.prototype.unregisterAfterRender = function (func) {
  19579. this.onAfterRenderObservable.removeCallback(func);
  19580. };
  19581. Scene.prototype._addPendingData = function (data) {
  19582. this._pendingData.push(data);
  19583. };
  19584. Scene.prototype._removePendingData = function (data) {
  19585. var wasLoading = this.isLoading;
  19586. var index = this._pendingData.indexOf(data);
  19587. if (index !== -1) {
  19588. this._pendingData.splice(index, 1);
  19589. }
  19590. if (wasLoading && !this.isLoading) {
  19591. this.onDataLoadedObservable.notifyObservers(this);
  19592. }
  19593. };
  19594. Scene.prototype.getWaitingItemsCount = function () {
  19595. return this._pendingData.length;
  19596. };
  19597. Object.defineProperty(Scene.prototype, "isLoading", {
  19598. get: function () {
  19599. return this._pendingData.length > 0;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. /**
  19605. * Registers a function to be executed when the scene is ready.
  19606. * @param {Function} func - the function to be executed.
  19607. */
  19608. Scene.prototype.executeWhenReady = function (func) {
  19609. var _this = this;
  19610. this.onReadyObservable.add(func);
  19611. if (this._executeWhenReadyTimeoutId !== -1) {
  19612. return;
  19613. }
  19614. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19615. _this._checkIsReady();
  19616. }, 150);
  19617. };
  19618. Scene.prototype._checkIsReady = function () {
  19619. var _this = this;
  19620. if (this.isReady()) {
  19621. this.onReadyObservable.notifyObservers(this);
  19622. this.onReadyObservable.clear();
  19623. this._executeWhenReadyTimeoutId = -1;
  19624. return;
  19625. }
  19626. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19627. _this._checkIsReady();
  19628. }, 150);
  19629. };
  19630. // Animations
  19631. /**
  19632. * Will start the animation sequence of a given target
  19633. * @param target - the target
  19634. * @param {number} from - from which frame should animation start
  19635. * @param {number} to - till which frame should animation run.
  19636. * @param {boolean} [loop] - should the animation loop
  19637. * @param {number} [speedRatio] - the speed in which to run the animation
  19638. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19639. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19640. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19641. * See BABYLON.Animatable
  19642. */
  19643. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19644. if (speedRatio === void 0) { speedRatio = 1.0; }
  19645. if (from > to && speedRatio > 0) {
  19646. speedRatio *= -1;
  19647. }
  19648. this.stopAnimation(target);
  19649. if (!animatable) {
  19650. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19651. }
  19652. // Local animations
  19653. if (target.animations) {
  19654. animatable.appendAnimations(target, target.animations);
  19655. }
  19656. // Children animations
  19657. if (target.getAnimatables) {
  19658. var animatables = target.getAnimatables();
  19659. for (var index = 0; index < animatables.length; index++) {
  19660. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19661. }
  19662. }
  19663. animatable.reset();
  19664. return animatable;
  19665. };
  19666. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19667. if (speedRatio === undefined) {
  19668. speedRatio = 1.0;
  19669. }
  19670. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19671. return animatable;
  19672. };
  19673. Scene.prototype.getAnimatableByTarget = function (target) {
  19674. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19675. if (this._activeAnimatables[index].target === target) {
  19676. return this._activeAnimatables[index];
  19677. }
  19678. }
  19679. return null;
  19680. };
  19681. Object.defineProperty(Scene.prototype, "Animatables", {
  19682. get: function () {
  19683. return this._activeAnimatables;
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. /**
  19689. * Will stop the animation of the given target
  19690. * @param target - the target
  19691. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19692. * @see beginAnimation
  19693. */
  19694. Scene.prototype.stopAnimation = function (target, animationName) {
  19695. var animatable = this.getAnimatableByTarget(target);
  19696. if (animatable) {
  19697. animatable.stop(animationName);
  19698. }
  19699. };
  19700. /**
  19701. * Stops and removes all animations that have been applied to the scene
  19702. */
  19703. Scene.prototype.stopAllAnimations = function () {
  19704. if (this._activeAnimatables) {
  19705. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19706. this._activeAnimatables[i].stop();
  19707. }
  19708. this._activeAnimatables = [];
  19709. }
  19710. };
  19711. Scene.prototype._animate = function () {
  19712. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19713. return;
  19714. }
  19715. // Getting time
  19716. var now = BABYLON.Tools.Now;
  19717. if (!this._animationTimeLast) {
  19718. if (this._pendingData.length > 0) {
  19719. return;
  19720. }
  19721. this._animationTimeLast = now;
  19722. }
  19723. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  19724. this._animationTime += deltaTime;
  19725. this._animationTimeLast = now;
  19726. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19727. this._activeAnimatables[index]._animate(this._animationTime);
  19728. }
  19729. };
  19730. // Matrix
  19731. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19732. this._useAlternateCameraConfiguration = active;
  19733. };
  19734. Scene.prototype.getViewMatrix = function () {
  19735. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19736. };
  19737. Scene.prototype.getProjectionMatrix = function () {
  19738. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19739. };
  19740. Scene.prototype.getTransformMatrix = function () {
  19741. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19742. };
  19743. Scene.prototype.setTransformMatrix = function (view, projection) {
  19744. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19745. return;
  19746. }
  19747. this._viewUpdateFlag = view.updateFlag;
  19748. this._projectionUpdateFlag = projection.updateFlag;
  19749. this._viewMatrix = view;
  19750. this._projectionMatrix = projection;
  19751. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19752. // Update frustum
  19753. if (!this._frustumPlanes) {
  19754. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19755. }
  19756. else {
  19757. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19758. }
  19759. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19760. var otherCamera = this.activeCamera._alternateCamera;
  19761. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19762. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19763. }
  19764. if (this._sceneUbo.useUbo) {
  19765. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19766. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19767. this._sceneUbo.update();
  19768. }
  19769. };
  19770. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19771. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19772. return;
  19773. }
  19774. this._alternateViewUpdateFlag = view.updateFlag;
  19775. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19776. this._alternateViewMatrix = view;
  19777. this._alternateProjectionMatrix = projection;
  19778. if (!this._alternateTransformMatrix) {
  19779. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19780. }
  19781. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19782. if (!this._alternateSceneUbo) {
  19783. this._createAlternateUbo();
  19784. }
  19785. if (this._alternateSceneUbo.useUbo) {
  19786. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19787. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19788. this._alternateSceneUbo.update();
  19789. }
  19790. };
  19791. Scene.prototype.getSceneUniformBuffer = function () {
  19792. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19793. };
  19794. // Methods
  19795. Scene.prototype.getUniqueId = function () {
  19796. var result = Scene._uniqueIdCounter;
  19797. Scene._uniqueIdCounter++;
  19798. return result;
  19799. };
  19800. Scene.prototype.addMesh = function (newMesh) {
  19801. this.meshes.push(newMesh);
  19802. //notify the collision coordinator
  19803. if (this.collisionCoordinator) {
  19804. this.collisionCoordinator.onMeshAdded(newMesh);
  19805. }
  19806. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19807. };
  19808. Scene.prototype.removeMesh = function (toRemove) {
  19809. var index = this.meshes.indexOf(toRemove);
  19810. if (index !== -1) {
  19811. // Remove from the scene if mesh found
  19812. this.meshes.splice(index, 1);
  19813. }
  19814. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19815. return index;
  19816. };
  19817. Scene.prototype.addTransformNode = function (newTransformNode) {
  19818. this.transformNodes.push(newTransformNode);
  19819. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19820. };
  19821. Scene.prototype.removeTransformNode = function (toRemove) {
  19822. var index = this.transformNodes.indexOf(toRemove);
  19823. if (index !== -1) {
  19824. // Remove from the scene if found
  19825. this.transformNodes.splice(index, 1);
  19826. }
  19827. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19828. return index;
  19829. };
  19830. Scene.prototype.removeSkeleton = function (toRemove) {
  19831. var index = this.skeletons.indexOf(toRemove);
  19832. if (index !== -1) {
  19833. // Remove from the scene if found
  19834. this.skeletons.splice(index, 1);
  19835. }
  19836. return index;
  19837. };
  19838. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19839. var index = this.morphTargetManagers.indexOf(toRemove);
  19840. if (index !== -1) {
  19841. // Remove from the scene if found
  19842. this.morphTargetManagers.splice(index, 1);
  19843. }
  19844. return index;
  19845. };
  19846. Scene.prototype.removeLight = function (toRemove) {
  19847. var index = this.lights.indexOf(toRemove);
  19848. if (index !== -1) {
  19849. // Remove from the scene if mesh found
  19850. this.lights.splice(index, 1);
  19851. this.sortLightsByPriority();
  19852. }
  19853. this.onLightRemovedObservable.notifyObservers(toRemove);
  19854. return index;
  19855. };
  19856. Scene.prototype.removeCamera = function (toRemove) {
  19857. var index = this.cameras.indexOf(toRemove);
  19858. if (index !== -1) {
  19859. // Remove from the scene if mesh found
  19860. this.cameras.splice(index, 1);
  19861. }
  19862. // Remove from activeCameras
  19863. var index2 = this.activeCameras.indexOf(toRemove);
  19864. if (index2 !== -1) {
  19865. // Remove from the scene if mesh found
  19866. this.activeCameras.splice(index2, 1);
  19867. }
  19868. // Reset the activeCamera
  19869. if (this.activeCamera === toRemove) {
  19870. if (this.cameras.length > 0) {
  19871. this.activeCamera = this.cameras[0];
  19872. }
  19873. else {
  19874. this.activeCamera = null;
  19875. }
  19876. }
  19877. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19878. return index;
  19879. };
  19880. Scene.prototype.addLight = function (newLight) {
  19881. this.lights.push(newLight);
  19882. this.sortLightsByPriority();
  19883. this.onNewLightAddedObservable.notifyObservers(newLight);
  19884. };
  19885. Scene.prototype.sortLightsByPriority = function () {
  19886. if (this.requireLightSorting) {
  19887. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19888. }
  19889. };
  19890. Scene.prototype.addCamera = function (newCamera) {
  19891. this.cameras.push(newCamera);
  19892. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19893. };
  19894. /**
  19895. * Switch active camera
  19896. * @param {Camera} newCamera - new active camera
  19897. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19898. */
  19899. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19900. if (attachControl === void 0) { attachControl = true; }
  19901. var canvas = this._engine.getRenderingCanvas();
  19902. if (!canvas) {
  19903. return;
  19904. }
  19905. if (this.activeCamera) {
  19906. this.activeCamera.detachControl(canvas);
  19907. }
  19908. this.activeCamera = newCamera;
  19909. if (attachControl) {
  19910. newCamera.attachControl(canvas);
  19911. }
  19912. };
  19913. /**
  19914. * sets the active camera of the scene using its ID
  19915. * @param {string} id - the camera's ID
  19916. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19917. * @see activeCamera
  19918. */
  19919. Scene.prototype.setActiveCameraByID = function (id) {
  19920. var camera = this.getCameraByID(id);
  19921. if (camera) {
  19922. this.activeCamera = camera;
  19923. return camera;
  19924. }
  19925. return null;
  19926. };
  19927. /**
  19928. * sets the active camera of the scene using its name
  19929. * @param {string} name - the camera's name
  19930. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19931. * @see activeCamera
  19932. */
  19933. Scene.prototype.setActiveCameraByName = function (name) {
  19934. var camera = this.getCameraByName(name);
  19935. if (camera) {
  19936. this.activeCamera = camera;
  19937. return camera;
  19938. }
  19939. return null;
  19940. };
  19941. /**
  19942. * get a material using its id
  19943. * @param {string} the material's ID
  19944. * @return {BABYLON.Material|null} the material or null if none found.
  19945. */
  19946. Scene.prototype.getMaterialByID = function (id) {
  19947. for (var index = 0; index < this.materials.length; index++) {
  19948. if (this.materials[index].id === id) {
  19949. return this.materials[index];
  19950. }
  19951. }
  19952. return null;
  19953. };
  19954. /**
  19955. * get a material using its name
  19956. * @param {string} the material's name
  19957. * @return {BABYLON.Material|null} the material or null if none found.
  19958. */
  19959. Scene.prototype.getMaterialByName = function (name) {
  19960. for (var index = 0; index < this.materials.length; index++) {
  19961. if (this.materials[index].name === name) {
  19962. return this.materials[index];
  19963. }
  19964. }
  19965. return null;
  19966. };
  19967. Scene.prototype.getLensFlareSystemByName = function (name) {
  19968. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19969. if (this.lensFlareSystems[index].name === name) {
  19970. return this.lensFlareSystems[index];
  19971. }
  19972. }
  19973. return null;
  19974. };
  19975. Scene.prototype.getLensFlareSystemByID = function (id) {
  19976. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19977. if (this.lensFlareSystems[index].id === id) {
  19978. return this.lensFlareSystems[index];
  19979. }
  19980. }
  19981. return null;
  19982. };
  19983. Scene.prototype.getCameraByID = function (id) {
  19984. for (var index = 0; index < this.cameras.length; index++) {
  19985. if (this.cameras[index].id === id) {
  19986. return this.cameras[index];
  19987. }
  19988. }
  19989. return null;
  19990. };
  19991. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19992. for (var index = 0; index < this.cameras.length; index++) {
  19993. if (this.cameras[index].uniqueId === uniqueId) {
  19994. return this.cameras[index];
  19995. }
  19996. }
  19997. return null;
  19998. };
  19999. /**
  20000. * get a camera using its name
  20001. * @param {string} the camera's name
  20002. * @return {BABYLON.Camera|null} the camera or null if none found.
  20003. */
  20004. Scene.prototype.getCameraByName = function (name) {
  20005. for (var index = 0; index < this.cameras.length; index++) {
  20006. if (this.cameras[index].name === name) {
  20007. return this.cameras[index];
  20008. }
  20009. }
  20010. return null;
  20011. };
  20012. /**
  20013. * get a bone using its id
  20014. * @param {string} the bone's id
  20015. * @return {BABYLON.Bone|null} the bone or null if not found
  20016. */
  20017. Scene.prototype.getBoneByID = function (id) {
  20018. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20019. var skeleton = this.skeletons[skeletonIndex];
  20020. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20021. if (skeleton.bones[boneIndex].id === id) {
  20022. return skeleton.bones[boneIndex];
  20023. }
  20024. }
  20025. }
  20026. return null;
  20027. };
  20028. /**
  20029. * get a bone using its id
  20030. * @param {string} the bone's name
  20031. * @return {BABYLON.Bone|null} the bone or null if not found
  20032. */
  20033. Scene.prototype.getBoneByName = function (name) {
  20034. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20035. var skeleton = this.skeletons[skeletonIndex];
  20036. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20037. if (skeleton.bones[boneIndex].name === name) {
  20038. return skeleton.bones[boneIndex];
  20039. }
  20040. }
  20041. }
  20042. return null;
  20043. };
  20044. /**
  20045. * get a light node using its name
  20046. * @param {string} the light's name
  20047. * @return {BABYLON.Light|null} the light or null if none found.
  20048. */
  20049. Scene.prototype.getLightByName = function (name) {
  20050. for (var index = 0; index < this.lights.length; index++) {
  20051. if (this.lights[index].name === name) {
  20052. return this.lights[index];
  20053. }
  20054. }
  20055. return null;
  20056. };
  20057. /**
  20058. * get a light node using its ID
  20059. * @param {string} the light's id
  20060. * @return {BABYLON.Light|null} the light or null if none found.
  20061. */
  20062. Scene.prototype.getLightByID = function (id) {
  20063. for (var index = 0; index < this.lights.length; index++) {
  20064. if (this.lights[index].id === id) {
  20065. return this.lights[index];
  20066. }
  20067. }
  20068. return null;
  20069. };
  20070. /**
  20071. * get a light node using its scene-generated unique ID
  20072. * @param {number} the light's unique id
  20073. * @return {BABYLON.Light|null} the light or null if none found.
  20074. */
  20075. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20076. for (var index = 0; index < this.lights.length; index++) {
  20077. if (this.lights[index].uniqueId === uniqueId) {
  20078. return this.lights[index];
  20079. }
  20080. }
  20081. return null;
  20082. };
  20083. /**
  20084. * get a particle system by id
  20085. * @param id {number} the particle system id
  20086. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  20087. */
  20088. Scene.prototype.getParticleSystemByID = function (id) {
  20089. for (var index = 0; index < this.particleSystems.length; index++) {
  20090. if (this.particleSystems[index].id === id) {
  20091. return this.particleSystems[index];
  20092. }
  20093. }
  20094. return null;
  20095. };
  20096. /**
  20097. * get a geometry using its ID
  20098. * @param {string} the geometry's id
  20099. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20100. */
  20101. Scene.prototype.getGeometryByID = function (id) {
  20102. for (var index = 0; index < this._geometries.length; index++) {
  20103. if (this._geometries[index].id === id) {
  20104. return this._geometries[index];
  20105. }
  20106. }
  20107. return null;
  20108. };
  20109. /**
  20110. * add a new geometry to this scene.
  20111. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20112. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20113. * @return {boolean} was the geometry added or not
  20114. */
  20115. Scene.prototype.pushGeometry = function (geometry, force) {
  20116. if (!force && this.getGeometryByID(geometry.id)) {
  20117. return false;
  20118. }
  20119. this._geometries.push(geometry);
  20120. //notify the collision coordinator
  20121. if (this.collisionCoordinator) {
  20122. this.collisionCoordinator.onGeometryAdded(geometry);
  20123. }
  20124. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20125. return true;
  20126. };
  20127. /**
  20128. * Removes an existing geometry
  20129. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20130. * @return {boolean} was the geometry removed or not
  20131. */
  20132. Scene.prototype.removeGeometry = function (geometry) {
  20133. var index = this._geometries.indexOf(geometry);
  20134. if (index > -1) {
  20135. this._geometries.splice(index, 1);
  20136. //notify the collision coordinator
  20137. if (this.collisionCoordinator) {
  20138. this.collisionCoordinator.onGeometryDeleted(geometry);
  20139. }
  20140. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20141. return true;
  20142. }
  20143. return false;
  20144. };
  20145. Scene.prototype.getGeometries = function () {
  20146. return this._geometries;
  20147. };
  20148. /**
  20149. * Get the first added mesh found of a given ID
  20150. * @param {string} id - the id to search for
  20151. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20152. */
  20153. Scene.prototype.getMeshByID = function (id) {
  20154. for (var index = 0; index < this.meshes.length; index++) {
  20155. if (this.meshes[index].id === id) {
  20156. return this.meshes[index];
  20157. }
  20158. }
  20159. return null;
  20160. };
  20161. Scene.prototype.getMeshesByID = function (id) {
  20162. return this.meshes.filter(function (m) {
  20163. return m.id === id;
  20164. });
  20165. };
  20166. /**
  20167. * Get the first added transform node found of a given ID
  20168. * @param {string} id - the id to search for
  20169. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20170. */
  20171. Scene.prototype.getTransformNodeByID = function (id) {
  20172. for (var index = 0; index < this.transformNodes.length; index++) {
  20173. if (this.transformNodes[index].id === id) {
  20174. return this.transformNodes[index];
  20175. }
  20176. }
  20177. return null;
  20178. };
  20179. Scene.prototype.getTransformNodesByID = function (id) {
  20180. return this.transformNodes.filter(function (m) {
  20181. return m.id === id;
  20182. });
  20183. };
  20184. /**
  20185. * Get a mesh with its auto-generated unique id
  20186. * @param {number} uniqueId - the unique id to search for
  20187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20188. */
  20189. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20190. for (var index = 0; index < this.meshes.length; index++) {
  20191. if (this.meshes[index].uniqueId === uniqueId) {
  20192. return this.meshes[index];
  20193. }
  20194. }
  20195. return null;
  20196. };
  20197. /**
  20198. * Get a the last added mesh found of a given ID
  20199. * @param {string} id - the id to search for
  20200. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20201. */
  20202. Scene.prototype.getLastMeshByID = function (id) {
  20203. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20204. if (this.meshes[index].id === id) {
  20205. return this.meshes[index];
  20206. }
  20207. }
  20208. return null;
  20209. };
  20210. /**
  20211. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20212. * @param {string} id - the id to search for
  20213. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20214. */
  20215. Scene.prototype.getLastEntryByID = function (id) {
  20216. var index;
  20217. for (index = this.meshes.length - 1; index >= 0; index--) {
  20218. if (this.meshes[index].id === id) {
  20219. return this.meshes[index];
  20220. }
  20221. }
  20222. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20223. if (this.transformNodes[index].id === id) {
  20224. return this.transformNodes[index];
  20225. }
  20226. }
  20227. for (index = this.cameras.length - 1; index >= 0; index--) {
  20228. if (this.cameras[index].id === id) {
  20229. return this.cameras[index];
  20230. }
  20231. }
  20232. for (index = this.lights.length - 1; index >= 0; index--) {
  20233. if (this.lights[index].id === id) {
  20234. return this.lights[index];
  20235. }
  20236. }
  20237. return null;
  20238. };
  20239. Scene.prototype.getNodeByID = function (id) {
  20240. var mesh = this.getMeshByID(id);
  20241. if (mesh) {
  20242. return mesh;
  20243. }
  20244. var light = this.getLightByID(id);
  20245. if (light) {
  20246. return light;
  20247. }
  20248. var camera = this.getCameraByID(id);
  20249. if (camera) {
  20250. return camera;
  20251. }
  20252. var bone = this.getBoneByID(id);
  20253. return bone;
  20254. };
  20255. Scene.prototype.getNodeByName = function (name) {
  20256. var mesh = this.getMeshByName(name);
  20257. if (mesh) {
  20258. return mesh;
  20259. }
  20260. var light = this.getLightByName(name);
  20261. if (light) {
  20262. return light;
  20263. }
  20264. var camera = this.getCameraByName(name);
  20265. if (camera) {
  20266. return camera;
  20267. }
  20268. var bone = this.getBoneByName(name);
  20269. return bone;
  20270. };
  20271. Scene.prototype.getMeshByName = function (name) {
  20272. for (var index = 0; index < this.meshes.length; index++) {
  20273. if (this.meshes[index].name === name) {
  20274. return this.meshes[index];
  20275. }
  20276. }
  20277. return null;
  20278. };
  20279. Scene.prototype.getTransformNodeByName = function (name) {
  20280. for (var index = 0; index < this.transformNodes.length; index++) {
  20281. if (this.transformNodes[index].name === name) {
  20282. return this.transformNodes[index];
  20283. }
  20284. }
  20285. return null;
  20286. };
  20287. Scene.prototype.getSoundByName = function (name) {
  20288. var index;
  20289. if (BABYLON.AudioEngine) {
  20290. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20291. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20292. return this.mainSoundTrack.soundCollection[index];
  20293. }
  20294. }
  20295. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20296. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20297. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20298. return this.soundTracks[sdIndex].soundCollection[index];
  20299. }
  20300. }
  20301. }
  20302. }
  20303. return null;
  20304. };
  20305. Scene.prototype.getLastSkeletonByID = function (id) {
  20306. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20307. if (this.skeletons[index].id === id) {
  20308. return this.skeletons[index];
  20309. }
  20310. }
  20311. return null;
  20312. };
  20313. Scene.prototype.getSkeletonById = function (id) {
  20314. for (var index = 0; index < this.skeletons.length; index++) {
  20315. if (this.skeletons[index].id === id) {
  20316. return this.skeletons[index];
  20317. }
  20318. }
  20319. return null;
  20320. };
  20321. Scene.prototype.getSkeletonByName = function (name) {
  20322. for (var index = 0; index < this.skeletons.length; index++) {
  20323. if (this.skeletons[index].name === name) {
  20324. return this.skeletons[index];
  20325. }
  20326. }
  20327. return null;
  20328. };
  20329. Scene.prototype.getMorphTargetManagerById = function (id) {
  20330. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20331. if (this.morphTargetManagers[index].uniqueId === id) {
  20332. return this.morphTargetManagers[index];
  20333. }
  20334. }
  20335. return null;
  20336. };
  20337. Scene.prototype.isActiveMesh = function (mesh) {
  20338. return (this._activeMeshes.indexOf(mesh) !== -1);
  20339. };
  20340. /**
  20341. * Return a the first highlight layer of the scene with a given name.
  20342. * @param name The name of the highlight layer to look for.
  20343. * @return The highlight layer if found otherwise null.
  20344. */
  20345. Scene.prototype.getHighlightLayerByName = function (name) {
  20346. for (var index = 0; index < this.highlightLayers.length; index++) {
  20347. if (this.highlightLayers[index].name === name) {
  20348. return this.highlightLayers[index];
  20349. }
  20350. }
  20351. return null;
  20352. };
  20353. Object.defineProperty(Scene.prototype, "uid", {
  20354. /**
  20355. * Return a unique id as a string which can serve as an identifier for the scene
  20356. */
  20357. get: function () {
  20358. if (!this._uid) {
  20359. this._uid = BABYLON.Tools.RandomId();
  20360. }
  20361. return this._uid;
  20362. },
  20363. enumerable: true,
  20364. configurable: true
  20365. });
  20366. /**
  20367. * Add an externaly attached data from its key.
  20368. * This method call will fail and return false, if such key already exists.
  20369. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20370. * @param key the unique key that identifies the data
  20371. * @param data the data object to associate to the key for this Engine instance
  20372. * @return true if no such key were already present and the data was added successfully, false otherwise
  20373. */
  20374. Scene.prototype.addExternalData = function (key, data) {
  20375. if (!this._externalData) {
  20376. this._externalData = new BABYLON.StringDictionary();
  20377. }
  20378. return this._externalData.add(key, data);
  20379. };
  20380. /**
  20381. * Get an externaly attached data from its key
  20382. * @param key the unique key that identifies the data
  20383. * @return the associated data, if present (can be null), or undefined if not present
  20384. */
  20385. Scene.prototype.getExternalData = function (key) {
  20386. if (!this._externalData) {
  20387. return null;
  20388. }
  20389. return this._externalData.get(key);
  20390. };
  20391. /**
  20392. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20393. * @param key the unique key that identifies the data
  20394. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20395. * @return the associated data, can be null if the factory returned null.
  20396. */
  20397. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20398. if (!this._externalData) {
  20399. this._externalData = new BABYLON.StringDictionary();
  20400. }
  20401. return this._externalData.getOrAddWithFactory(key, factory);
  20402. };
  20403. /**
  20404. * Remove an externaly attached data from the Engine instance
  20405. * @param key the unique key that identifies the data
  20406. * @return true if the data was successfully removed, false if it doesn't exist
  20407. */
  20408. Scene.prototype.removeExternalData = function (key) {
  20409. return this._externalData.remove(key);
  20410. };
  20411. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20412. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20413. var material = subMesh.getMaterial();
  20414. if (mesh.showSubMeshesBoundingBox) {
  20415. var boundingInfo = subMesh.getBoundingInfo();
  20416. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20417. }
  20418. if (material) {
  20419. // Render targets
  20420. if (material.getRenderTargetTextures) {
  20421. if (this._processedMaterials.indexOf(material) === -1) {
  20422. this._processedMaterials.push(material);
  20423. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20424. }
  20425. }
  20426. // Dispatch
  20427. this._activeIndices.addCount(subMesh.indexCount, false);
  20428. this._renderingManager.dispatch(subMesh);
  20429. }
  20430. }
  20431. };
  20432. Scene.prototype._isInIntermediateRendering = function () {
  20433. return this._intermediateRendering;
  20434. };
  20435. /**
  20436. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20437. */
  20438. Scene.prototype.freezeActiveMeshes = function () {
  20439. this._evaluateActiveMeshes();
  20440. this._activeMeshesFrozen = true;
  20441. return this;
  20442. };
  20443. /**
  20444. * Use this function to restart evaluating active meshes on every frame
  20445. */
  20446. Scene.prototype.unfreezeActiveMeshes = function () {
  20447. this._activeMeshesFrozen = false;
  20448. return this;
  20449. };
  20450. Scene.prototype._evaluateActiveMeshes = function () {
  20451. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20452. return;
  20453. }
  20454. if (!this.activeCamera) {
  20455. return;
  20456. }
  20457. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20458. this.activeCamera._activeMeshes.reset();
  20459. this._activeMeshes.reset();
  20460. this._renderingManager.reset();
  20461. this._processedMaterials.reset();
  20462. this._activeParticleSystems.reset();
  20463. this._activeSkeletons.reset();
  20464. this._softwareSkinnedMeshes.reset();
  20465. if (this._boundingBoxRenderer) {
  20466. this._boundingBoxRenderer.reset();
  20467. }
  20468. // Meshes
  20469. var meshes;
  20470. var len;
  20471. if (this._selectionOctree) {
  20472. var selection = this._selectionOctree.select(this._frustumPlanes);
  20473. meshes = selection.data;
  20474. len = selection.length;
  20475. }
  20476. else {
  20477. len = this.meshes.length;
  20478. meshes = this.meshes;
  20479. }
  20480. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20481. var mesh = meshes[meshIndex];
  20482. if (mesh.isBlocked) {
  20483. continue;
  20484. }
  20485. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20486. if (!mesh.isReady() || !mesh.isEnabled()) {
  20487. continue;
  20488. }
  20489. mesh.computeWorldMatrix();
  20490. // Intersections
  20491. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20492. this._meshesForIntersections.pushNoDuplicate(mesh);
  20493. }
  20494. // Switch to current LOD
  20495. var meshLOD = mesh.getLOD(this.activeCamera);
  20496. if (!meshLOD) {
  20497. continue;
  20498. }
  20499. mesh._preActivate();
  20500. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20501. this._activeMeshes.push(mesh);
  20502. this.activeCamera._activeMeshes.push(mesh);
  20503. mesh._activate(this._renderId);
  20504. if (meshLOD !== mesh) {
  20505. meshLOD._activate(this._renderId);
  20506. }
  20507. this._activeMesh(mesh, meshLOD);
  20508. }
  20509. }
  20510. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20511. // Particle systems
  20512. if (this.particlesEnabled) {
  20513. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20514. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20515. var particleSystem = this.particleSystems[particleIndex];
  20516. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20517. continue;
  20518. }
  20519. var emitter = particleSystem.emitter;
  20520. if (!emitter.position || emitter.isEnabled()) {
  20521. this._activeParticleSystems.push(particleSystem);
  20522. particleSystem.animate();
  20523. this._renderingManager.dispatchParticles(particleSystem);
  20524. }
  20525. }
  20526. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20527. }
  20528. };
  20529. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20530. if (mesh.skeleton && this.skeletonsEnabled) {
  20531. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20532. mesh.skeleton.prepare();
  20533. }
  20534. if (!mesh.computeBonesUsingShaders) {
  20535. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20536. }
  20537. }
  20538. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20539. var boundingInfo = sourceMesh.getBoundingInfo();
  20540. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20541. }
  20542. if (mesh && mesh.subMeshes) {
  20543. // Submeshes Octrees
  20544. var len;
  20545. var subMeshes;
  20546. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20547. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20548. len = intersections.length;
  20549. subMeshes = intersections.data;
  20550. }
  20551. else {
  20552. subMeshes = mesh.subMeshes;
  20553. len = subMeshes.length;
  20554. }
  20555. for (var subIndex = 0; subIndex < len; subIndex++) {
  20556. var subMesh = subMeshes[subIndex];
  20557. this._evaluateSubMesh(subMesh, mesh);
  20558. }
  20559. }
  20560. };
  20561. Scene.prototype.updateTransformMatrix = function (force) {
  20562. if (!this.activeCamera) {
  20563. return;
  20564. }
  20565. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20566. };
  20567. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20568. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20569. };
  20570. Scene.prototype._renderForCamera = function (camera) {
  20571. if (camera && camera._skipRendering) {
  20572. return;
  20573. }
  20574. var engine = this._engine;
  20575. this.activeCamera = camera;
  20576. if (!this.activeCamera)
  20577. throw new Error("Active camera not set");
  20578. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20579. // Viewport
  20580. engine.setViewport(this.activeCamera.viewport);
  20581. // Camera
  20582. this.resetCachedMaterial();
  20583. this._renderId++;
  20584. this.activeCamera.update();
  20585. this.updateTransformMatrix();
  20586. if (camera._alternateCamera) {
  20587. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20588. this._alternateRendering = true;
  20589. }
  20590. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20591. // Meshes
  20592. this._evaluateActiveMeshes();
  20593. // Software skinning
  20594. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20595. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20596. mesh.applySkeleton(mesh.skeleton);
  20597. }
  20598. // Render targets
  20599. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20600. var needsRestoreFrameBuffer = false;
  20601. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20602. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20603. }
  20604. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20605. this._intermediateRendering = true;
  20606. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20607. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20608. var renderTarget = this._renderTargets.data[renderIndex];
  20609. if (renderTarget._shouldRender()) {
  20610. this._renderId++;
  20611. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20612. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20613. }
  20614. }
  20615. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20616. this._intermediateRendering = false;
  20617. this._renderId++;
  20618. needsRestoreFrameBuffer = true; // Restore back buffer
  20619. }
  20620. // Render HighlightLayer Texture
  20621. var stencilState = this._engine.getStencilBuffer();
  20622. var renderhighlights = false;
  20623. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20624. this._intermediateRendering = true;
  20625. for (var i = 0; i < this.highlightLayers.length; i++) {
  20626. var highlightLayer = this.highlightLayers[i];
  20627. if (highlightLayer.shouldRender() &&
  20628. (!highlightLayer.camera ||
  20629. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20630. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20631. renderhighlights = true;
  20632. var renderTarget = highlightLayer._mainTexture;
  20633. if (renderTarget._shouldRender()) {
  20634. this._renderId++;
  20635. renderTarget.render(false, false);
  20636. needsRestoreFrameBuffer = true;
  20637. }
  20638. }
  20639. }
  20640. this._intermediateRendering = false;
  20641. this._renderId++;
  20642. }
  20643. if (needsRestoreFrameBuffer) {
  20644. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20645. }
  20646. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20647. // Prepare Frame
  20648. this.postProcessManager._prepareFrame();
  20649. // Backgrounds
  20650. var layerIndex;
  20651. var layer;
  20652. if (this.layers.length) {
  20653. engine.setDepthBuffer(false);
  20654. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20655. layer = this.layers[layerIndex];
  20656. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20657. layer.render();
  20658. }
  20659. }
  20660. engine.setDepthBuffer(true);
  20661. }
  20662. // Activate HighlightLayer stencil
  20663. if (renderhighlights) {
  20664. this._engine.setStencilBuffer(true);
  20665. }
  20666. // Render
  20667. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20668. this._renderingManager.render(null, null, true, true);
  20669. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20670. // Restore HighlightLayer stencil
  20671. if (renderhighlights) {
  20672. this._engine.setStencilBuffer(stencilState);
  20673. }
  20674. // Bounding boxes
  20675. if (this._boundingBoxRenderer) {
  20676. this._boundingBoxRenderer.render();
  20677. }
  20678. // Lens flares
  20679. if (this.lensFlaresEnabled) {
  20680. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20681. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20682. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20683. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20684. lensFlareSystem.render();
  20685. }
  20686. }
  20687. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20688. }
  20689. // Foregrounds
  20690. if (this.layers.length) {
  20691. engine.setDepthBuffer(false);
  20692. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20693. layer = this.layers[layerIndex];
  20694. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20695. layer.render();
  20696. }
  20697. }
  20698. engine.setDepthBuffer(true);
  20699. }
  20700. // Highlight Layer
  20701. if (renderhighlights) {
  20702. engine.setDepthBuffer(false);
  20703. for (var i = 0; i < this.highlightLayers.length; i++) {
  20704. if (this.highlightLayers[i].shouldRender()) {
  20705. this.highlightLayers[i].render();
  20706. }
  20707. }
  20708. engine.setDepthBuffer(true);
  20709. }
  20710. // Finalize frame
  20711. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20712. // Reset some special arrays
  20713. this._renderTargets.reset();
  20714. this._alternateRendering = false;
  20715. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20716. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20717. };
  20718. Scene.prototype._processSubCameras = function (camera) {
  20719. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20720. this._renderForCamera(camera);
  20721. return;
  20722. }
  20723. // Update camera
  20724. if (this.activeCamera) {
  20725. this.activeCamera.update();
  20726. }
  20727. // rig cameras
  20728. for (var index = 0; index < camera._rigCameras.length; index++) {
  20729. this._renderForCamera(camera._rigCameras[index]);
  20730. }
  20731. this.activeCamera = camera;
  20732. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20733. };
  20734. Scene.prototype._checkIntersections = function () {
  20735. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20736. var sourceMesh = this._meshesForIntersections.data[index];
  20737. if (!sourceMesh.actionManager) {
  20738. continue;
  20739. }
  20740. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20741. var action = sourceMesh.actionManager.actions[actionIndex];
  20742. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20743. var parameters = action.getTriggerParameter();
  20744. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20745. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20746. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20747. if (areIntersecting && currentIntersectionInProgress === -1) {
  20748. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20749. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20750. sourceMesh._intersectionsInProgress.push(otherMesh);
  20751. }
  20752. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20753. sourceMesh._intersectionsInProgress.push(otherMesh);
  20754. }
  20755. }
  20756. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20757. //They intersected, and now they don't.
  20758. //is this trigger an exit trigger? execute an event.
  20759. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20760. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20761. }
  20762. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20763. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20764. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20765. }
  20766. }
  20767. }
  20768. }
  20769. }
  20770. };
  20771. Scene.prototype.render = function () {
  20772. if (this.isDisposed) {
  20773. return;
  20774. }
  20775. this._activeParticles.fetchNewFrame();
  20776. this._totalVertices.fetchNewFrame();
  20777. this._activeIndices.fetchNewFrame();
  20778. this._activeBones.fetchNewFrame();
  20779. this._meshesForIntersections.reset();
  20780. this.resetCachedMaterial();
  20781. this.onBeforeAnimationsObservable.notifyObservers(this);
  20782. // Actions
  20783. if (this.actionManager) {
  20784. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20785. }
  20786. //Simplification Queue
  20787. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20788. this.simplificationQueue.executeNext();
  20789. }
  20790. if (this._engine.isDeterministicLockStep()) {
  20791. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  20792. var defaultFPS = (60.0 / 1000.0);
  20793. var defaultFrameTime = 1000 / 60; // frame time in MS
  20794. if (this._physicsEngine) {
  20795. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  20796. }
  20797. var stepsTaken = 0;
  20798. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20799. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  20800. internalSteps = Math.min(internalSteps, maxSubSteps);
  20801. do {
  20802. this.onBeforeStepObservable.notifyObservers(this);
  20803. // Animations
  20804. this._animationRatio = defaultFrameTime * defaultFPS;
  20805. this._animate();
  20806. this.onAfterAnimationsObservable.notifyObservers(this);
  20807. // Physics
  20808. if (this._physicsEngine) {
  20809. this.onBeforePhysicsObservable.notifyObservers(this);
  20810. this._physicsEngine._step(defaultFrameTime / 1000);
  20811. this.onAfterPhysicsObservable.notifyObservers(this);
  20812. }
  20813. this.onAfterStepObservable.notifyObservers(this);
  20814. this._currentStepId++;
  20815. stepsTaken++;
  20816. deltaTime -= defaultFrameTime;
  20817. } while (deltaTime > 0 && stepsTaken < internalSteps);
  20818. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  20819. }
  20820. else {
  20821. // Animations
  20822. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20823. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20824. this._animate();
  20825. this.onAfterAnimationsObservable.notifyObservers(this);
  20826. // Physics
  20827. if (this._physicsEngine) {
  20828. this.onBeforePhysicsObservable.notifyObservers(this);
  20829. this._physicsEngine._step(deltaTime / 1000.0);
  20830. this.onAfterPhysicsObservable.notifyObservers(this);
  20831. }
  20832. }
  20833. // update gamepad manager
  20834. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  20835. this._gamepadManager._checkGamepadsStatus();
  20836. }
  20837. // Before render
  20838. this.onBeforeRenderObservable.notifyObservers(this);
  20839. // Customs render targets
  20840. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20841. var engine = this.getEngine();
  20842. var currentActiveCamera = this.activeCamera;
  20843. if (this.renderTargetsEnabled) {
  20844. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20845. this._intermediateRendering = true;
  20846. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20847. var renderTarget = this.customRenderTargets[customIndex];
  20848. if (renderTarget._shouldRender()) {
  20849. this._renderId++;
  20850. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20851. if (!this.activeCamera)
  20852. throw new Error("Active camera not set");
  20853. // Viewport
  20854. engine.setViewport(this.activeCamera.viewport);
  20855. // Camera
  20856. this.updateTransformMatrix();
  20857. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20858. }
  20859. }
  20860. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20861. this._intermediateRendering = false;
  20862. this._renderId++;
  20863. }
  20864. // Restore back buffer
  20865. if (this.customRenderTargets.length > 0) {
  20866. engine.restoreDefaultFramebuffer();
  20867. }
  20868. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20869. this.activeCamera = currentActiveCamera;
  20870. // Procedural textures
  20871. if (this.proceduralTexturesEnabled) {
  20872. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20873. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20874. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20875. if (proceduralTexture._shouldRender()) {
  20876. proceduralTexture.render();
  20877. }
  20878. }
  20879. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20880. }
  20881. // Clear
  20882. if (this.autoClearDepthAndStencil || this.autoClear) {
  20883. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20884. }
  20885. // Shadows
  20886. if (this.shadowsEnabled) {
  20887. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20888. var light = this.lights[lightIndex];
  20889. var shadowGenerator = light.getShadowGenerator();
  20890. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20891. var shadowMap = (shadowGenerator.getShadowMap());
  20892. if (this.textures.indexOf(shadowMap) !== -1) {
  20893. this._renderTargets.push(shadowMap);
  20894. }
  20895. }
  20896. }
  20897. }
  20898. // Depth renderer
  20899. if (this._depthRenderer) {
  20900. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20901. }
  20902. // Geometry renderer
  20903. if (this._geometryBufferRenderer) {
  20904. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20905. }
  20906. // RenderPipeline
  20907. if (this._postProcessRenderPipelineManager) {
  20908. this._postProcessRenderPipelineManager.update();
  20909. }
  20910. // Multi-cameras?
  20911. if (this.activeCameras.length > 0) {
  20912. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20913. if (cameraIndex > 0) {
  20914. this._engine.clear(null, false, true, true);
  20915. }
  20916. this._processSubCameras(this.activeCameras[cameraIndex]);
  20917. }
  20918. }
  20919. else {
  20920. if (!this.activeCamera) {
  20921. throw new Error("No camera defined");
  20922. }
  20923. this._processSubCameras(this.activeCamera);
  20924. }
  20925. // Intersection checks
  20926. this._checkIntersections();
  20927. // Update the audio listener attached to the camera
  20928. if (BABYLON.AudioEngine) {
  20929. this._updateAudioParameters();
  20930. }
  20931. // After render
  20932. if (this.afterRender) {
  20933. this.afterRender();
  20934. }
  20935. this.onAfterRenderObservable.notifyObservers(this);
  20936. // Cleaning
  20937. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20938. var data = this._toBeDisposed.data[index];
  20939. if (data) {
  20940. data.dispose();
  20941. }
  20942. this._toBeDisposed[index] = null;
  20943. }
  20944. this._toBeDisposed.reset();
  20945. if (this.dumpNextRenderTargets) {
  20946. this.dumpNextRenderTargets = false;
  20947. }
  20948. this._activeBones.addCount(0, true);
  20949. this._activeIndices.addCount(0, true);
  20950. this._activeParticles.addCount(0, true);
  20951. };
  20952. Scene.prototype._updateAudioParameters = function () {
  20953. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20954. return;
  20955. }
  20956. var listeningCamera;
  20957. var audioEngine = BABYLON.Engine.audioEngine;
  20958. if (this.activeCameras.length > 0) {
  20959. listeningCamera = this.activeCameras[0];
  20960. }
  20961. else {
  20962. listeningCamera = this.activeCamera;
  20963. }
  20964. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20965. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20966. // for VR cameras
  20967. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20968. listeningCamera = listeningCamera.rigCameras[0];
  20969. }
  20970. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20971. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20972. cameraDirection.normalize();
  20973. // To avoid some errors on GearVR
  20974. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20975. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20976. }
  20977. var i;
  20978. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20979. var sound = this.mainSoundTrack.soundCollection[i];
  20980. if (sound.useCustomAttenuation) {
  20981. sound.updateDistanceFromListener();
  20982. }
  20983. }
  20984. for (i = 0; i < this.soundTracks.length; i++) {
  20985. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20986. sound = this.soundTracks[i].soundCollection[j];
  20987. if (sound.useCustomAttenuation) {
  20988. sound.updateDistanceFromListener();
  20989. }
  20990. }
  20991. }
  20992. }
  20993. };
  20994. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20995. // Audio
  20996. get: function () {
  20997. return this._audioEnabled;
  20998. },
  20999. set: function (value) {
  21000. this._audioEnabled = value;
  21001. if (BABYLON.AudioEngine) {
  21002. if (this._audioEnabled) {
  21003. this._enableAudio();
  21004. }
  21005. else {
  21006. this._disableAudio();
  21007. }
  21008. }
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. Scene.prototype._disableAudio = function () {
  21014. var i;
  21015. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21016. this.mainSoundTrack.soundCollection[i].pause();
  21017. }
  21018. for (i = 0; i < this.soundTracks.length; i++) {
  21019. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21020. this.soundTracks[i].soundCollection[j].pause();
  21021. }
  21022. }
  21023. };
  21024. Scene.prototype._enableAudio = function () {
  21025. var i;
  21026. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21027. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21028. this.mainSoundTrack.soundCollection[i].play();
  21029. }
  21030. }
  21031. for (i = 0; i < this.soundTracks.length; i++) {
  21032. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21033. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21034. this.soundTracks[i].soundCollection[j].play();
  21035. }
  21036. }
  21037. }
  21038. };
  21039. Object.defineProperty(Scene.prototype, "headphone", {
  21040. get: function () {
  21041. return this._headphone;
  21042. },
  21043. set: function (value) {
  21044. this._headphone = value;
  21045. if (BABYLON.AudioEngine) {
  21046. if (this._headphone) {
  21047. this._switchAudioModeForHeadphones();
  21048. }
  21049. else {
  21050. this._switchAudioModeForNormalSpeakers();
  21051. }
  21052. }
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Scene.prototype._switchAudioModeForHeadphones = function () {
  21058. this.mainSoundTrack.switchPanningModelToHRTF();
  21059. for (var i = 0; i < this.soundTracks.length; i++) {
  21060. this.soundTracks[i].switchPanningModelToHRTF();
  21061. }
  21062. };
  21063. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21064. this.mainSoundTrack.switchPanningModelToEqualPower();
  21065. for (var i = 0; i < this.soundTracks.length; i++) {
  21066. this.soundTracks[i].switchPanningModelToEqualPower();
  21067. }
  21068. };
  21069. Scene.prototype.enableDepthRenderer = function () {
  21070. if (this._depthRenderer) {
  21071. return this._depthRenderer;
  21072. }
  21073. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21074. return this._depthRenderer;
  21075. };
  21076. Scene.prototype.disableDepthRenderer = function () {
  21077. if (!this._depthRenderer) {
  21078. return;
  21079. }
  21080. this._depthRenderer.dispose();
  21081. this._depthRenderer = null;
  21082. };
  21083. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  21084. if (ratio === void 0) { ratio = 1; }
  21085. if (this._geometryBufferRenderer) {
  21086. return this._geometryBufferRenderer;
  21087. }
  21088. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  21089. if (!this._geometryBufferRenderer.isSupported) {
  21090. this._geometryBufferRenderer = null;
  21091. }
  21092. return this._geometryBufferRenderer;
  21093. };
  21094. Scene.prototype.disableGeometryBufferRenderer = function () {
  21095. if (!this._geometryBufferRenderer) {
  21096. return;
  21097. }
  21098. this._geometryBufferRenderer.dispose();
  21099. this._geometryBufferRenderer = null;
  21100. };
  21101. Scene.prototype.freezeMaterials = function () {
  21102. for (var i = 0; i < this.materials.length; i++) {
  21103. this.materials[i].freeze();
  21104. }
  21105. };
  21106. Scene.prototype.unfreezeMaterials = function () {
  21107. for (var i = 0; i < this.materials.length; i++) {
  21108. this.materials[i].unfreeze();
  21109. }
  21110. };
  21111. Scene.prototype.dispose = function () {
  21112. this.beforeRender = null;
  21113. this.afterRender = null;
  21114. this.skeletons = [];
  21115. this.morphTargetManagers = [];
  21116. this.importedMeshesFiles = new Array();
  21117. this.stopAllAnimations();
  21118. this.resetCachedMaterial();
  21119. if (this._depthRenderer) {
  21120. this._depthRenderer.dispose();
  21121. }
  21122. if (this._gamepadManager) {
  21123. this._gamepadManager.dispose();
  21124. this._gamepadManager = null;
  21125. }
  21126. // Smart arrays
  21127. if (this.activeCamera) {
  21128. this.activeCamera._activeMeshes.dispose();
  21129. this.activeCamera = null;
  21130. }
  21131. this._activeMeshes.dispose();
  21132. this._renderingManager.dispose();
  21133. this._processedMaterials.dispose();
  21134. this._activeParticleSystems.dispose();
  21135. this._activeSkeletons.dispose();
  21136. this._softwareSkinnedMeshes.dispose();
  21137. this._renderTargets.dispose();
  21138. if (this._boundingBoxRenderer) {
  21139. this._boundingBoxRenderer.dispose();
  21140. }
  21141. this._meshesForIntersections.dispose();
  21142. this._toBeDisposed.dispose();
  21143. // Debug layer
  21144. if (this._debugLayer) {
  21145. this._debugLayer.hide();
  21146. }
  21147. // Events
  21148. this.onDisposeObservable.notifyObservers(this);
  21149. this.onDisposeObservable.clear();
  21150. this.onBeforeRenderObservable.clear();
  21151. this.onAfterRenderObservable.clear();
  21152. this.OnBeforeRenderTargetsRenderObservable.clear();
  21153. this.OnAfterRenderTargetsRenderObservable.clear();
  21154. this.onAfterStepObservable.clear();
  21155. this.onBeforeStepObservable.clear();
  21156. this.onBeforeActiveMeshesEvaluationObservable.clear();
  21157. this.onAfterActiveMeshesEvaluationObservable.clear();
  21158. this.onBeforeParticlesRenderingObservable.clear();
  21159. this.onAfterParticlesRenderingObservable.clear();
  21160. this.onBeforeSpritesRenderingObservable.clear();
  21161. this.onAfterSpritesRenderingObservable.clear();
  21162. this.onBeforeDrawPhaseObservable.clear();
  21163. this.onAfterDrawPhaseObservable.clear();
  21164. this.onBeforePhysicsObservable.clear();
  21165. this.onAfterPhysicsObservable.clear();
  21166. this.onBeforeAnimationsObservable.clear();
  21167. this.onAfterAnimationsObservable.clear();
  21168. this.onDataLoadedObservable.clear();
  21169. this.detachControl();
  21170. // Release sounds & sounds tracks
  21171. if (BABYLON.AudioEngine) {
  21172. this.disposeSounds();
  21173. }
  21174. // VR Helper
  21175. if (this.VRHelper) {
  21176. this.VRHelper.dispose();
  21177. }
  21178. // Detach cameras
  21179. var canvas = this._engine.getRenderingCanvas();
  21180. if (canvas) {
  21181. var index;
  21182. for (index = 0; index < this.cameras.length; index++) {
  21183. this.cameras[index].detachControl(canvas);
  21184. }
  21185. }
  21186. // Release lights
  21187. while (this.lights.length) {
  21188. this.lights[0].dispose();
  21189. }
  21190. // Release meshes
  21191. while (this.meshes.length) {
  21192. this.meshes[0].dispose(true);
  21193. }
  21194. while (this.transformNodes.length) {
  21195. this.removeTransformNode(this.transformNodes[0]);
  21196. }
  21197. // Release cameras
  21198. while (this.cameras.length) {
  21199. this.cameras[0].dispose();
  21200. }
  21201. // Release materials
  21202. if (this.defaultMaterial) {
  21203. this.defaultMaterial.dispose();
  21204. }
  21205. while (this.multiMaterials.length) {
  21206. this.multiMaterials[0].dispose();
  21207. }
  21208. while (this.materials.length) {
  21209. this.materials[0].dispose();
  21210. }
  21211. // Release particles
  21212. while (this.particleSystems.length) {
  21213. this.particleSystems[0].dispose();
  21214. }
  21215. // Release sprites
  21216. while (this.spriteManagers.length) {
  21217. this.spriteManagers[0].dispose();
  21218. }
  21219. // Release postProcesses
  21220. while (this.postProcesses.length) {
  21221. this.postProcesses[0].dispose();
  21222. }
  21223. // Release layers
  21224. while (this.layers.length) {
  21225. this.layers[0].dispose();
  21226. }
  21227. while (this.highlightLayers.length) {
  21228. this.highlightLayers[0].dispose();
  21229. }
  21230. // Release textures
  21231. while (this.textures.length) {
  21232. this.textures[0].dispose();
  21233. }
  21234. // Release UBO
  21235. this._sceneUbo.dispose();
  21236. if (this._alternateSceneUbo) {
  21237. this._alternateSceneUbo.dispose();
  21238. }
  21239. // Post-processes
  21240. this.postProcessManager.dispose();
  21241. if (this._postProcessRenderPipelineManager) {
  21242. this._postProcessRenderPipelineManager.dispose();
  21243. }
  21244. // Physics
  21245. if (this._physicsEngine) {
  21246. this.disablePhysicsEngine();
  21247. }
  21248. // Remove from engine
  21249. index = this._engine.scenes.indexOf(this);
  21250. if (index > -1) {
  21251. this._engine.scenes.splice(index, 1);
  21252. }
  21253. this._engine.wipeCaches(true);
  21254. this._isDisposed = true;
  21255. };
  21256. Object.defineProperty(Scene.prototype, "isDisposed", {
  21257. get: function () {
  21258. return this._isDisposed;
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. // Release sounds & sounds tracks
  21264. Scene.prototype.disposeSounds = function () {
  21265. if (!this._mainSoundTrack) {
  21266. return;
  21267. }
  21268. this.mainSoundTrack.dispose();
  21269. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21270. this.soundTracks[scIndex].dispose();
  21271. }
  21272. };
  21273. // Octrees
  21274. Scene.prototype.getWorldExtends = function () {
  21275. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21276. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21277. for (var index = 0; index < this.meshes.length; index++) {
  21278. var mesh = this.meshes[index];
  21279. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21280. continue;
  21281. }
  21282. mesh.computeWorldMatrix(true);
  21283. var boundingInfo = mesh.getBoundingInfo();
  21284. var minBox = boundingInfo.boundingBox.minimumWorld;
  21285. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21286. BABYLON.Tools.CheckExtends(minBox, min, max);
  21287. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21288. }
  21289. return {
  21290. min: min,
  21291. max: max
  21292. };
  21293. };
  21294. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21295. if (maxCapacity === void 0) { maxCapacity = 64; }
  21296. if (maxDepth === void 0) { maxDepth = 2; }
  21297. if (!this._selectionOctree) {
  21298. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21299. }
  21300. var worldExtends = this.getWorldExtends();
  21301. // Update octree
  21302. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21303. return this._selectionOctree;
  21304. };
  21305. // Picking
  21306. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21307. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21308. var result = BABYLON.Ray.Zero();
  21309. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21310. return result;
  21311. };
  21312. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21313. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21314. var engine = this._engine;
  21315. if (!camera) {
  21316. if (!this.activeCamera)
  21317. throw new Error("Active camera not set");
  21318. camera = this.activeCamera;
  21319. }
  21320. var cameraViewport = camera.viewport;
  21321. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21322. // Moving coordinates to local viewport world
  21323. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21324. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21325. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21326. return this;
  21327. };
  21328. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21329. var result = BABYLON.Ray.Zero();
  21330. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21331. return result;
  21332. };
  21333. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21334. if (!BABYLON.PickingInfo) {
  21335. return this;
  21336. }
  21337. var engine = this._engine;
  21338. if (!camera) {
  21339. if (!this.activeCamera)
  21340. throw new Error("Active camera not set");
  21341. camera = this.activeCamera;
  21342. }
  21343. var cameraViewport = camera.viewport;
  21344. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21345. var identity = BABYLON.Matrix.Identity();
  21346. // Moving coordinates to local viewport world
  21347. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21348. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21349. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21350. return this;
  21351. };
  21352. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21353. if (!BABYLON.PickingInfo) {
  21354. return null;
  21355. }
  21356. var pickingInfo = null;
  21357. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21358. var mesh = this.meshes[meshIndex];
  21359. if (predicate) {
  21360. if (!predicate(mesh)) {
  21361. continue;
  21362. }
  21363. }
  21364. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21365. continue;
  21366. }
  21367. var world = mesh.getWorldMatrix();
  21368. var ray = rayFunction(world);
  21369. var result = mesh.intersects(ray, fastCheck);
  21370. if (!result || !result.hit)
  21371. continue;
  21372. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21373. continue;
  21374. pickingInfo = result;
  21375. if (fastCheck) {
  21376. break;
  21377. }
  21378. }
  21379. return pickingInfo || new BABYLON.PickingInfo();
  21380. };
  21381. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21382. if (!BABYLON.PickingInfo) {
  21383. return null;
  21384. }
  21385. var pickingInfos = new Array();
  21386. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21387. var mesh = this.meshes[meshIndex];
  21388. if (predicate) {
  21389. if (!predicate(mesh)) {
  21390. continue;
  21391. }
  21392. }
  21393. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21394. continue;
  21395. }
  21396. var world = mesh.getWorldMatrix();
  21397. var ray = rayFunction(world);
  21398. var result = mesh.intersects(ray, false);
  21399. if (!result || !result.hit)
  21400. continue;
  21401. pickingInfos.push(result);
  21402. }
  21403. return pickingInfos;
  21404. };
  21405. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21406. if (!BABYLON.PickingInfo) {
  21407. return null;
  21408. }
  21409. var pickingInfo = null;
  21410. if (!camera) {
  21411. if (!this.activeCamera) {
  21412. return null;
  21413. }
  21414. camera = this.activeCamera;
  21415. }
  21416. if (this.spriteManagers.length > 0) {
  21417. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21418. var spriteManager = this.spriteManagers[spriteIndex];
  21419. if (!spriteManager.isPickable) {
  21420. continue;
  21421. }
  21422. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21423. if (!result || !result.hit)
  21424. continue;
  21425. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21426. continue;
  21427. pickingInfo = result;
  21428. if (fastCheck) {
  21429. break;
  21430. }
  21431. }
  21432. }
  21433. return pickingInfo || new BABYLON.PickingInfo();
  21434. };
  21435. /** Launch a ray to try to pick a mesh in the scene
  21436. * @param x position on screen
  21437. * @param y position on screen
  21438. * @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
  21439. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21440. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21441. */
  21442. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21443. var _this = this;
  21444. if (!BABYLON.PickingInfo) {
  21445. return null;
  21446. }
  21447. return this._internalPick(function (world) {
  21448. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21449. return _this._tempPickingRay;
  21450. }, predicate, fastCheck);
  21451. };
  21452. /** Launch a ray to try to pick a sprite in the scene
  21453. * @param x position on screen
  21454. * @param y position on screen
  21455. * @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
  21456. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21457. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21458. */
  21459. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21460. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21461. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21462. };
  21463. /** Use the given ray to pick a mesh in the scene
  21464. * @param ray The ray to use to pick meshes
  21465. * @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
  21466. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21467. */
  21468. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21469. var _this = this;
  21470. return this._internalPick(function (world) {
  21471. if (!_this._pickWithRayInverseMatrix) {
  21472. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21473. }
  21474. world.invertToRef(_this._pickWithRayInverseMatrix);
  21475. if (!_this._cachedRayForTransform) {
  21476. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21477. }
  21478. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21479. return _this._cachedRayForTransform;
  21480. }, predicate, fastCheck);
  21481. };
  21482. /**
  21483. * Launch a ray to try to pick a mesh in the scene
  21484. * @param x X position on screen
  21485. * @param y Y position on screen
  21486. * @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
  21487. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21488. */
  21489. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21490. var _this = this;
  21491. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21492. };
  21493. /**
  21494. * Launch a ray to try to pick a mesh in the scene
  21495. * @param ray Ray to use
  21496. * @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
  21497. */
  21498. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21499. var _this = this;
  21500. return this._internalMultiPick(function (world) {
  21501. if (!_this._pickWithRayInverseMatrix) {
  21502. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21503. }
  21504. world.invertToRef(_this._pickWithRayInverseMatrix);
  21505. if (!_this._cachedRayForTransform) {
  21506. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21507. }
  21508. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21509. return _this._cachedRayForTransform;
  21510. }, predicate);
  21511. };
  21512. Scene.prototype.setPointerOverMesh = function (mesh) {
  21513. if (this._pointerOverMesh === mesh) {
  21514. return;
  21515. }
  21516. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21517. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21518. }
  21519. this._pointerOverMesh = mesh;
  21520. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21521. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21522. }
  21523. };
  21524. Scene.prototype.getPointerOverMesh = function () {
  21525. return this._pointerOverMesh;
  21526. };
  21527. Scene.prototype.setPointerOverSprite = function (sprite) {
  21528. if (this._pointerOverSprite === sprite) {
  21529. return;
  21530. }
  21531. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21532. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21533. }
  21534. this._pointerOverSprite = sprite;
  21535. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21536. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21537. }
  21538. };
  21539. Scene.prototype.getPointerOverSprite = function () {
  21540. return this._pointerOverSprite;
  21541. };
  21542. // Physics
  21543. Scene.prototype.getPhysicsEngine = function () {
  21544. return this._physicsEngine;
  21545. };
  21546. /**
  21547. * Enables physics to the current scene
  21548. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21549. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21550. * @return {boolean} was the physics engine initialized
  21551. */
  21552. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21553. if (gravity === void 0) { gravity = null; }
  21554. if (this._physicsEngine) {
  21555. return true;
  21556. }
  21557. try {
  21558. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21559. return true;
  21560. }
  21561. catch (e) {
  21562. BABYLON.Tools.Error(e.message);
  21563. return false;
  21564. }
  21565. };
  21566. Scene.prototype.disablePhysicsEngine = function () {
  21567. if (!this._physicsEngine) {
  21568. return;
  21569. }
  21570. this._physicsEngine.dispose();
  21571. this._physicsEngine = null;
  21572. };
  21573. Scene.prototype.isPhysicsEnabled = function () {
  21574. return this._physicsEngine !== undefined;
  21575. };
  21576. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21577. var mesh = compound.parts[0].mesh;
  21578. if (mesh.physicsImpostor) {
  21579. mesh.physicsImpostor.dispose();
  21580. mesh.physicsImpostor = null;
  21581. }
  21582. };
  21583. // Misc.
  21584. Scene.prototype._rebuildGeometries = function () {
  21585. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21586. var geometry = _a[_i];
  21587. geometry._rebuild();
  21588. }
  21589. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21590. var mesh = _c[_b];
  21591. mesh._rebuild();
  21592. }
  21593. if (this.postProcessManager) {
  21594. this.postProcessManager._rebuild();
  21595. }
  21596. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21597. var layer = _e[_d];
  21598. layer._rebuild();
  21599. }
  21600. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21601. var highlightLayer = _g[_f];
  21602. highlightLayer._rebuild();
  21603. }
  21604. if (this._boundingBoxRenderer) {
  21605. this._boundingBoxRenderer._rebuild();
  21606. }
  21607. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21608. var system = _j[_h];
  21609. system.rebuild();
  21610. }
  21611. if (this._postProcessRenderPipelineManager) {
  21612. this._postProcessRenderPipelineManager._rebuild();
  21613. }
  21614. };
  21615. Scene.prototype._rebuildTextures = function () {
  21616. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21617. var texture = _a[_i];
  21618. texture._rebuild();
  21619. }
  21620. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21621. };
  21622. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21623. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21624. if (replace === void 0) { replace = false; }
  21625. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21626. // Dispose existing camera or light in replace mode.
  21627. if (replace) {
  21628. if (this.activeCamera) {
  21629. this.activeCamera.dispose();
  21630. this.activeCamera = null;
  21631. }
  21632. if (this.lights) {
  21633. for (var i = 0; i < this.lights.length; i++) {
  21634. this.lights[i].dispose();
  21635. }
  21636. }
  21637. }
  21638. // Light
  21639. if (this.lights.length === 0) {
  21640. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21641. }
  21642. // Camera
  21643. if (!this.activeCamera) {
  21644. var worldExtends = this.getWorldExtends();
  21645. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21646. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21647. var camera;
  21648. var radius = worldSize.length() * 1.5;
  21649. if (createArcRotateCamera) {
  21650. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21651. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21652. arcRotateCamera.wheelPrecision = 100 / radius;
  21653. camera = arcRotateCamera;
  21654. }
  21655. else {
  21656. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21657. freeCamera.setTarget(worldCenter);
  21658. camera = freeCamera;
  21659. }
  21660. camera.minZ = radius * 0.01;
  21661. camera.maxZ = radius * 100;
  21662. camera.speed = radius * 0.2;
  21663. this.activeCamera = camera;
  21664. var canvas = this.getEngine().getRenderingCanvas();
  21665. if (attachCameraControls && canvas) {
  21666. camera.attachControl(canvas);
  21667. }
  21668. }
  21669. };
  21670. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21671. if (pbr === void 0) { pbr = false; }
  21672. if (scale === void 0) { scale = 1000; }
  21673. if (blur === void 0) { blur = 0; }
  21674. if (environmentTexture) {
  21675. this.environmentTexture = environmentTexture;
  21676. }
  21677. if (!this.environmentTexture) {
  21678. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21679. return null;
  21680. }
  21681. // Skybox
  21682. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21683. if (pbr) {
  21684. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21685. hdrSkyboxMaterial.backFaceCulling = false;
  21686. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21687. if (hdrSkyboxMaterial.reflectionTexture) {
  21688. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21689. }
  21690. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21691. hdrSkyboxMaterial.disableLighting = true;
  21692. hdrSkyboxMaterial.twoSidedLighting = true;
  21693. hdrSkybox.infiniteDistance = true;
  21694. hdrSkybox.material = hdrSkyboxMaterial;
  21695. }
  21696. else {
  21697. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21698. skyboxMaterial.backFaceCulling = false;
  21699. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21700. if (skyboxMaterial.reflectionTexture) {
  21701. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21702. }
  21703. skyboxMaterial.disableLighting = true;
  21704. hdrSkybox.infiniteDistance = true;
  21705. hdrSkybox.material = skyboxMaterial;
  21706. }
  21707. return hdrSkybox;
  21708. };
  21709. Scene.prototype.createDefaultEnvironment = function (options) {
  21710. if (BABYLON.EnvironmentHelper) {
  21711. return new BABYLON.EnvironmentHelper(options, this);
  21712. }
  21713. return null;
  21714. };
  21715. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21716. if (webVROptions === void 0) { webVROptions = {}; }
  21717. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21718. };
  21719. // Tags
  21720. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21721. if (tagsQuery === undefined) {
  21722. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21723. return list;
  21724. }
  21725. var listByTags = [];
  21726. forEach = forEach || (function (item) { return; });
  21727. for (var i in list) {
  21728. var item = list[i];
  21729. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21730. listByTags.push(item);
  21731. forEach(item);
  21732. }
  21733. }
  21734. return listByTags;
  21735. };
  21736. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21737. return this._getByTags(this.meshes, tagsQuery, forEach);
  21738. };
  21739. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21740. return this._getByTags(this.cameras, tagsQuery, forEach);
  21741. };
  21742. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21743. return this._getByTags(this.lights, tagsQuery, forEach);
  21744. };
  21745. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21746. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21747. };
  21748. /**
  21749. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21750. * This allowed control for front to back rendering or reversly depending of the special needs.
  21751. *
  21752. * @param renderingGroupId The rendering group id corresponding to its index
  21753. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21754. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21755. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21756. */
  21757. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21758. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21759. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21760. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21761. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21762. };
  21763. /**
  21764. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21765. *
  21766. * @param renderingGroupId The rendering group id corresponding to its index
  21767. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21768. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21769. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21770. */
  21771. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21772. if (depth === void 0) { depth = true; }
  21773. if (stencil === void 0) { stencil = true; }
  21774. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21775. };
  21776. /**
  21777. * Will flag all materials as dirty to trigger new shader compilation
  21778. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21779. */
  21780. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21781. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21782. var material = _a[_i];
  21783. if (predicate && !predicate(material)) {
  21784. continue;
  21785. }
  21786. material.markAsDirty(flag);
  21787. }
  21788. };
  21789. // Statics
  21790. Scene._FOGMODE_NONE = 0;
  21791. Scene._FOGMODE_EXP = 1;
  21792. Scene._FOGMODE_EXP2 = 2;
  21793. Scene._FOGMODE_LINEAR = 3;
  21794. Scene._uniqueIdCounter = 0;
  21795. Scene.MinDeltaTime = 1.0;
  21796. Scene.MaxDeltaTime = 1000.0;
  21797. /** The distance in pixel that you have to move to prevent some events */
  21798. Scene.DragMovementThreshold = 10; // in pixels
  21799. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21800. Scene.LongPressDelay = 500; // in milliseconds
  21801. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21802. Scene.DoubleClickDelay = 300; // in milliseconds
  21803. /** If you need to check double click without raising a single click at first click, enable this flag */
  21804. Scene.ExclusiveDoubleClickMode = false;
  21805. return Scene;
  21806. }());
  21807. BABYLON.Scene = Scene;
  21808. })(BABYLON || (BABYLON = {}));
  21809. //# sourceMappingURL=babylon.scene.js.map
  21810. var BABYLON;
  21811. (function (BABYLON) {
  21812. var Buffer = /** @class */ (function () {
  21813. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21814. if (instanced === void 0) { instanced = false; }
  21815. if (engine instanceof BABYLON.Mesh) {
  21816. this._engine = engine.getScene().getEngine();
  21817. }
  21818. else {
  21819. this._engine = engine;
  21820. }
  21821. this._updatable = updatable;
  21822. this._data = data;
  21823. this._strideSize = stride;
  21824. if (!postponeInternalCreation) {
  21825. this.create();
  21826. }
  21827. this._instanced = instanced;
  21828. this._instanceDivisor = instanced ? 1 : 0;
  21829. }
  21830. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21831. // a lot of these parameters are ignored as they are overriden by the buffer
  21832. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21833. };
  21834. // Properties
  21835. Buffer.prototype.isUpdatable = function () {
  21836. return this._updatable;
  21837. };
  21838. Buffer.prototype.getData = function () {
  21839. return this._data;
  21840. };
  21841. Buffer.prototype.getBuffer = function () {
  21842. return this._buffer;
  21843. };
  21844. Buffer.prototype.getStrideSize = function () {
  21845. return this._strideSize;
  21846. };
  21847. Buffer.prototype.getIsInstanced = function () {
  21848. return this._instanced;
  21849. };
  21850. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21851. get: function () {
  21852. return this._instanceDivisor;
  21853. },
  21854. set: function (value) {
  21855. this._instanceDivisor = value;
  21856. if (value == 0) {
  21857. this._instanced = false;
  21858. }
  21859. else {
  21860. this._instanced = true;
  21861. }
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. // Methods
  21867. Buffer.prototype.create = function (data) {
  21868. if (data === void 0) { data = null; }
  21869. if (!data && this._buffer) {
  21870. return; // nothing to do
  21871. }
  21872. data = data || this._data;
  21873. if (!data) {
  21874. return;
  21875. }
  21876. if (!this._buffer) {
  21877. if (this._updatable) {
  21878. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21879. this._data = data;
  21880. }
  21881. else {
  21882. this._buffer = this._engine.createVertexBuffer(data);
  21883. }
  21884. }
  21885. else if (this._updatable) {
  21886. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21887. this._data = data;
  21888. }
  21889. };
  21890. Buffer.prototype._rebuild = function () {
  21891. this._buffer = null;
  21892. this.create(this._data);
  21893. };
  21894. Buffer.prototype.update = function (data) {
  21895. this.create(data);
  21896. };
  21897. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21898. if (!this._buffer) {
  21899. return;
  21900. }
  21901. if (this._updatable) {
  21902. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21903. this._data = null;
  21904. }
  21905. };
  21906. Buffer.prototype.dispose = function () {
  21907. if (!this._buffer) {
  21908. return;
  21909. }
  21910. if (this._engine._releaseBuffer(this._buffer)) {
  21911. this._buffer = null;
  21912. }
  21913. };
  21914. return Buffer;
  21915. }());
  21916. BABYLON.Buffer = Buffer;
  21917. })(BABYLON || (BABYLON = {}));
  21918. //# sourceMappingURL=babylon.buffer.js.map
  21919. var BABYLON;
  21920. (function (BABYLON) {
  21921. var VertexBuffer = /** @class */ (function () {
  21922. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21923. if (!stride) {
  21924. // Deduce stride from kind
  21925. switch (kind) {
  21926. case VertexBuffer.PositionKind:
  21927. stride = 3;
  21928. break;
  21929. case VertexBuffer.NormalKind:
  21930. stride = 3;
  21931. break;
  21932. case VertexBuffer.UVKind:
  21933. case VertexBuffer.UV2Kind:
  21934. case VertexBuffer.UV3Kind:
  21935. case VertexBuffer.UV4Kind:
  21936. case VertexBuffer.UV5Kind:
  21937. case VertexBuffer.UV6Kind:
  21938. stride = 2;
  21939. break;
  21940. case VertexBuffer.TangentKind:
  21941. case VertexBuffer.ColorKind:
  21942. stride = 4;
  21943. break;
  21944. case VertexBuffer.MatricesIndicesKind:
  21945. case VertexBuffer.MatricesIndicesExtraKind:
  21946. stride = 4;
  21947. break;
  21948. case VertexBuffer.MatricesWeightsKind:
  21949. case VertexBuffer.MatricesWeightsExtraKind:
  21950. default:
  21951. stride = 4;
  21952. break;
  21953. }
  21954. }
  21955. if (data instanceof BABYLON.Buffer) {
  21956. if (!stride) {
  21957. stride = data.getStrideSize();
  21958. }
  21959. this._buffer = data;
  21960. this._ownsBuffer = false;
  21961. }
  21962. else {
  21963. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21964. this._ownsBuffer = true;
  21965. }
  21966. this._stride = stride;
  21967. this._offset = offset ? offset : 0;
  21968. this._size = size ? size : stride;
  21969. this._kind = kind;
  21970. }
  21971. VertexBuffer.prototype._rebuild = function () {
  21972. if (!this._buffer) {
  21973. return;
  21974. }
  21975. this._buffer._rebuild();
  21976. };
  21977. /**
  21978. * Returns the kind of the VertexBuffer (string).
  21979. */
  21980. VertexBuffer.prototype.getKind = function () {
  21981. return this._kind;
  21982. };
  21983. // Properties
  21984. /**
  21985. * Boolean : is the VertexBuffer updatable ?
  21986. */
  21987. VertexBuffer.prototype.isUpdatable = function () {
  21988. return this._buffer.isUpdatable();
  21989. };
  21990. /**
  21991. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21992. */
  21993. VertexBuffer.prototype.getData = function () {
  21994. return this._buffer.getData();
  21995. };
  21996. /**
  21997. * Returns the WebGLBuffer associated to the VertexBuffer.
  21998. */
  21999. VertexBuffer.prototype.getBuffer = function () {
  22000. return this._buffer.getBuffer();
  22001. };
  22002. /**
  22003. * Returns the stride of the VertexBuffer (integer).
  22004. */
  22005. VertexBuffer.prototype.getStrideSize = function () {
  22006. return this._stride;
  22007. };
  22008. /**
  22009. * Returns the offset (integer).
  22010. */
  22011. VertexBuffer.prototype.getOffset = function () {
  22012. return this._offset;
  22013. };
  22014. /**
  22015. * Returns the VertexBuffer total size (integer).
  22016. */
  22017. VertexBuffer.prototype.getSize = function () {
  22018. return this._size;
  22019. };
  22020. /**
  22021. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22022. */
  22023. VertexBuffer.prototype.getIsInstanced = function () {
  22024. return this._buffer.getIsInstanced();
  22025. };
  22026. /**
  22027. * Returns the instancing divisor, zero for non-instanced (integer).
  22028. */
  22029. VertexBuffer.prototype.getInstanceDivisor = function () {
  22030. return this._buffer.instanceDivisor;
  22031. };
  22032. // Methods
  22033. /**
  22034. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22035. * Returns the created WebGLBuffer.
  22036. */
  22037. VertexBuffer.prototype.create = function (data) {
  22038. return this._buffer.create(data);
  22039. };
  22040. /**
  22041. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22042. * Returns the updated WebGLBuffer.
  22043. */
  22044. VertexBuffer.prototype.update = function (data) {
  22045. return this._buffer.update(data);
  22046. };
  22047. /**
  22048. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22049. * Returns the directly updated WebGLBuffer.
  22050. */
  22051. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22052. return this._buffer.updateDirectly(data, offset);
  22053. };
  22054. /**
  22055. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22056. */
  22057. VertexBuffer.prototype.dispose = function () {
  22058. if (this._ownsBuffer) {
  22059. this._buffer.dispose();
  22060. }
  22061. };
  22062. Object.defineProperty(VertexBuffer, "PositionKind", {
  22063. get: function () {
  22064. return VertexBuffer._PositionKind;
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(VertexBuffer, "NormalKind", {
  22070. get: function () {
  22071. return VertexBuffer._NormalKind;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(VertexBuffer, "TangentKind", {
  22077. get: function () {
  22078. return VertexBuffer._TangentKind;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(VertexBuffer, "UVKind", {
  22084. get: function () {
  22085. return VertexBuffer._UVKind;
  22086. },
  22087. enumerable: true,
  22088. configurable: true
  22089. });
  22090. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22091. get: function () {
  22092. return VertexBuffer._UV2Kind;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22098. get: function () {
  22099. return VertexBuffer._UV3Kind;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22105. get: function () {
  22106. return VertexBuffer._UV4Kind;
  22107. },
  22108. enumerable: true,
  22109. configurable: true
  22110. });
  22111. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22112. get: function () {
  22113. return VertexBuffer._UV5Kind;
  22114. },
  22115. enumerable: true,
  22116. configurable: true
  22117. });
  22118. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22119. get: function () {
  22120. return VertexBuffer._UV6Kind;
  22121. },
  22122. enumerable: true,
  22123. configurable: true
  22124. });
  22125. Object.defineProperty(VertexBuffer, "ColorKind", {
  22126. get: function () {
  22127. return VertexBuffer._ColorKind;
  22128. },
  22129. enumerable: true,
  22130. configurable: true
  22131. });
  22132. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22133. get: function () {
  22134. return VertexBuffer._MatricesIndicesKind;
  22135. },
  22136. enumerable: true,
  22137. configurable: true
  22138. });
  22139. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22140. get: function () {
  22141. return VertexBuffer._MatricesWeightsKind;
  22142. },
  22143. enumerable: true,
  22144. configurable: true
  22145. });
  22146. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22147. get: function () {
  22148. return VertexBuffer._MatricesIndicesExtraKind;
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22154. get: function () {
  22155. return VertexBuffer._MatricesWeightsExtraKind;
  22156. },
  22157. enumerable: true,
  22158. configurable: true
  22159. });
  22160. // Enums
  22161. VertexBuffer._PositionKind = "position";
  22162. VertexBuffer._NormalKind = "normal";
  22163. VertexBuffer._TangentKind = "tangent";
  22164. VertexBuffer._UVKind = "uv";
  22165. VertexBuffer._UV2Kind = "uv2";
  22166. VertexBuffer._UV3Kind = "uv3";
  22167. VertexBuffer._UV4Kind = "uv4";
  22168. VertexBuffer._UV5Kind = "uv5";
  22169. VertexBuffer._UV6Kind = "uv6";
  22170. VertexBuffer._ColorKind = "color";
  22171. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22172. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22173. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22174. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22175. return VertexBuffer;
  22176. }());
  22177. BABYLON.VertexBuffer = VertexBuffer;
  22178. })(BABYLON || (BABYLON = {}));
  22179. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22180. var BABYLON;
  22181. (function (BABYLON) {
  22182. var InternalTexture = /** @class */ (function () {
  22183. function InternalTexture(engine, dataSource) {
  22184. this.onLoadedObservable = new BABYLON.Observable();
  22185. // Private
  22186. this._initialSlot = -1;
  22187. this._designatedSlot = -1;
  22188. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22189. this._references = 1;
  22190. this._engine = engine;
  22191. this._dataSource = dataSource;
  22192. this._webGLTexture = engine._createTexture();
  22193. }
  22194. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22195. get: function () {
  22196. return this._dataSource;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. InternalTexture.prototype.incrementReferences = function () {
  22202. this._references++;
  22203. };
  22204. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22205. if (depth === void 0) { depth = 1; }
  22206. this.width = width;
  22207. this.height = height;
  22208. this.depth = depth;
  22209. this.baseWidth = width;
  22210. this.baseHeight = height;
  22211. this.baseDepth = depth;
  22212. this._size = width * height * depth;
  22213. };
  22214. InternalTexture.prototype._rebuild = function () {
  22215. var _this = this;
  22216. var proxy;
  22217. this.isReady = false;
  22218. this._cachedCoordinatesMode = null;
  22219. this._cachedWrapU = null;
  22220. this._cachedWrapV = null;
  22221. this._cachedAnisotropicFilteringLevel = null;
  22222. switch (this._dataSource) {
  22223. case InternalTexture.DATASOURCE_TEMP:
  22224. return;
  22225. case InternalTexture.DATASOURCE_URL:
  22226. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22227. _this.isReady = true;
  22228. }, null, this._buffer, undefined, this.format);
  22229. proxy._swapAndDie(this);
  22230. return;
  22231. case InternalTexture.DATASOURCE_RAW:
  22232. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22233. proxy._swapAndDie(this);
  22234. this.isReady = true;
  22235. return;
  22236. case InternalTexture.DATASOURCE_RAW3D:
  22237. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22238. proxy._swapAndDie(this);
  22239. this.isReady = true;
  22240. return;
  22241. case InternalTexture.DATASOURCE_DYNAMIC:
  22242. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22243. proxy._swapAndDie(this);
  22244. // The engine will make sure to update content so no need to flag it as isReady = true
  22245. return;
  22246. case InternalTexture.DATASOURCE_RENDERTARGET:
  22247. var options = new BABYLON.RenderTargetCreationOptions();
  22248. options.generateDepthBuffer = this._generateDepthBuffer;
  22249. options.generateMipMaps = this.generateMipMaps;
  22250. options.generateStencilBuffer = this._generateStencilBuffer;
  22251. options.samplingMode = this.samplingMode;
  22252. options.type = this.type;
  22253. if (this.isCube) {
  22254. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22255. }
  22256. else {
  22257. var size = {
  22258. width: this.width,
  22259. height: this.height
  22260. };
  22261. proxy = this._engine.createRenderTargetTexture(size, options);
  22262. }
  22263. proxy._swapAndDie(this);
  22264. this.isReady = true;
  22265. return;
  22266. case InternalTexture.DATASOURCE_CUBE:
  22267. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22268. _this.isReady = true;
  22269. }, null, this.format, this._extension);
  22270. proxy._swapAndDie(this);
  22271. return;
  22272. case InternalTexture.DATASOURCE_CUBERAW:
  22273. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22274. proxy._swapAndDie(this);
  22275. this.isReady = true;
  22276. return;
  22277. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22278. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22279. if (proxy) {
  22280. proxy._swapAndDie(_this);
  22281. }
  22282. _this.isReady = true;
  22283. }, null, this.format, this._extension);
  22284. return;
  22285. }
  22286. };
  22287. InternalTexture.prototype._swapAndDie = function (target) {
  22288. target._webGLTexture = this._webGLTexture;
  22289. if (this._framebuffer) {
  22290. target._framebuffer = this._framebuffer;
  22291. }
  22292. if (this._depthStencilBuffer) {
  22293. target._depthStencilBuffer = this._depthStencilBuffer;
  22294. }
  22295. if (this._lodTextureHigh) {
  22296. if (target._lodTextureHigh) {
  22297. target._lodTextureHigh.dispose();
  22298. }
  22299. target._lodTextureHigh = this._lodTextureHigh;
  22300. }
  22301. if (this._lodTextureMid) {
  22302. if (target._lodTextureMid) {
  22303. target._lodTextureMid.dispose();
  22304. }
  22305. target._lodTextureMid = this._lodTextureMid;
  22306. }
  22307. if (this._lodTextureLow) {
  22308. if (target._lodTextureLow) {
  22309. target._lodTextureLow.dispose();
  22310. }
  22311. target._lodTextureLow = this._lodTextureLow;
  22312. }
  22313. var cache = this._engine.getLoadedTexturesCache();
  22314. var index = cache.indexOf(this);
  22315. if (index !== -1) {
  22316. cache.splice(index, 1);
  22317. }
  22318. };
  22319. InternalTexture.prototype.dispose = function () {
  22320. if (!this._webGLTexture) {
  22321. return;
  22322. }
  22323. this._references--;
  22324. if (this._references === 0) {
  22325. this._engine._releaseTexture(this);
  22326. this._webGLTexture = null;
  22327. }
  22328. };
  22329. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22330. InternalTexture.DATASOURCE_URL = 1;
  22331. InternalTexture.DATASOURCE_TEMP = 2;
  22332. InternalTexture.DATASOURCE_RAW = 3;
  22333. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22334. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22335. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22336. InternalTexture.DATASOURCE_CUBE = 7;
  22337. InternalTexture.DATASOURCE_CUBERAW = 8;
  22338. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22339. InternalTexture.DATASOURCE_RAW3D = 10;
  22340. return InternalTexture;
  22341. }());
  22342. BABYLON.InternalTexture = InternalTexture;
  22343. })(BABYLON || (BABYLON = {}));
  22344. //# sourceMappingURL=babylon.internalTexture.js.map
  22345. var BABYLON;
  22346. (function (BABYLON) {
  22347. var BaseTexture = /** @class */ (function () {
  22348. function BaseTexture(scene) {
  22349. this._hasAlpha = false;
  22350. this.getAlphaFromRGB = false;
  22351. this.level = 1;
  22352. this.coordinatesIndex = 0;
  22353. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22354. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22355. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22356. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22357. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22358. this.isCube = false;
  22359. this.is3D = false;
  22360. this.gammaSpace = true;
  22361. this.invertZ = false;
  22362. this.lodLevelInAlpha = false;
  22363. this.lodGenerationOffset = 0.0;
  22364. this.lodGenerationScale = 0.8;
  22365. this.isRenderTarget = false;
  22366. this.animations = new Array();
  22367. /**
  22368. * An event triggered when the texture is disposed.
  22369. * @type {BABYLON.Observable}
  22370. */
  22371. this.onDisposeObservable = new BABYLON.Observable();
  22372. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22373. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22374. if (this._scene) {
  22375. this._scene.textures.push(this);
  22376. }
  22377. this._uid = null;
  22378. }
  22379. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22380. get: function () {
  22381. return this._hasAlpha;
  22382. },
  22383. set: function (value) {
  22384. if (this._hasAlpha === value) {
  22385. return;
  22386. }
  22387. this._hasAlpha = value;
  22388. if (this._scene) {
  22389. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22390. }
  22391. },
  22392. enumerable: true,
  22393. configurable: true
  22394. });
  22395. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22396. get: function () {
  22397. return this._coordinatesMode;
  22398. },
  22399. set: function (value) {
  22400. if (this._coordinatesMode === value) {
  22401. return;
  22402. }
  22403. this._coordinatesMode = value;
  22404. if (this._scene) {
  22405. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22406. }
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Object.defineProperty(BaseTexture.prototype, "uid", {
  22412. get: function () {
  22413. if (!this._uid) {
  22414. this._uid = BABYLON.Tools.RandomId();
  22415. }
  22416. return this._uid;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. BaseTexture.prototype.toString = function () {
  22422. return this.name;
  22423. };
  22424. BaseTexture.prototype.getClassName = function () {
  22425. return "BaseTexture";
  22426. };
  22427. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22428. set: function (callback) {
  22429. if (this._onDisposeObserver) {
  22430. this.onDisposeObservable.remove(this._onDisposeObserver);
  22431. }
  22432. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22433. },
  22434. enumerable: true,
  22435. configurable: true
  22436. });
  22437. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22438. get: function () {
  22439. return true;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. BaseTexture.prototype.getScene = function () {
  22445. return this._scene;
  22446. };
  22447. BaseTexture.prototype.getTextureMatrix = function () {
  22448. return BABYLON.Matrix.IdentityReadOnly;
  22449. };
  22450. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22451. return BABYLON.Matrix.IdentityReadOnly;
  22452. };
  22453. BaseTexture.prototype.getInternalTexture = function () {
  22454. return this._texture;
  22455. };
  22456. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22457. return !this.isBlocking || this.isReady();
  22458. };
  22459. BaseTexture.prototype.isReady = function () {
  22460. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22461. this.delayLoad();
  22462. return false;
  22463. }
  22464. if (this._texture) {
  22465. return this._texture.isReady;
  22466. }
  22467. return false;
  22468. };
  22469. BaseTexture.prototype.getSize = function () {
  22470. if (this._texture && this._texture.width) {
  22471. return new BABYLON.Size(this._texture.width, this._texture.height);
  22472. }
  22473. if (this._texture && this._texture._size) {
  22474. return new BABYLON.Size(this._texture._size, this._texture._size);
  22475. }
  22476. return BABYLON.Size.Zero();
  22477. };
  22478. BaseTexture.prototype.getBaseSize = function () {
  22479. if (!this.isReady() || !this._texture)
  22480. return BABYLON.Size.Zero();
  22481. if (this._texture._size) {
  22482. return new BABYLON.Size(this._texture._size, this._texture._size);
  22483. }
  22484. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22485. };
  22486. BaseTexture.prototype.scale = function (ratio) {
  22487. };
  22488. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22489. get: function () {
  22490. return false;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22496. if (!this._scene) {
  22497. return null;
  22498. }
  22499. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22500. for (var index = 0; index < texturesCache.length; index++) {
  22501. var texturesCacheEntry = texturesCache[index];
  22502. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22503. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22504. texturesCacheEntry.incrementReferences();
  22505. return texturesCacheEntry;
  22506. }
  22507. }
  22508. }
  22509. return null;
  22510. };
  22511. BaseTexture.prototype._rebuild = function () {
  22512. };
  22513. BaseTexture.prototype.delayLoad = function () {
  22514. };
  22515. BaseTexture.prototype.clone = function () {
  22516. return null;
  22517. };
  22518. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22519. get: function () {
  22520. if (!this._texture) {
  22521. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22522. }
  22523. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22529. get: function () {
  22530. if (!this._texture) {
  22531. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22532. }
  22533. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22534. },
  22535. enumerable: true,
  22536. configurable: true
  22537. });
  22538. BaseTexture.prototype.readPixels = function (faceIndex) {
  22539. if (faceIndex === void 0) { faceIndex = 0; }
  22540. if (!this._texture) {
  22541. return null;
  22542. }
  22543. var size = this.getSize();
  22544. var scene = this.getScene();
  22545. if (!scene) {
  22546. return null;
  22547. }
  22548. var engine = scene.getEngine();
  22549. if (this._texture.isCube) {
  22550. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22551. }
  22552. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22553. };
  22554. BaseTexture.prototype.releaseInternalTexture = function () {
  22555. if (this._texture) {
  22556. this._texture.dispose();
  22557. this._texture = null;
  22558. }
  22559. };
  22560. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22561. get: function () {
  22562. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22563. return null;
  22564. }
  22565. if (!this._texture._sphericalPolynomial) {
  22566. this._texture._sphericalPolynomial =
  22567. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22568. }
  22569. return this._texture._sphericalPolynomial;
  22570. },
  22571. set: function (value) {
  22572. if (this._texture) {
  22573. this._texture._sphericalPolynomial = value;
  22574. }
  22575. },
  22576. enumerable: true,
  22577. configurable: true
  22578. });
  22579. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22580. get: function () {
  22581. if (this._texture) {
  22582. return this._texture._lodTextureHigh;
  22583. }
  22584. return null;
  22585. },
  22586. enumerable: true,
  22587. configurable: true
  22588. });
  22589. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22590. get: function () {
  22591. if (this._texture) {
  22592. return this._texture._lodTextureMid;
  22593. }
  22594. return null;
  22595. },
  22596. enumerable: true,
  22597. configurable: true
  22598. });
  22599. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22600. get: function () {
  22601. if (this._texture) {
  22602. return this._texture._lodTextureLow;
  22603. }
  22604. return null;
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. BaseTexture.prototype.dispose = function () {
  22610. if (!this._scene) {
  22611. return;
  22612. }
  22613. // Animations
  22614. this._scene.stopAnimation(this);
  22615. // Remove from scene
  22616. this._scene._removePendingData(this);
  22617. var index = this._scene.textures.indexOf(this);
  22618. if (index >= 0) {
  22619. this._scene.textures.splice(index, 1);
  22620. }
  22621. if (this._texture === undefined) {
  22622. return;
  22623. }
  22624. // Release
  22625. this.releaseInternalTexture();
  22626. // Callback
  22627. this.onDisposeObservable.notifyObservers(this);
  22628. this.onDisposeObservable.clear();
  22629. };
  22630. BaseTexture.prototype.serialize = function () {
  22631. if (!this.name) {
  22632. return null;
  22633. }
  22634. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22635. // Animations
  22636. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22637. return serializationObject;
  22638. };
  22639. BaseTexture.WhenAllReady = function (textures, callback) {
  22640. var numRemaining = textures.length;
  22641. if (numRemaining === 0) {
  22642. callback();
  22643. return;
  22644. }
  22645. var _loop_1 = function () {
  22646. texture = textures[i];
  22647. if (texture.isReady()) {
  22648. if (--numRemaining === 0) {
  22649. callback();
  22650. }
  22651. }
  22652. else {
  22653. onLoadObservable = texture.onLoadObservable;
  22654. var onLoadCallback_1 = function () {
  22655. onLoadObservable.removeCallback(onLoadCallback_1);
  22656. if (--numRemaining === 0) {
  22657. callback();
  22658. }
  22659. };
  22660. onLoadObservable.add(onLoadCallback_1);
  22661. }
  22662. };
  22663. var texture, onLoadObservable;
  22664. for (var i = 0; i < textures.length; i++) {
  22665. _loop_1();
  22666. }
  22667. };
  22668. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22669. __decorate([
  22670. BABYLON.serialize()
  22671. ], BaseTexture.prototype, "name", void 0);
  22672. __decorate([
  22673. BABYLON.serialize("hasAlpha")
  22674. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22675. __decorate([
  22676. BABYLON.serialize()
  22677. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22678. __decorate([
  22679. BABYLON.serialize()
  22680. ], BaseTexture.prototype, "level", void 0);
  22681. __decorate([
  22682. BABYLON.serialize()
  22683. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22684. __decorate([
  22685. BABYLON.serialize("coordinatesMode")
  22686. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22687. __decorate([
  22688. BABYLON.serialize()
  22689. ], BaseTexture.prototype, "wrapU", void 0);
  22690. __decorate([
  22691. BABYLON.serialize()
  22692. ], BaseTexture.prototype, "wrapV", void 0);
  22693. __decorate([
  22694. BABYLON.serialize()
  22695. ], BaseTexture.prototype, "wrapR", void 0);
  22696. __decorate([
  22697. BABYLON.serialize()
  22698. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22699. __decorate([
  22700. BABYLON.serialize()
  22701. ], BaseTexture.prototype, "isCube", void 0);
  22702. __decorate([
  22703. BABYLON.serialize()
  22704. ], BaseTexture.prototype, "is3D", void 0);
  22705. __decorate([
  22706. BABYLON.serialize()
  22707. ], BaseTexture.prototype, "gammaSpace", void 0);
  22708. __decorate([
  22709. BABYLON.serialize()
  22710. ], BaseTexture.prototype, "invertZ", void 0);
  22711. __decorate([
  22712. BABYLON.serialize()
  22713. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22714. __decorate([
  22715. BABYLON.serialize()
  22716. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22717. __decorate([
  22718. BABYLON.serialize()
  22719. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22720. __decorate([
  22721. BABYLON.serialize()
  22722. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22723. return BaseTexture;
  22724. }());
  22725. BABYLON.BaseTexture = BaseTexture;
  22726. })(BABYLON || (BABYLON = {}));
  22727. //# sourceMappingURL=babylon.baseTexture.js.map
  22728. var BABYLON;
  22729. (function (BABYLON) {
  22730. var Texture = /** @class */ (function (_super) {
  22731. __extends(Texture, _super);
  22732. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22733. if (noMipmap === void 0) { noMipmap = false; }
  22734. if (invertY === void 0) { invertY = true; }
  22735. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22736. if (onLoad === void 0) { onLoad = null; }
  22737. if (onError === void 0) { onError = null; }
  22738. if (buffer === void 0) { buffer = null; }
  22739. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22740. var _this = _super.call(this, scene) || this;
  22741. _this.uOffset = 0;
  22742. _this.vOffset = 0;
  22743. _this.uScale = 1.0;
  22744. _this.vScale = 1.0;
  22745. _this.uAng = 0;
  22746. _this.vAng = 0;
  22747. _this.wAng = 0;
  22748. _this._isBlocking = true;
  22749. _this.name = url || "";
  22750. _this.url = url;
  22751. _this._noMipmap = noMipmap;
  22752. _this._invertY = invertY;
  22753. _this._samplingMode = samplingMode;
  22754. _this._buffer = buffer;
  22755. _this._deleteBuffer = deleteBuffer;
  22756. if (format) {
  22757. _this._format = format;
  22758. }
  22759. scene = _this.getScene();
  22760. if (!scene) {
  22761. return _this;
  22762. }
  22763. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22764. var load = function () {
  22765. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22766. _this.onLoadObservable.notifyObservers(_this);
  22767. }
  22768. if (onLoad) {
  22769. onLoad();
  22770. }
  22771. if (!_this.isBlocking && scene) {
  22772. scene.resetCachedMaterial();
  22773. }
  22774. };
  22775. if (!_this.url) {
  22776. _this._delayedOnLoad = load;
  22777. _this._delayedOnError = onError;
  22778. return _this;
  22779. }
  22780. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22781. if (!_this._texture) {
  22782. if (!scene.useDelayedTextureLoading) {
  22783. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22784. if (deleteBuffer) {
  22785. delete _this._buffer;
  22786. }
  22787. }
  22788. else {
  22789. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22790. _this._delayedOnLoad = load;
  22791. _this._delayedOnError = onError;
  22792. }
  22793. }
  22794. else {
  22795. if (_this._texture.isReady) {
  22796. BABYLON.Tools.SetImmediate(function () { return load(); });
  22797. }
  22798. else {
  22799. _this._texture.onLoadedObservable.add(load);
  22800. }
  22801. }
  22802. return _this;
  22803. }
  22804. Object.defineProperty(Texture.prototype, "noMipmap", {
  22805. get: function () {
  22806. return this._noMipmap;
  22807. },
  22808. enumerable: true,
  22809. configurable: true
  22810. });
  22811. Object.defineProperty(Texture.prototype, "isBlocking", {
  22812. get: function () {
  22813. return this._isBlocking;
  22814. },
  22815. set: function (value) {
  22816. this._isBlocking = value;
  22817. },
  22818. enumerable: true,
  22819. configurable: true
  22820. });
  22821. Object.defineProperty(Texture.prototype, "samplingMode", {
  22822. get: function () {
  22823. return this._samplingMode;
  22824. },
  22825. enumerable: true,
  22826. configurable: true
  22827. });
  22828. Texture.prototype.updateURL = function (url) {
  22829. this.url = url;
  22830. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22831. this.delayLoad();
  22832. };
  22833. Texture.prototype.delayLoad = function () {
  22834. var _this = this;
  22835. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22836. return;
  22837. }
  22838. var scene = this.getScene();
  22839. if (!scene) {
  22840. return;
  22841. }
  22842. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22843. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22844. if (!this._texture) {
  22845. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22846. if (this._deleteBuffer) {
  22847. delete this._buffer;
  22848. }
  22849. }
  22850. else {
  22851. if (this._texture.isReady) {
  22852. BABYLON.Tools.SetImmediate(function () {
  22853. if (!_this._delayedOnLoad) {
  22854. return;
  22855. }
  22856. _this._delayedOnLoad();
  22857. });
  22858. }
  22859. else {
  22860. if (this._delayedOnLoad) {
  22861. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22862. }
  22863. }
  22864. }
  22865. };
  22866. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22867. if (!this._texture) {
  22868. return;
  22869. }
  22870. var scene = this.getScene();
  22871. if (!scene) {
  22872. return;
  22873. }
  22874. this._samplingMode = samplingMode;
  22875. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22876. };
  22877. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22878. x *= this.uScale;
  22879. y *= this.vScale;
  22880. x -= 0.5 * this.uScale;
  22881. y -= 0.5 * this.vScale;
  22882. z -= 0.5;
  22883. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22884. t.x += 0.5 * this.uScale + this.uOffset;
  22885. t.y += 0.5 * this.vScale + this.vOffset;
  22886. t.z += 0.5;
  22887. };
  22888. Texture.prototype.getTextureMatrix = function () {
  22889. var _this = this;
  22890. if (this.uOffset === this._cachedUOffset &&
  22891. this.vOffset === this._cachedVOffset &&
  22892. this.uScale === this._cachedUScale &&
  22893. this.vScale === this._cachedVScale &&
  22894. this.uAng === this._cachedUAng &&
  22895. this.vAng === this._cachedVAng &&
  22896. this.wAng === this._cachedWAng) {
  22897. return this._cachedTextureMatrix;
  22898. }
  22899. this._cachedUOffset = this.uOffset;
  22900. this._cachedVOffset = this.vOffset;
  22901. this._cachedUScale = this.uScale;
  22902. this._cachedVScale = this.vScale;
  22903. this._cachedUAng = this.uAng;
  22904. this._cachedVAng = this.vAng;
  22905. this._cachedWAng = this.wAng;
  22906. if (!this._cachedTextureMatrix) {
  22907. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22908. this._rowGenerationMatrix = new BABYLON.Matrix();
  22909. this._t0 = BABYLON.Vector3.Zero();
  22910. this._t1 = BABYLON.Vector3.Zero();
  22911. this._t2 = BABYLON.Vector3.Zero();
  22912. }
  22913. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22914. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22915. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22916. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22917. this._t1.subtractInPlace(this._t0);
  22918. this._t2.subtractInPlace(this._t0);
  22919. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22920. this._cachedTextureMatrix.m[0] = this._t1.x;
  22921. this._cachedTextureMatrix.m[1] = this._t1.y;
  22922. this._cachedTextureMatrix.m[2] = this._t1.z;
  22923. this._cachedTextureMatrix.m[4] = this._t2.x;
  22924. this._cachedTextureMatrix.m[5] = this._t2.y;
  22925. this._cachedTextureMatrix.m[6] = this._t2.z;
  22926. this._cachedTextureMatrix.m[8] = this._t0.x;
  22927. this._cachedTextureMatrix.m[9] = this._t0.y;
  22928. this._cachedTextureMatrix.m[10] = this._t0.z;
  22929. var scene = this.getScene();
  22930. if (!scene) {
  22931. return this._cachedTextureMatrix;
  22932. }
  22933. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22934. return mat.hasTexture(_this);
  22935. });
  22936. return this._cachedTextureMatrix;
  22937. };
  22938. Texture.prototype.getReflectionTextureMatrix = function () {
  22939. var _this = this;
  22940. var scene = this.getScene();
  22941. if (!scene) {
  22942. return this._cachedTextureMatrix;
  22943. }
  22944. if (this.uOffset === this._cachedUOffset &&
  22945. this.vOffset === this._cachedVOffset &&
  22946. this.uScale === this._cachedUScale &&
  22947. this.vScale === this._cachedVScale &&
  22948. this.coordinatesMode === this._cachedCoordinatesMode) {
  22949. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22950. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22951. return this._cachedTextureMatrix;
  22952. }
  22953. }
  22954. else {
  22955. return this._cachedTextureMatrix;
  22956. }
  22957. }
  22958. if (!this._cachedTextureMatrix) {
  22959. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22960. }
  22961. if (!this._projectionModeMatrix) {
  22962. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22963. }
  22964. this._cachedUOffset = this.uOffset;
  22965. this._cachedVOffset = this.vOffset;
  22966. this._cachedUScale = this.uScale;
  22967. this._cachedVScale = this.vScale;
  22968. this._cachedCoordinatesMode = this.coordinatesMode;
  22969. switch (this.coordinatesMode) {
  22970. case Texture.PLANAR_MODE:
  22971. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22972. this._cachedTextureMatrix[0] = this.uScale;
  22973. this._cachedTextureMatrix[5] = this.vScale;
  22974. this._cachedTextureMatrix[12] = this.uOffset;
  22975. this._cachedTextureMatrix[13] = this.vOffset;
  22976. break;
  22977. case Texture.PROJECTION_MODE:
  22978. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22979. this._projectionModeMatrix.m[0] = 0.5;
  22980. this._projectionModeMatrix.m[5] = -0.5;
  22981. this._projectionModeMatrix.m[10] = 0.0;
  22982. this._projectionModeMatrix.m[12] = 0.5;
  22983. this._projectionModeMatrix.m[13] = 0.5;
  22984. this._projectionModeMatrix.m[14] = 1.0;
  22985. this._projectionModeMatrix.m[15] = 1.0;
  22986. var projectionMatrix = scene.getProjectionMatrix();
  22987. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22988. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22989. break;
  22990. default:
  22991. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22992. break;
  22993. }
  22994. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22995. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22996. });
  22997. return this._cachedTextureMatrix;
  22998. };
  22999. Texture.prototype.clone = function () {
  23000. var _this = this;
  23001. return BABYLON.SerializationHelper.Clone(function () {
  23002. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23003. }, this);
  23004. };
  23005. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23006. get: function () {
  23007. if (!this._onLoadObservable) {
  23008. this._onLoadObservable = new BABYLON.Observable();
  23009. }
  23010. return this._onLoadObservable;
  23011. },
  23012. enumerable: true,
  23013. configurable: true
  23014. });
  23015. Texture.prototype.serialize = function () {
  23016. var serializationObject = _super.prototype.serialize.call(this);
  23017. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  23018. serializationObject.base64String = this._buffer;
  23019. serializationObject.name = serializationObject.name.replace("data:", "");
  23020. }
  23021. return serializationObject;
  23022. };
  23023. Texture.prototype.getClassName = function () {
  23024. return "Texture";
  23025. };
  23026. Texture.prototype.dispose = function () {
  23027. _super.prototype.dispose.call(this);
  23028. if (this.onLoadObservable) {
  23029. this.onLoadObservable.clear();
  23030. this._onLoadObservable = null;
  23031. }
  23032. this._delayedOnLoad = null;
  23033. this._delayedOnError = null;
  23034. };
  23035. // Statics
  23036. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23037. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23038. if (onLoad === void 0) { onLoad = null; }
  23039. if (onError === void 0) { onError = null; }
  23040. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23041. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  23042. };
  23043. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23044. if (parsedTexture.customType) {
  23045. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23046. // Update Sampling Mode
  23047. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  23048. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  23049. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  23050. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  23051. }
  23052. }
  23053. return parsedCustomTexture;
  23054. }
  23055. if (parsedTexture.isCube) {
  23056. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23057. }
  23058. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23059. return null;
  23060. }
  23061. var texture = BABYLON.SerializationHelper.Parse(function () {
  23062. var generateMipMaps = true;
  23063. if (parsedTexture.noMipmap) {
  23064. generateMipMaps = false;
  23065. }
  23066. if (parsedTexture.mirrorPlane) {
  23067. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23068. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23069. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23070. return mirrorTexture;
  23071. }
  23072. else if (parsedTexture.isRenderTarget) {
  23073. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23074. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23075. return renderTargetTexture;
  23076. }
  23077. else {
  23078. var texture;
  23079. if (parsedTexture.base64String) {
  23080. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  23081. }
  23082. else {
  23083. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  23084. }
  23085. return texture;
  23086. }
  23087. }, parsedTexture, scene);
  23088. // Update Sampling Mode
  23089. if (parsedTexture.samplingMode) {
  23090. var sampling = parsedTexture.samplingMode;
  23091. if (texture._samplingMode !== sampling) {
  23092. texture.updateSamplingMode(sampling);
  23093. }
  23094. }
  23095. // Animations
  23096. if (parsedTexture.animations) {
  23097. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23098. var parsedAnimation = parsedTexture.animations[animationIndex];
  23099. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23100. }
  23101. }
  23102. return texture;
  23103. };
  23104. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23105. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23106. if (noMipmap === void 0) { noMipmap = false; }
  23107. if (invertY === void 0) { invertY = true; }
  23108. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23109. if (onLoad === void 0) { onLoad = null; }
  23110. if (onError === void 0) { onError = null; }
  23111. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23112. if (name.substr(0, 5) !== "data:") {
  23113. name = "data:" + name;
  23114. }
  23115. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  23116. };
  23117. // Constants
  23118. Texture.NEAREST_SAMPLINGMODE = 1;
  23119. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  23120. Texture.BILINEAR_SAMPLINGMODE = 2;
  23121. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  23122. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23123. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  23124. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  23125. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  23126. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  23127. Texture.NEAREST_LINEAR = 7;
  23128. Texture.NEAREST_NEAREST = 8;
  23129. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  23130. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  23131. Texture.LINEAR_LINEAR = 11;
  23132. Texture.LINEAR_NEAREST = 12;
  23133. Texture.EXPLICIT_MODE = 0;
  23134. Texture.SPHERICAL_MODE = 1;
  23135. Texture.PLANAR_MODE = 2;
  23136. Texture.CUBIC_MODE = 3;
  23137. Texture.PROJECTION_MODE = 4;
  23138. Texture.SKYBOX_MODE = 5;
  23139. Texture.INVCUBIC_MODE = 6;
  23140. Texture.EQUIRECTANGULAR_MODE = 7;
  23141. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23142. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  23143. Texture.CLAMP_ADDRESSMODE = 0;
  23144. Texture.WRAP_ADDRESSMODE = 1;
  23145. Texture.MIRROR_ADDRESSMODE = 2;
  23146. __decorate([
  23147. BABYLON.serialize()
  23148. ], Texture.prototype, "url", void 0);
  23149. __decorate([
  23150. BABYLON.serialize()
  23151. ], Texture.prototype, "uOffset", void 0);
  23152. __decorate([
  23153. BABYLON.serialize()
  23154. ], Texture.prototype, "vOffset", void 0);
  23155. __decorate([
  23156. BABYLON.serialize()
  23157. ], Texture.prototype, "uScale", void 0);
  23158. __decorate([
  23159. BABYLON.serialize()
  23160. ], Texture.prototype, "vScale", void 0);
  23161. __decorate([
  23162. BABYLON.serialize()
  23163. ], Texture.prototype, "uAng", void 0);
  23164. __decorate([
  23165. BABYLON.serialize()
  23166. ], Texture.prototype, "vAng", void 0);
  23167. __decorate([
  23168. BABYLON.serialize()
  23169. ], Texture.prototype, "wAng", void 0);
  23170. __decorate([
  23171. BABYLON.serialize()
  23172. ], Texture.prototype, "isBlocking", null);
  23173. return Texture;
  23174. }(BABYLON.BaseTexture));
  23175. BABYLON.Texture = Texture;
  23176. })(BABYLON || (BABYLON = {}));
  23177. //# sourceMappingURL=babylon.texture.js.map
  23178. var BABYLON;
  23179. (function (BABYLON) {
  23180. var _InstancesBatch = /** @class */ (function () {
  23181. function _InstancesBatch() {
  23182. this.mustReturn = false;
  23183. this.visibleInstances = new Array();
  23184. this.renderSelf = new Array();
  23185. }
  23186. return _InstancesBatch;
  23187. }());
  23188. BABYLON._InstancesBatch = _InstancesBatch;
  23189. var Mesh = /** @class */ (function (_super) {
  23190. __extends(Mesh, _super);
  23191. /**
  23192. * @constructor
  23193. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23194. * @param {Scene} scene The scene to add this mesh to.
  23195. * @param {Node} parent The parent of this mesh, if it has one
  23196. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23197. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23198. * When false, achieved by calling a clone(), also passing False.
  23199. * This will make creation of children, recursive.
  23200. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23201. */
  23202. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23203. if (scene === void 0) { scene = null; }
  23204. if (parent === void 0) { parent = null; }
  23205. if (source === void 0) { source = null; }
  23206. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23207. var _this = _super.call(this, name, scene) || this;
  23208. // Events
  23209. /**
  23210. * An event triggered before rendering the mesh
  23211. * @type {BABYLON.Observable}
  23212. */
  23213. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23214. /**
  23215. * An event triggered after rendering the mesh
  23216. * @type {BABYLON.Observable}
  23217. */
  23218. _this.onAfterRenderObservable = new BABYLON.Observable();
  23219. /**
  23220. * An event triggered before drawing the mesh
  23221. * @type {BABYLON.Observable}
  23222. */
  23223. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23224. // Members
  23225. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23226. _this.instances = new Array();
  23227. _this._LODLevels = new Array();
  23228. _this._visibleInstances = {};
  23229. _this._renderIdForInstances = new Array();
  23230. _this._batchCache = new _InstancesBatch();
  23231. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23232. // Use by builder only to know what orientation were the mesh build in.
  23233. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23234. _this.overrideMaterialSideOrientation = null;
  23235. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23236. // Will be used to save a source mesh reference, If any
  23237. _this._source = null;
  23238. scene = _this.getScene();
  23239. if (source) {
  23240. // Source mesh
  23241. _this._source = source;
  23242. // Geometry
  23243. if (source._geometry) {
  23244. source._geometry.applyToMesh(_this);
  23245. }
  23246. // Deep copy
  23247. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23248. // Tags
  23249. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23250. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23251. }
  23252. _this.metadata = source.metadata;
  23253. // Parent
  23254. _this.parent = source.parent;
  23255. // Pivot
  23256. _this.setPivotMatrix(source.getPivotMatrix());
  23257. _this.id = name + "." + source.id;
  23258. // Material
  23259. _this.material = source.material;
  23260. var index;
  23261. if (!doNotCloneChildren) {
  23262. // Children
  23263. var directDescendants = source.getDescendants(true);
  23264. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23265. var child = directDescendants[index_1];
  23266. if (child.clone) {
  23267. child.clone(name + "." + child.name, _this);
  23268. }
  23269. }
  23270. }
  23271. // Physics clone
  23272. var physicsEngine = _this.getScene().getPhysicsEngine();
  23273. if (clonePhysicsImpostor && physicsEngine) {
  23274. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23275. if (impostor) {
  23276. _this.physicsImpostor = impostor.clone(_this);
  23277. }
  23278. }
  23279. // Particles
  23280. for (index = 0; index < scene.particleSystems.length; index++) {
  23281. var system = scene.particleSystems[index];
  23282. if (system.emitter === source) {
  23283. system.clone(system.name, _this);
  23284. }
  23285. }
  23286. _this.computeWorldMatrix(true);
  23287. }
  23288. // Parent
  23289. if (parent !== null) {
  23290. _this.parent = parent;
  23291. }
  23292. return _this;
  23293. }
  23294. Object.defineProperty(Mesh, "FRONTSIDE", {
  23295. /**
  23296. * Mesh side orientation : usually the external or front surface
  23297. */
  23298. get: function () {
  23299. return Mesh._FRONTSIDE;
  23300. },
  23301. enumerable: true,
  23302. configurable: true
  23303. });
  23304. Object.defineProperty(Mesh, "BACKSIDE", {
  23305. /**
  23306. * Mesh side orientation : usually the internal or back surface
  23307. */
  23308. get: function () {
  23309. return Mesh._BACKSIDE;
  23310. },
  23311. enumerable: true,
  23312. configurable: true
  23313. });
  23314. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23315. /**
  23316. * Mesh side orientation : both internal and external or front and back surfaces
  23317. */
  23318. get: function () {
  23319. return Mesh._DOUBLESIDE;
  23320. },
  23321. enumerable: true,
  23322. configurable: true
  23323. });
  23324. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23325. /**
  23326. * Mesh side orientation : by default, `FRONTSIDE`
  23327. */
  23328. get: function () {
  23329. return Mesh._DEFAULTSIDE;
  23330. },
  23331. enumerable: true,
  23332. configurable: true
  23333. });
  23334. Object.defineProperty(Mesh, "NO_CAP", {
  23335. /**
  23336. * Mesh cap setting : no cap
  23337. */
  23338. get: function () {
  23339. return Mesh._NO_CAP;
  23340. },
  23341. enumerable: true,
  23342. configurable: true
  23343. });
  23344. Object.defineProperty(Mesh, "CAP_START", {
  23345. /**
  23346. * Mesh cap setting : one cap at the beginning of the mesh
  23347. */
  23348. get: function () {
  23349. return Mesh._CAP_START;
  23350. },
  23351. enumerable: true,
  23352. configurable: true
  23353. });
  23354. Object.defineProperty(Mesh, "CAP_END", {
  23355. /**
  23356. * Mesh cap setting : one cap at the end of the mesh
  23357. */
  23358. get: function () {
  23359. return Mesh._CAP_END;
  23360. },
  23361. enumerable: true,
  23362. configurable: true
  23363. });
  23364. Object.defineProperty(Mesh, "CAP_ALL", {
  23365. /**
  23366. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23367. */
  23368. get: function () {
  23369. return Mesh._CAP_ALL;
  23370. },
  23371. enumerable: true,
  23372. configurable: true
  23373. });
  23374. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23375. set: function (callback) {
  23376. if (this._onBeforeDrawObserver) {
  23377. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23378. }
  23379. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23380. },
  23381. enumerable: true,
  23382. configurable: true
  23383. });
  23384. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23385. get: function () {
  23386. return this._morphTargetManager;
  23387. },
  23388. set: function (value) {
  23389. if (this._morphTargetManager === value) {
  23390. return;
  23391. }
  23392. this._morphTargetManager = value;
  23393. this._syncGeometryWithMorphTargetManager();
  23394. },
  23395. enumerable: true,
  23396. configurable: true
  23397. });
  23398. Object.defineProperty(Mesh.prototype, "source", {
  23399. get: function () {
  23400. return this._source;
  23401. },
  23402. enumerable: true,
  23403. configurable: true
  23404. });
  23405. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  23406. get: function () {
  23407. return this._unIndexed;
  23408. },
  23409. set: function (value) {
  23410. if (this._unIndexed !== value) {
  23411. this._unIndexed = value;
  23412. this._markSubMeshesAsAttributesDirty();
  23413. }
  23414. },
  23415. enumerable: true,
  23416. configurable: true
  23417. });
  23418. // Methods
  23419. /**
  23420. * Returns the string "Mesh".
  23421. */
  23422. Mesh.prototype.getClassName = function () {
  23423. return "Mesh";
  23424. };
  23425. /**
  23426. * Returns a string.
  23427. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23428. */
  23429. Mesh.prototype.toString = function (fullDetails) {
  23430. var ret = _super.prototype.toString.call(this, fullDetails);
  23431. ret += ", n vertices: " + this.getTotalVertices();
  23432. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23433. if (this.animations) {
  23434. for (var i = 0; i < this.animations.length; i++) {
  23435. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23436. }
  23437. }
  23438. if (fullDetails) {
  23439. if (this._geometry) {
  23440. var ib = this.getIndices();
  23441. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23442. if (vb && ib) {
  23443. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23444. }
  23445. }
  23446. else {
  23447. ret += ", flat shading: UNKNOWN";
  23448. }
  23449. }
  23450. return ret;
  23451. };
  23452. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23453. /**
  23454. * True if the mesh has some Levels Of Details (LOD).
  23455. * Returns a boolean.
  23456. */
  23457. get: function () {
  23458. return this._LODLevels.length > 0;
  23459. },
  23460. enumerable: true,
  23461. configurable: true
  23462. });
  23463. Mesh.prototype._sortLODLevels = function () {
  23464. this._LODLevels.sort(function (a, b) {
  23465. if (a.distance < b.distance) {
  23466. return 1;
  23467. }
  23468. if (a.distance > b.distance) {
  23469. return -1;
  23470. }
  23471. return 0;
  23472. });
  23473. };
  23474. /**
  23475. * Add a mesh as LOD level triggered at the given distance.
  23476. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23477. * @param {number} distance The distance from the center of the object to show this level
  23478. * @param {Mesh} mesh The mesh to be added as LOD level
  23479. * @return {Mesh} This mesh (for chaining)
  23480. */
  23481. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23482. if (mesh && mesh._masterMesh) {
  23483. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23484. return this;
  23485. }
  23486. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23487. this._LODLevels.push(level);
  23488. if (mesh) {
  23489. mesh._masterMesh = this;
  23490. }
  23491. this._sortLODLevels();
  23492. return this;
  23493. };
  23494. /**
  23495. * Returns the LOD level mesh at the passed distance or null if not found.
  23496. * It is related to the method `addLODLevel(distance, mesh)`.
  23497. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23498. * Returns an object Mesh or `null`.
  23499. */
  23500. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23501. for (var index = 0; index < this._LODLevels.length; index++) {
  23502. var level = this._LODLevels[index];
  23503. if (level.distance === distance) {
  23504. return level.mesh;
  23505. }
  23506. }
  23507. return null;
  23508. };
  23509. /**
  23510. * Remove a mesh from the LOD array
  23511. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23512. * @param {Mesh} mesh The mesh to be removed.
  23513. * @return {Mesh} This mesh (for chaining)
  23514. */
  23515. Mesh.prototype.removeLODLevel = function (mesh) {
  23516. for (var index = 0; index < this._LODLevels.length; index++) {
  23517. if (this._LODLevels[index].mesh === mesh) {
  23518. this._LODLevels.splice(index, 1);
  23519. if (mesh) {
  23520. mesh._masterMesh = null;
  23521. }
  23522. }
  23523. }
  23524. this._sortLODLevels();
  23525. return this;
  23526. };
  23527. /**
  23528. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23529. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23530. */
  23531. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23532. if (!this._LODLevels || this._LODLevels.length === 0) {
  23533. return this;
  23534. }
  23535. var bSphere;
  23536. if (boundingSphere) {
  23537. bSphere = boundingSphere;
  23538. }
  23539. else {
  23540. var boundingInfo = this.getBoundingInfo();
  23541. bSphere = boundingInfo.boundingSphere;
  23542. }
  23543. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23544. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23545. if (this.onLODLevelSelection) {
  23546. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23547. }
  23548. return this;
  23549. }
  23550. for (var index = 0; index < this._LODLevels.length; index++) {
  23551. var level = this._LODLevels[index];
  23552. if (level.distance < distanceToCamera) {
  23553. if (level.mesh) {
  23554. level.mesh._preActivate();
  23555. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23556. }
  23557. if (this.onLODLevelSelection) {
  23558. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23559. }
  23560. return level.mesh;
  23561. }
  23562. }
  23563. if (this.onLODLevelSelection) {
  23564. this.onLODLevelSelection(distanceToCamera, this, this);
  23565. }
  23566. return this;
  23567. };
  23568. Object.defineProperty(Mesh.prototype, "geometry", {
  23569. /**
  23570. * Returns the mesh internal Geometry object.
  23571. */
  23572. get: function () {
  23573. return this._geometry;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. /**
  23579. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23580. */
  23581. Mesh.prototype.getTotalVertices = function () {
  23582. if (!this._geometry) {
  23583. return 0;
  23584. }
  23585. return this._geometry.getTotalVertices();
  23586. };
  23587. /**
  23588. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23589. * 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.
  23590. * You can force the copy with forceCopy === true
  23591. * Returns null if the mesh has no geometry or no vertex buffer.
  23592. * Possible `kind` values :
  23593. * - BABYLON.VertexBuffer.PositionKind
  23594. * - BABYLON.VertexBuffer.UVKind
  23595. * - BABYLON.VertexBuffer.UV2Kind
  23596. * - BABYLON.VertexBuffer.UV3Kind
  23597. * - BABYLON.VertexBuffer.UV4Kind
  23598. * - BABYLON.VertexBuffer.UV5Kind
  23599. * - BABYLON.VertexBuffer.UV6Kind
  23600. * - BABYLON.VertexBuffer.ColorKind
  23601. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23602. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23603. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23604. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23605. */
  23606. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23607. if (!this._geometry) {
  23608. return null;
  23609. }
  23610. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23611. };
  23612. /**
  23613. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23614. * Returns `null` if the mesh has no geometry.
  23615. * Possible `kind` values :
  23616. * - BABYLON.VertexBuffer.PositionKind
  23617. * - BABYLON.VertexBuffer.UVKind
  23618. * - BABYLON.VertexBuffer.UV2Kind
  23619. * - BABYLON.VertexBuffer.UV3Kind
  23620. * - BABYLON.VertexBuffer.UV4Kind
  23621. * - BABYLON.VertexBuffer.UV5Kind
  23622. * - BABYLON.VertexBuffer.UV6Kind
  23623. * - BABYLON.VertexBuffer.ColorKind
  23624. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23625. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23626. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23627. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23628. */
  23629. Mesh.prototype.getVertexBuffer = function (kind) {
  23630. if (!this._geometry) {
  23631. return null;
  23632. }
  23633. return this._geometry.getVertexBuffer(kind);
  23634. };
  23635. /**
  23636. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23637. * Possible `kind` values :
  23638. * - BABYLON.VertexBuffer.PositionKind
  23639. * - BABYLON.VertexBuffer.UVKind
  23640. * - BABYLON.VertexBuffer.UV2Kind
  23641. * - BABYLON.VertexBuffer.UV3Kind
  23642. * - BABYLON.VertexBuffer.UV4Kind
  23643. * - BABYLON.VertexBuffer.UV5Kind
  23644. * - BABYLON.VertexBuffer.UV6Kind
  23645. * - BABYLON.VertexBuffer.ColorKind
  23646. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23647. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23648. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23649. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23650. */
  23651. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23652. if (!this._geometry) {
  23653. if (this._delayInfo) {
  23654. return this._delayInfo.indexOf(kind) !== -1;
  23655. }
  23656. return false;
  23657. }
  23658. return this._geometry.isVerticesDataPresent(kind);
  23659. };
  23660. /**
  23661. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23662. * Possible `kind` values :
  23663. * - BABYLON.VertexBuffer.PositionKind
  23664. * - BABYLON.VertexBuffer.UVKind
  23665. * - BABYLON.VertexBuffer.UV2Kind
  23666. * - BABYLON.VertexBuffer.UV3Kind
  23667. * - BABYLON.VertexBuffer.UV4Kind
  23668. * - BABYLON.VertexBuffer.UV5Kind
  23669. * - BABYLON.VertexBuffer.UV6Kind
  23670. * - BABYLON.VertexBuffer.ColorKind
  23671. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23672. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23673. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23674. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23675. */
  23676. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23677. if (!this._geometry) {
  23678. if (this._delayInfo) {
  23679. return this._delayInfo.indexOf(kind) !== -1;
  23680. }
  23681. return false;
  23682. }
  23683. return this._geometry.isVertexBufferUpdatable(kind);
  23684. };
  23685. /**
  23686. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23687. * Possible `kind` values :
  23688. * - BABYLON.VertexBuffer.PositionKind
  23689. * - BABYLON.VertexBuffer.UVKind
  23690. * - BABYLON.VertexBuffer.UV2Kind
  23691. * - BABYLON.VertexBuffer.UV3Kind
  23692. * - BABYLON.VertexBuffer.UV4Kind
  23693. * - BABYLON.VertexBuffer.UV5Kind
  23694. * - BABYLON.VertexBuffer.UV6Kind
  23695. * - BABYLON.VertexBuffer.ColorKind
  23696. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23697. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23698. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23699. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23700. */
  23701. Mesh.prototype.getVerticesDataKinds = function () {
  23702. if (!this._geometry) {
  23703. var result = new Array();
  23704. if (this._delayInfo) {
  23705. this._delayInfo.forEach(function (kind, index, array) {
  23706. result.push(kind);
  23707. });
  23708. }
  23709. return result;
  23710. }
  23711. return this._geometry.getVerticesDataKinds();
  23712. };
  23713. /**
  23714. * Returns a positive integer : the total number of indices in this mesh geometry.
  23715. * Returns zero if the mesh has no geometry.
  23716. */
  23717. Mesh.prototype.getTotalIndices = function () {
  23718. if (!this._geometry) {
  23719. return 0;
  23720. }
  23721. return this._geometry.getTotalIndices();
  23722. };
  23723. /**
  23724. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23725. * 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.
  23726. * Returns an empty array if the mesh has no geometry.
  23727. */
  23728. Mesh.prototype.getIndices = function (copyWhenShared) {
  23729. if (!this._geometry) {
  23730. return [];
  23731. }
  23732. return this._geometry.getIndices(copyWhenShared);
  23733. };
  23734. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23735. get: function () {
  23736. return this._masterMesh !== null && this._masterMesh !== undefined;
  23737. },
  23738. enumerable: true,
  23739. configurable: true
  23740. });
  23741. /**
  23742. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23743. */
  23744. Mesh.prototype.isReady = function () {
  23745. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23746. return false;
  23747. }
  23748. return _super.prototype.isReady.call(this);
  23749. };
  23750. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23751. /**
  23752. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23753. * This property is pertinent only for updatable parametric shapes.
  23754. */
  23755. get: function () {
  23756. return this._areNormalsFrozen;
  23757. },
  23758. enumerable: true,
  23759. configurable: true
  23760. });
  23761. /**
  23762. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23763. * It has no effect at all on other shapes.
  23764. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23765. * Returns the Mesh.
  23766. */
  23767. Mesh.prototype.freezeNormals = function () {
  23768. this._areNormalsFrozen = true;
  23769. return this;
  23770. };
  23771. /**
  23772. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23773. * It has no effect at all on other shapes.
  23774. * It reactivates the mesh normals computation if it was previously frozen.
  23775. * Returns the Mesh.
  23776. */
  23777. Mesh.prototype.unfreezeNormals = function () {
  23778. this._areNormalsFrozen = false;
  23779. return this;
  23780. };
  23781. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23782. /**
  23783. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23784. */
  23785. set: function (count) {
  23786. this._overridenInstanceCount = count;
  23787. },
  23788. enumerable: true,
  23789. configurable: true
  23790. });
  23791. // Methods
  23792. Mesh.prototype._preActivate = function () {
  23793. var sceneRenderId = this.getScene().getRenderId();
  23794. if (this._preActivateId === sceneRenderId) {
  23795. return this;
  23796. }
  23797. this._preActivateId = sceneRenderId;
  23798. this._visibleInstances = null;
  23799. return this;
  23800. };
  23801. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23802. if (this._visibleInstances) {
  23803. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23804. }
  23805. return this;
  23806. };
  23807. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23808. if (!this._visibleInstances) {
  23809. this._visibleInstances = {};
  23810. this._visibleInstances.defaultRenderId = renderId;
  23811. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23812. }
  23813. if (!this._visibleInstances[renderId]) {
  23814. this._visibleInstances[renderId] = new Array();
  23815. }
  23816. this._visibleInstances[renderId].push(instance);
  23817. return this;
  23818. };
  23819. /**
  23820. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23821. * This means the mesh underlying bounding box and sphere are recomputed.
  23822. * Returns the Mesh.
  23823. */
  23824. Mesh.prototype.refreshBoundingInfo = function () {
  23825. return this._refreshBoundingInfo(false);
  23826. };
  23827. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  23828. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23829. return this;
  23830. }
  23831. var data = this._getPositionData(applySkeleton);
  23832. if (data) {
  23833. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23834. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23835. }
  23836. if (this.subMeshes) {
  23837. for (var index = 0; index < this.subMeshes.length; index++) {
  23838. this.subMeshes[index].refreshBoundingInfo();
  23839. }
  23840. }
  23841. this._updateBoundingInfo();
  23842. return this;
  23843. };
  23844. Mesh.prototype._getPositionData = function (applySkeleton) {
  23845. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23846. if (data && applySkeleton && this.skeleton) {
  23847. data = data.slice();
  23848. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23849. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23850. if (matricesWeightsData && matricesIndicesData) {
  23851. var needExtras = this.numBoneInfluencers > 4;
  23852. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23853. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23854. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  23855. var tempVector = BABYLON.Tmp.Vector3[0];
  23856. var finalMatrix = BABYLON.Tmp.Matrix[0];
  23857. var tempMatrix = BABYLON.Tmp.Matrix[1];
  23858. var matWeightIdx = 0;
  23859. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  23860. finalMatrix.reset();
  23861. var inf;
  23862. var weight;
  23863. for (inf = 0; inf < 4; inf++) {
  23864. weight = matricesWeightsData[matWeightIdx + inf];
  23865. if (weight <= 0)
  23866. break;
  23867. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23868. finalMatrix.addToSelf(tempMatrix);
  23869. }
  23870. if (needExtras) {
  23871. for (inf = 0; inf < 4; inf++) {
  23872. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23873. if (weight <= 0)
  23874. break;
  23875. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23876. finalMatrix.addToSelf(tempMatrix);
  23877. }
  23878. }
  23879. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  23880. tempVector.toArray(data, index);
  23881. }
  23882. }
  23883. }
  23884. return data;
  23885. };
  23886. Mesh.prototype._createGlobalSubMesh = function (force) {
  23887. var totalVertices = this.getTotalVertices();
  23888. if (!totalVertices || !this.getIndices()) {
  23889. return null;
  23890. }
  23891. // Check if we need to recreate the submeshes
  23892. if (this.subMeshes && this.subMeshes.length > 0) {
  23893. var ib = this.getIndices();
  23894. if (!ib) {
  23895. return null;
  23896. }
  23897. var totalIndices = ib.length;
  23898. var needToRecreate = false;
  23899. if (force) {
  23900. needToRecreate = true;
  23901. }
  23902. else {
  23903. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23904. var submesh = _a[_i];
  23905. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23906. needToRecreate = true;
  23907. break;
  23908. }
  23909. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23910. needToRecreate = true;
  23911. break;
  23912. }
  23913. }
  23914. }
  23915. if (!needToRecreate) {
  23916. return this.subMeshes[0];
  23917. }
  23918. }
  23919. this.releaseSubMeshes();
  23920. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23921. };
  23922. Mesh.prototype.subdivide = function (count) {
  23923. if (count < 1) {
  23924. return;
  23925. }
  23926. var totalIndices = this.getTotalIndices();
  23927. var subdivisionSize = (totalIndices / count) | 0;
  23928. var offset = 0;
  23929. // Ensure that subdivisionSize is a multiple of 3
  23930. while (subdivisionSize % 3 !== 0) {
  23931. subdivisionSize++;
  23932. }
  23933. this.releaseSubMeshes();
  23934. for (var index = 0; index < count; index++) {
  23935. if (offset >= totalIndices) {
  23936. break;
  23937. }
  23938. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23939. offset += subdivisionSize;
  23940. }
  23941. this.synchronizeInstances();
  23942. };
  23943. /**
  23944. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23945. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23946. * The `data` are either a numeric array either a Float32Array.
  23947. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23948. * 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).
  23949. * Note that a new underlying VertexBuffer object is created each call.
  23950. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23951. *
  23952. * Possible `kind` values :
  23953. * - BABYLON.VertexBuffer.PositionKind
  23954. * - BABYLON.VertexBuffer.UVKind
  23955. * - BABYLON.VertexBuffer.UV2Kind
  23956. * - BABYLON.VertexBuffer.UV3Kind
  23957. * - BABYLON.VertexBuffer.UV4Kind
  23958. * - BABYLON.VertexBuffer.UV5Kind
  23959. * - BABYLON.VertexBuffer.UV6Kind
  23960. * - BABYLON.VertexBuffer.ColorKind
  23961. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23962. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23963. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23964. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23965. *
  23966. * Returns the Mesh.
  23967. */
  23968. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23969. if (updatable === void 0) { updatable = false; }
  23970. if (!this._geometry) {
  23971. var vertexData = new BABYLON.VertexData();
  23972. vertexData.set(data, kind);
  23973. var scene = this.getScene();
  23974. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23975. }
  23976. else {
  23977. this._geometry.setVerticesData(kind, data, updatable, stride);
  23978. }
  23979. return this;
  23980. };
  23981. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23982. if (updatable === void 0) { updatable = true; }
  23983. var vb = this.getVertexBuffer(kind);
  23984. if (!vb || vb.isUpdatable() === updatable) {
  23985. return;
  23986. }
  23987. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23988. };
  23989. /**
  23990. * Sets the mesh VertexBuffer.
  23991. * Returns the Mesh.
  23992. */
  23993. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23994. if (!this._geometry) {
  23995. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23996. }
  23997. this._geometry.setVerticesBuffer(buffer);
  23998. return this;
  23999. };
  24000. /**
  24001. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24002. * If the mesh has no geometry, it is simply returned as it is.
  24003. * The `data` are either a numeric array either a Float32Array.
  24004. * No new underlying VertexBuffer object is created.
  24005. * 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.
  24006. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24007. *
  24008. * Possible `kind` values :
  24009. * - BABYLON.VertexBuffer.PositionKind
  24010. * - BABYLON.VertexBuffer.UVKind
  24011. * - BABYLON.VertexBuffer.UV2Kind
  24012. * - BABYLON.VertexBuffer.UV3Kind
  24013. * - BABYLON.VertexBuffer.UV4Kind
  24014. * - BABYLON.VertexBuffer.UV5Kind
  24015. * - BABYLON.VertexBuffer.UV6Kind
  24016. * - BABYLON.VertexBuffer.ColorKind
  24017. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24018. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24019. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24020. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24021. *
  24022. * Returns the Mesh.
  24023. */
  24024. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24025. if (!this._geometry) {
  24026. return this;
  24027. }
  24028. if (!makeItUnique) {
  24029. this._geometry.updateVerticesData(kind, data, updateExtends);
  24030. }
  24031. else {
  24032. this.makeGeometryUnique();
  24033. this.updateVerticesData(kind, data, updateExtends, false);
  24034. }
  24035. return this;
  24036. };
  24037. /**
  24038. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24039. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24040. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24041. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24042. * Returns the Mesh.
  24043. */
  24044. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24045. if (computeNormals === void 0) { computeNormals = true; }
  24046. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24047. if (!positions) {
  24048. return this;
  24049. }
  24050. positionFunction(positions);
  24051. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24052. if (computeNormals) {
  24053. var indices = this.getIndices();
  24054. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24055. if (!normals) {
  24056. return this;
  24057. }
  24058. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24059. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24060. }
  24061. return this;
  24062. };
  24063. /**
  24064. * Creates a un-shared specific occurence of the geometry for the mesh.
  24065. * Returns the Mesh.
  24066. */
  24067. Mesh.prototype.makeGeometryUnique = function () {
  24068. if (!this._geometry) {
  24069. return this;
  24070. }
  24071. var oldGeometry = this._geometry;
  24072. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24073. oldGeometry.releaseForMesh(this, true);
  24074. geometry.applyToMesh(this);
  24075. return this;
  24076. };
  24077. /**
  24078. * Sets the mesh indices.
  24079. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24080. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  24081. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24082. * This method creates a new index buffer each call.
  24083. * Returns the Mesh.
  24084. */
  24085. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  24086. if (totalVertices === void 0) { totalVertices = null; }
  24087. if (updatable === void 0) { updatable = false; }
  24088. if (!this._geometry) {
  24089. var vertexData = new BABYLON.VertexData();
  24090. vertexData.indices = indices;
  24091. var scene = this.getScene();
  24092. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24093. }
  24094. else {
  24095. this._geometry.setIndices(indices, totalVertices, updatable);
  24096. }
  24097. return this;
  24098. };
  24099. /**
  24100. * Update the current index buffer
  24101. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  24102. * Returns the Mesh.
  24103. */
  24104. Mesh.prototype.updateIndices = function (indices, offset) {
  24105. if (!this._geometry) {
  24106. return this;
  24107. }
  24108. this._geometry.updateIndices(indices, offset);
  24109. return this;
  24110. };
  24111. /**
  24112. * Invert the geometry to move from a right handed system to a left handed one.
  24113. * Returns the Mesh.
  24114. */
  24115. Mesh.prototype.toLeftHanded = function () {
  24116. if (!this._geometry) {
  24117. return this;
  24118. }
  24119. this._geometry.toLeftHanded();
  24120. return this;
  24121. };
  24122. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24123. if (!this._geometry) {
  24124. return this;
  24125. }
  24126. var engine = this.getScene().getEngine();
  24127. // Wireframe
  24128. var indexToBind;
  24129. if (this._unIndexed) {
  24130. indexToBind = null;
  24131. }
  24132. else {
  24133. switch (fillMode) {
  24134. case BABYLON.Material.PointFillMode:
  24135. indexToBind = null;
  24136. break;
  24137. case BABYLON.Material.WireFrameFillMode:
  24138. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24139. break;
  24140. default:
  24141. case BABYLON.Material.TriangleFillMode:
  24142. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24143. break;
  24144. }
  24145. }
  24146. // VBOs
  24147. this._geometry._bind(effect, indexToBind);
  24148. return this;
  24149. };
  24150. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  24151. if (alternate === void 0) { alternate = false; }
  24152. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24153. return this;
  24154. }
  24155. this.onBeforeDrawObservable.notifyObservers(this);
  24156. var scene = this.getScene();
  24157. var engine = scene.getEngine();
  24158. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  24159. // or triangles as points
  24160. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24161. }
  24162. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  24163. // Triangles as wireframe
  24164. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  24165. }
  24166. else {
  24167. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24168. }
  24169. if (scene._isAlternateRenderingEnabled && !alternate) {
  24170. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  24171. if (!effect || !scene.activeCamera) {
  24172. return this;
  24173. }
  24174. scene._switchToAlternateCameraConfiguration(true);
  24175. this._effectiveMaterial.bindView(effect);
  24176. this._effectiveMaterial.bindViewProjection(effect);
  24177. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  24178. this._draw(subMesh, fillMode, instancesCount, true);
  24179. engine.setViewport(scene.activeCamera.viewport);
  24180. scene._switchToAlternateCameraConfiguration(false);
  24181. this._effectiveMaterial.bindView(effect);
  24182. this._effectiveMaterial.bindViewProjection(effect);
  24183. }
  24184. return this;
  24185. };
  24186. /**
  24187. * Registers for this mesh a javascript function called just before the rendering process.
  24188. * This function is passed the current mesh.
  24189. * Return the Mesh.
  24190. */
  24191. Mesh.prototype.registerBeforeRender = function (func) {
  24192. this.onBeforeRenderObservable.add(func);
  24193. return this;
  24194. };
  24195. /**
  24196. * Disposes a previously registered javascript function called before the rendering.
  24197. * This function is passed the current mesh.
  24198. * Returns the Mesh.
  24199. */
  24200. Mesh.prototype.unregisterBeforeRender = function (func) {
  24201. this.onBeforeRenderObservable.removeCallback(func);
  24202. return this;
  24203. };
  24204. /**
  24205. * Registers for this mesh a javascript function called just after the rendering is complete.
  24206. * This function is passed the current mesh.
  24207. * Returns the Mesh.
  24208. */
  24209. Mesh.prototype.registerAfterRender = function (func) {
  24210. this.onAfterRenderObservable.add(func);
  24211. return this;
  24212. };
  24213. /**
  24214. * Disposes a previously registered javascript function called after the rendering.
  24215. * This function is passed the current mesh.
  24216. * Return the Mesh.
  24217. */
  24218. Mesh.prototype.unregisterAfterRender = function (func) {
  24219. this.onAfterRenderObservable.removeCallback(func);
  24220. return this;
  24221. };
  24222. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24223. var scene = this.getScene();
  24224. this._batchCache.mustReturn = false;
  24225. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24226. this._batchCache.visibleInstances[subMeshId] = null;
  24227. if (this._visibleInstances) {
  24228. var currentRenderId = scene.getRenderId();
  24229. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24230. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24231. var selfRenderId = this._renderId;
  24232. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24233. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24234. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24235. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24236. }
  24237. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24238. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24239. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24240. this._batchCache.mustReturn = true;
  24241. return this._batchCache;
  24242. }
  24243. if (currentRenderId !== selfRenderId) {
  24244. this._batchCache.renderSelf[subMeshId] = false;
  24245. }
  24246. }
  24247. this._renderIdForInstances[subMeshId] = currentRenderId;
  24248. }
  24249. return this._batchCache;
  24250. };
  24251. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24252. var visibleInstances = batch.visibleInstances[subMesh._id];
  24253. if (!visibleInstances) {
  24254. return this;
  24255. }
  24256. var matricesCount = visibleInstances.length + 1;
  24257. var bufferSize = matricesCount * 16 * 4;
  24258. var currentInstancesBufferSize = this._instancesBufferSize;
  24259. var instancesBuffer = this._instancesBuffer;
  24260. while (this._instancesBufferSize < bufferSize) {
  24261. this._instancesBufferSize *= 2;
  24262. }
  24263. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24264. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24265. }
  24266. var offset = 0;
  24267. var instancesCount = 0;
  24268. var world = this.getWorldMatrix();
  24269. if (batch.renderSelf[subMesh._id]) {
  24270. world.copyToArray(this._instancesData, offset);
  24271. offset += 16;
  24272. instancesCount++;
  24273. }
  24274. if (visibleInstances) {
  24275. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24276. var instance = visibleInstances[instanceIndex];
  24277. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24278. offset += 16;
  24279. instancesCount++;
  24280. }
  24281. }
  24282. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24283. if (instancesBuffer) {
  24284. instancesBuffer.dispose();
  24285. }
  24286. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24287. this._instancesBuffer = instancesBuffer;
  24288. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24289. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24290. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24291. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24292. }
  24293. else {
  24294. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24295. }
  24296. this._bind(subMesh, effect, fillMode);
  24297. this._draw(subMesh, fillMode, instancesCount);
  24298. engine.unbindInstanceAttributes();
  24299. return this;
  24300. };
  24301. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24302. var scene = this.getScene();
  24303. var engine = scene.getEngine();
  24304. if (hardwareInstancedRendering) {
  24305. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24306. }
  24307. else {
  24308. if (batch.renderSelf[subMesh._id]) {
  24309. // Draw
  24310. if (onBeforeDraw) {
  24311. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24312. }
  24313. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24314. }
  24315. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24316. if (visibleInstancesForSubMesh) {
  24317. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24318. var instance = visibleInstancesForSubMesh[instanceIndex];
  24319. // World
  24320. var world = instance.getWorldMatrix();
  24321. if (onBeforeDraw) {
  24322. onBeforeDraw(true, world, effectiveMaterial);
  24323. }
  24324. // Draw
  24325. this._draw(subMesh, fillMode);
  24326. }
  24327. }
  24328. }
  24329. return this;
  24330. };
  24331. /**
  24332. * Triggers the draw call for the mesh.
  24333. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24334. * Returns the Mesh.
  24335. */
  24336. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24337. this.checkOcclusionQuery();
  24338. if (this._isOccluded) {
  24339. return this;
  24340. }
  24341. var scene = this.getScene();
  24342. // Managing instances
  24343. var batch = this._getInstancesRenderList(subMesh._id);
  24344. if (batch.mustReturn) {
  24345. return this;
  24346. }
  24347. // Checking geometry state
  24348. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24349. return this;
  24350. }
  24351. this.onBeforeRenderObservable.notifyObservers(this);
  24352. var engine = scene.getEngine();
  24353. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24354. // Material
  24355. var material = subMesh.getMaterial();
  24356. if (!material) {
  24357. return this;
  24358. }
  24359. this._effectiveMaterial = material;
  24360. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24361. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24362. return this;
  24363. }
  24364. }
  24365. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24366. return this;
  24367. }
  24368. // Alpha mode
  24369. if (enableAlphaMode) {
  24370. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24371. }
  24372. // Outline - step 1
  24373. var savedDepthWrite = engine.getDepthWrite();
  24374. if (this.renderOutline) {
  24375. engine.setDepthWrite(false);
  24376. scene.getOutlineRenderer().render(subMesh, batch);
  24377. engine.setDepthWrite(savedDepthWrite);
  24378. }
  24379. var effect;
  24380. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24381. effect = subMesh.effect;
  24382. }
  24383. else {
  24384. effect = this._effectiveMaterial.getEffect();
  24385. }
  24386. if (!effect) {
  24387. return this;
  24388. }
  24389. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  24390. if (this._effectiveMaterial.forceDepthWrite) {
  24391. engine.setDepthWrite(true);
  24392. }
  24393. // Bind
  24394. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24395. if (!hardwareInstancedRendering) {
  24396. this._bind(subMesh, effect, fillMode);
  24397. }
  24398. var world = this.getWorldMatrix();
  24399. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24400. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24401. }
  24402. else {
  24403. this._effectiveMaterial.bind(world, this);
  24404. }
  24405. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24406. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24407. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24408. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24409. }
  24410. // Draw
  24411. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24412. // Unbind
  24413. this._effectiveMaterial.unbind();
  24414. // Outline - step 2
  24415. if (this.renderOutline && savedDepthWrite) {
  24416. engine.setDepthWrite(true);
  24417. engine.setColorWrite(false);
  24418. scene.getOutlineRenderer().render(subMesh, batch);
  24419. engine.setColorWrite(true);
  24420. }
  24421. // Overlay
  24422. if (this.renderOverlay) {
  24423. var currentMode = engine.getAlphaMode();
  24424. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24425. scene.getOutlineRenderer().render(subMesh, batch, true);
  24426. engine.setAlphaMode(currentMode);
  24427. }
  24428. this.onAfterRenderObservable.notifyObservers(this);
  24429. return this;
  24430. };
  24431. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24432. if (isInstance && effectiveMaterial) {
  24433. effectiveMaterial.bindOnlyWorldMatrix(world);
  24434. }
  24435. };
  24436. /**
  24437. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24438. */
  24439. Mesh.prototype.getEmittedParticleSystems = function () {
  24440. var results = new Array();
  24441. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24442. var particleSystem = this.getScene().particleSystems[index];
  24443. if (particleSystem.emitter === this) {
  24444. results.push(particleSystem);
  24445. }
  24446. }
  24447. return results;
  24448. };
  24449. /**
  24450. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24451. */
  24452. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24453. var results = new Array();
  24454. var descendants = this.getDescendants();
  24455. descendants.push(this);
  24456. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24457. var particleSystem = this.getScene().particleSystems[index];
  24458. var emitter = particleSystem.emitter;
  24459. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24460. results.push(particleSystem);
  24461. }
  24462. }
  24463. return results;
  24464. };
  24465. Mesh.prototype._checkDelayState = function () {
  24466. var scene = this.getScene();
  24467. if (this._geometry) {
  24468. this._geometry.load(scene);
  24469. }
  24470. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24471. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24472. this._queueLoad(scene);
  24473. }
  24474. return this;
  24475. };
  24476. Mesh.prototype._queueLoad = function (scene) {
  24477. var _this = this;
  24478. scene._addPendingData(this);
  24479. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24480. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24481. if (data instanceof ArrayBuffer) {
  24482. _this._delayLoadingFunction(data, _this);
  24483. }
  24484. else {
  24485. _this._delayLoadingFunction(JSON.parse(data), _this);
  24486. }
  24487. _this.instances.forEach(function (instance) {
  24488. instance._syncSubMeshes();
  24489. });
  24490. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24491. scene._removePendingData(_this);
  24492. }, function () { }, scene.database, getBinaryData);
  24493. return this;
  24494. };
  24495. /**
  24496. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24497. */
  24498. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24499. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24500. return false;
  24501. }
  24502. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24503. return false;
  24504. }
  24505. this._checkDelayState();
  24506. return true;
  24507. };
  24508. /**
  24509. * Sets the mesh material by the material or multiMaterial `id` property.
  24510. * The material `id` is a string identifying the material or the multiMaterial.
  24511. * This method returns the Mesh.
  24512. */
  24513. Mesh.prototype.setMaterialByID = function (id) {
  24514. var materials = this.getScene().materials;
  24515. var index;
  24516. for (index = materials.length - 1; index > -1; index--) {
  24517. if (materials[index].id === id) {
  24518. this.material = materials[index];
  24519. return this;
  24520. }
  24521. }
  24522. // Multi
  24523. var multiMaterials = this.getScene().multiMaterials;
  24524. for (index = multiMaterials.length - 1; index > -1; index--) {
  24525. if (multiMaterials[index].id === id) {
  24526. this.material = multiMaterials[index];
  24527. return this;
  24528. }
  24529. }
  24530. return this;
  24531. };
  24532. /**
  24533. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24534. */
  24535. Mesh.prototype.getAnimatables = function () {
  24536. var results = new Array();
  24537. if (this.material) {
  24538. results.push(this.material);
  24539. }
  24540. if (this.skeleton) {
  24541. results.push(this.skeleton);
  24542. }
  24543. return results;
  24544. };
  24545. /**
  24546. * Modifies the mesh geometry according to the passed transformation matrix.
  24547. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24548. * The mesh normals are modified accordingly the same transformation.
  24549. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24550. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24551. * Returns the Mesh.
  24552. */
  24553. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24554. // Position
  24555. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24556. return this;
  24557. }
  24558. var submeshes = this.subMeshes.splice(0);
  24559. this._resetPointsArrayCache();
  24560. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24561. var temp = new Array();
  24562. var index;
  24563. for (index = 0; index < data.length; index += 3) {
  24564. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24565. }
  24566. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24567. // Normals
  24568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24569. return this;
  24570. }
  24571. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24572. temp = [];
  24573. for (index = 0; index < data.length; index += 3) {
  24574. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24575. }
  24576. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24577. // flip faces?
  24578. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24579. this.flipFaces();
  24580. }
  24581. // Restore submeshes
  24582. this.releaseSubMeshes();
  24583. this.subMeshes = submeshes;
  24584. return this;
  24585. };
  24586. /**
  24587. * Modifies the mesh geometry according to its own current World Matrix.
  24588. * The mesh World Matrix is then reset.
  24589. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24590. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  24591. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24592. * Returns the Mesh.
  24593. */
  24594. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24595. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24596. this.scaling.copyFromFloats(1, 1, 1);
  24597. this.position.copyFromFloats(0, 0, 0);
  24598. this.rotation.copyFromFloats(0, 0, 0);
  24599. //only if quaternion is already set
  24600. if (this.rotationQuaternion) {
  24601. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24602. }
  24603. this._worldMatrix = BABYLON.Matrix.Identity();
  24604. return this;
  24605. };
  24606. Object.defineProperty(Mesh.prototype, "_positions", {
  24607. // Cache
  24608. get: function () {
  24609. if (this._geometry) {
  24610. return this._geometry._positions;
  24611. }
  24612. return null;
  24613. },
  24614. enumerable: true,
  24615. configurable: true
  24616. });
  24617. Mesh.prototype._resetPointsArrayCache = function () {
  24618. if (this._geometry) {
  24619. this._geometry._resetPointsArrayCache();
  24620. }
  24621. return this;
  24622. };
  24623. Mesh.prototype._generatePointsArray = function () {
  24624. if (this._geometry) {
  24625. return this._geometry._generatePointsArray();
  24626. }
  24627. return false;
  24628. };
  24629. /**
  24630. * Returns a new Mesh object generated from the current mesh properties.
  24631. * This method must not get confused with createInstance().
  24632. * The parameter `name` is a string, the name given to the new mesh.
  24633. * The optional parameter `newParent` can be any Node object (default `null`).
  24634. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24635. * 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.
  24636. */
  24637. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24638. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24639. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24640. };
  24641. /**
  24642. * Disposes the Mesh.
  24643. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24644. * Returns nothing.
  24645. */
  24646. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24647. var _this = this;
  24648. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24649. this.morphTargetManager = null;
  24650. if (this._geometry) {
  24651. this._geometry.releaseForMesh(this, true);
  24652. }
  24653. // Sources
  24654. var meshes = this.getScene().meshes;
  24655. meshes.forEach(function (abstractMesh) {
  24656. var mesh = abstractMesh;
  24657. if (mesh._source && mesh._source === _this) {
  24658. mesh._source = null;
  24659. }
  24660. });
  24661. this._source = null;
  24662. // Instances
  24663. if (this._instancesBuffer) {
  24664. this._instancesBuffer.dispose();
  24665. this._instancesBuffer = null;
  24666. }
  24667. while (this.instances.length) {
  24668. this.instances[0].dispose();
  24669. }
  24670. // Highlight layers.
  24671. var highlightLayers = this.getScene().highlightLayers;
  24672. for (var i = 0; i < highlightLayers.length; i++) {
  24673. var highlightLayer = highlightLayers[i];
  24674. if (highlightLayer) {
  24675. highlightLayer.removeMesh(this);
  24676. highlightLayer.removeExcludedMesh(this);
  24677. }
  24678. }
  24679. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24680. };
  24681. /**
  24682. * Modifies the mesh geometry according to a displacement map.
  24683. * 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.
  24684. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24685. * This method returns nothing.
  24686. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24687. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24688. * 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.
  24689. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24690. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24691. *
  24692. * Returns the Mesh.
  24693. */
  24694. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24695. var _this = this;
  24696. var scene = this.getScene();
  24697. var onload = function (img) {
  24698. // Getting height map data
  24699. var canvas = document.createElement("canvas");
  24700. var context = canvas.getContext("2d");
  24701. var heightMapWidth = img.width;
  24702. var heightMapHeight = img.height;
  24703. canvas.width = heightMapWidth;
  24704. canvas.height = heightMapHeight;
  24705. context.drawImage(img, 0, 0);
  24706. // Create VertexData from map data
  24707. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24708. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24709. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24710. //execute success callback, if set
  24711. if (onSuccess) {
  24712. onSuccess(_this);
  24713. }
  24714. };
  24715. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24716. return this;
  24717. };
  24718. /**
  24719. * Modifies the mesh geometry according to a displacementMap buffer.
  24720. * 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.
  24721. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24722. * This method returns nothing.
  24723. * 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.
  24724. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24725. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24726. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24727. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24728. *
  24729. * Returns the Mesh.
  24730. */
  24731. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24733. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24734. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24735. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24736. return this;
  24737. }
  24738. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24739. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24740. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24741. var position = BABYLON.Vector3.Zero();
  24742. var normal = BABYLON.Vector3.Zero();
  24743. var uv = BABYLON.Vector2.Zero();
  24744. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24745. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24746. for (var index = 0; index < positions.length; index += 3) {
  24747. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24748. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24749. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24750. // Compute height
  24751. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24752. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24753. var pos = (u + v * heightMapWidth) * 4;
  24754. var r = buffer[pos] / 255.0;
  24755. var g = buffer[pos + 1] / 255.0;
  24756. var b = buffer[pos + 2] / 255.0;
  24757. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24758. normal.normalize();
  24759. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24760. position = position.add(normal);
  24761. position.toArray(positions, index);
  24762. }
  24763. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24764. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24765. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24766. return this;
  24767. };
  24768. /**
  24769. * Modify the mesh to get a flat shading rendering.
  24770. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24771. * This method returns the Mesh.
  24772. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24773. */
  24774. Mesh.prototype.convertToFlatShadedMesh = function () {
  24775. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24776. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24777. var kinds = this.getVerticesDataKinds();
  24778. var vbs = {};
  24779. var data = {};
  24780. var newdata = {};
  24781. var updatableNormals = false;
  24782. var kindIndex;
  24783. var kind;
  24784. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24785. kind = kinds[kindIndex];
  24786. var vertexBuffer = this.getVertexBuffer(kind);
  24787. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24788. updatableNormals = vertexBuffer.isUpdatable();
  24789. kinds.splice(kindIndex, 1);
  24790. kindIndex--;
  24791. continue;
  24792. }
  24793. vbs[kind] = vertexBuffer;
  24794. data[kind] = vbs[kind].getData();
  24795. newdata[kind] = [];
  24796. }
  24797. // Save previous submeshes
  24798. var previousSubmeshes = this.subMeshes.slice(0);
  24799. var indices = this.getIndices();
  24800. var totalIndices = this.getTotalIndices();
  24801. // Generating unique vertices per face
  24802. var index;
  24803. for (index = 0; index < totalIndices; index++) {
  24804. var vertexIndex = indices[index];
  24805. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24806. kind = kinds[kindIndex];
  24807. var stride = vbs[kind].getStrideSize();
  24808. for (var offset = 0; offset < stride; offset++) {
  24809. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24810. }
  24811. }
  24812. }
  24813. // Updating faces & normal
  24814. var normals = [];
  24815. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24816. for (index = 0; index < totalIndices; index += 3) {
  24817. indices[index] = index;
  24818. indices[index + 1] = index + 1;
  24819. indices[index + 2] = index + 2;
  24820. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24821. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24822. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24823. var p1p2 = p1.subtract(p2);
  24824. var p3p2 = p3.subtract(p2);
  24825. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24826. // Store same normals for every vertex
  24827. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24828. normals.push(normal.x);
  24829. normals.push(normal.y);
  24830. normals.push(normal.z);
  24831. }
  24832. }
  24833. this.setIndices(indices);
  24834. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24835. // Updating vertex buffers
  24836. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24837. kind = kinds[kindIndex];
  24838. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24839. }
  24840. // Updating submeshes
  24841. this.releaseSubMeshes();
  24842. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24843. var previousOne = previousSubmeshes[submeshIndex];
  24844. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24845. }
  24846. this.synchronizeInstances();
  24847. return this;
  24848. };
  24849. /**
  24850. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24851. * In other words, more vertices, no more indices and a single bigger VBO.
  24852. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24853. * Returns the Mesh.
  24854. */
  24855. Mesh.prototype.convertToUnIndexedMesh = function () {
  24856. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24857. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24858. var kinds = this.getVerticesDataKinds();
  24859. var vbs = {};
  24860. var data = {};
  24861. var newdata = {};
  24862. var kindIndex;
  24863. var kind;
  24864. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24865. kind = kinds[kindIndex];
  24866. var vertexBuffer = this.getVertexBuffer(kind);
  24867. vbs[kind] = vertexBuffer;
  24868. data[kind] = vbs[kind].getData();
  24869. newdata[kind] = [];
  24870. }
  24871. // Save previous submeshes
  24872. var previousSubmeshes = this.subMeshes.slice(0);
  24873. var indices = this.getIndices();
  24874. var totalIndices = this.getTotalIndices();
  24875. // Generating unique vertices per face
  24876. var index;
  24877. for (index = 0; index < totalIndices; index++) {
  24878. var vertexIndex = indices[index];
  24879. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24880. kind = kinds[kindIndex];
  24881. var stride = vbs[kind].getStrideSize();
  24882. for (var offset = 0; offset < stride; offset++) {
  24883. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24884. }
  24885. }
  24886. }
  24887. // Updating indices
  24888. for (index = 0; index < totalIndices; index += 3) {
  24889. indices[index] = index;
  24890. indices[index + 1] = index + 1;
  24891. indices[index + 2] = index + 2;
  24892. }
  24893. this.setIndices(indices);
  24894. // Updating vertex buffers
  24895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24896. kind = kinds[kindIndex];
  24897. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24898. }
  24899. // Updating submeshes
  24900. this.releaseSubMeshes();
  24901. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24902. var previousOne = previousSubmeshes[submeshIndex];
  24903. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24904. }
  24905. this._unIndexed = true;
  24906. this.synchronizeInstances();
  24907. return this;
  24908. };
  24909. /**
  24910. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24911. * This method returns the Mesh.
  24912. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24913. */
  24914. Mesh.prototype.flipFaces = function (flipNormals) {
  24915. if (flipNormals === void 0) { flipNormals = false; }
  24916. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24917. var i;
  24918. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24919. for (i = 0; i < vertex_data.normals.length; i++) {
  24920. vertex_data.normals[i] *= -1;
  24921. }
  24922. }
  24923. if (vertex_data.indices) {
  24924. var temp;
  24925. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24926. // reassign indices
  24927. temp = vertex_data.indices[i + 1];
  24928. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24929. vertex_data.indices[i + 2] = temp;
  24930. }
  24931. }
  24932. vertex_data.applyToMesh(this);
  24933. return this;
  24934. };
  24935. // Instances
  24936. /**
  24937. * Creates a new InstancedMesh object from the mesh model.
  24938. * An instance shares the same properties and the same material than its model.
  24939. * Only these properties of each instance can then be set individually :
  24940. * - position
  24941. * - rotation
  24942. * - rotationQuaternion
  24943. * - setPivotMatrix
  24944. * - scaling
  24945. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24946. * Warning : this method is not supported for Line mesh and LineSystem
  24947. */
  24948. Mesh.prototype.createInstance = function (name) {
  24949. return new BABYLON.InstancedMesh(name, this);
  24950. };
  24951. /**
  24952. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24953. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24954. * This method returns the Mesh.
  24955. */
  24956. Mesh.prototype.synchronizeInstances = function () {
  24957. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24958. var instance = this.instances[instanceIndex];
  24959. instance._syncSubMeshes();
  24960. }
  24961. return this;
  24962. };
  24963. /**
  24964. * Simplify the mesh according to the given array of settings.
  24965. * Function will return immediately and will simplify async. It returns the Mesh.
  24966. * @param settings a collection of simplification settings.
  24967. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24968. * @param type the type of simplification to run.
  24969. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24970. */
  24971. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24972. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24973. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24974. this.getScene().simplificationQueue.addTask({
  24975. settings: settings,
  24976. parallelProcessing: parallelProcessing,
  24977. mesh: this,
  24978. simplificationType: simplificationType,
  24979. successCallback: successCallback
  24980. });
  24981. return this;
  24982. };
  24983. /**
  24984. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24985. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24986. * This should be used together with the simplification to avoid disappearing triangles.
  24987. * Returns the Mesh.
  24988. * @param successCallback an optional success callback to be called after the optimization finished.
  24989. */
  24990. Mesh.prototype.optimizeIndices = function (successCallback) {
  24991. var _this = this;
  24992. var indices = this.getIndices();
  24993. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24994. if (!positions || !indices) {
  24995. return this;
  24996. }
  24997. var vectorPositions = new Array();
  24998. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24999. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25000. }
  25001. var dupes = new Array();
  25002. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25003. var realPos = vectorPositions.length - 1 - iteration;
  25004. var testedPosition = vectorPositions[realPos];
  25005. for (var j = 0; j < realPos; ++j) {
  25006. var againstPosition = vectorPositions[j];
  25007. if (testedPosition.equals(againstPosition)) {
  25008. dupes[realPos] = j;
  25009. break;
  25010. }
  25011. }
  25012. }, function () {
  25013. for (var i = 0; i < indices.length; ++i) {
  25014. indices[i] = dupes[indices[i]] || indices[i];
  25015. }
  25016. //indices are now reordered
  25017. var originalSubMeshes = _this.subMeshes.slice(0);
  25018. _this.setIndices(indices);
  25019. _this.subMeshes = originalSubMeshes;
  25020. if (successCallback) {
  25021. successCallback(_this);
  25022. }
  25023. });
  25024. return this;
  25025. };
  25026. Mesh.prototype.serialize = function (serializationObject) {
  25027. serializationObject.name = this.name;
  25028. serializationObject.id = this.id;
  25029. serializationObject.type = this.getClassName();
  25030. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  25031. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25032. }
  25033. serializationObject.position = this.position.asArray();
  25034. if (this.rotationQuaternion) {
  25035. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25036. }
  25037. else if (this.rotation) {
  25038. serializationObject.rotation = this.rotation.asArray();
  25039. }
  25040. serializationObject.scaling = this.scaling.asArray();
  25041. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25042. serializationObject.isEnabled = this.isEnabled();
  25043. serializationObject.isVisible = this.isVisible;
  25044. serializationObject.infiniteDistance = this.infiniteDistance;
  25045. serializationObject.pickable = this.isPickable;
  25046. serializationObject.receiveShadows = this.receiveShadows;
  25047. serializationObject.billboardMode = this.billboardMode;
  25048. serializationObject.visibility = this.visibility;
  25049. serializationObject.checkCollisions = this.checkCollisions;
  25050. serializationObject.isBlocker = this.isBlocker;
  25051. // Parent
  25052. if (this.parent) {
  25053. serializationObject.parentId = this.parent.id;
  25054. }
  25055. // Geometry
  25056. serializationObject.isUnIndexed = this.isUnIndexed;
  25057. var geometry = this._geometry;
  25058. if (geometry) {
  25059. var geometryId = geometry.id;
  25060. serializationObject.geometryId = geometryId;
  25061. // SubMeshes
  25062. serializationObject.subMeshes = [];
  25063. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25064. var subMesh = this.subMeshes[subIndex];
  25065. serializationObject.subMeshes.push({
  25066. materialIndex: subMesh.materialIndex,
  25067. verticesStart: subMesh.verticesStart,
  25068. verticesCount: subMesh.verticesCount,
  25069. indexStart: subMesh.indexStart,
  25070. indexCount: subMesh.indexCount
  25071. });
  25072. }
  25073. }
  25074. // Material
  25075. if (this.material) {
  25076. serializationObject.materialId = this.material.id;
  25077. }
  25078. else {
  25079. this.material = null;
  25080. }
  25081. // Morph targets
  25082. if (this.morphTargetManager) {
  25083. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25084. }
  25085. // Skeleton
  25086. if (this.skeleton) {
  25087. serializationObject.skeletonId = this.skeleton.id;
  25088. }
  25089. // Physics
  25090. //TODO implement correct serialization for physics impostors.
  25091. var impostor = this.getPhysicsImpostor();
  25092. if (impostor) {
  25093. serializationObject.physicsMass = impostor.getParam("mass");
  25094. serializationObject.physicsFriction = impostor.getParam("friction");
  25095. serializationObject.physicsRestitution = impostor.getParam("mass");
  25096. serializationObject.physicsImpostor = impostor.type;
  25097. }
  25098. // Metadata
  25099. if (this.metadata) {
  25100. serializationObject.metadata = this.metadata;
  25101. }
  25102. // Instances
  25103. serializationObject.instances = [];
  25104. for (var index = 0; index < this.instances.length; index++) {
  25105. var instance = this.instances[index];
  25106. var serializationInstance = {
  25107. name: instance.name,
  25108. id: instance.id,
  25109. position: instance.position.asArray(),
  25110. scaling: instance.scaling.asArray()
  25111. };
  25112. if (instance.rotationQuaternion) {
  25113. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25114. }
  25115. else if (instance.rotation) {
  25116. serializationInstance.rotation = instance.rotation.asArray();
  25117. }
  25118. serializationObject.instances.push(serializationInstance);
  25119. // Animations
  25120. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25121. serializationInstance.ranges = instance.serializeAnimationRanges();
  25122. }
  25123. //
  25124. // Animations
  25125. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25126. serializationObject.ranges = this.serializeAnimationRanges();
  25127. // Layer mask
  25128. serializationObject.layerMask = this.layerMask;
  25129. // Alpha
  25130. serializationObject.alphaIndex = this.alphaIndex;
  25131. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25132. // Overlay
  25133. serializationObject.overlayAlpha = this.overlayAlpha;
  25134. serializationObject.overlayColor = this.overlayColor.asArray();
  25135. serializationObject.renderOverlay = this.renderOverlay;
  25136. // Fog
  25137. serializationObject.applyFog = this.applyFog;
  25138. // Action Manager
  25139. if (this.actionManager) {
  25140. serializationObject.actions = this.actionManager.serialize(this.name);
  25141. }
  25142. };
  25143. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25144. if (!this.geometry) {
  25145. return;
  25146. }
  25147. this._markSubMeshesAsAttributesDirty();
  25148. var morphTargetManager = this._morphTargetManager;
  25149. if (morphTargetManager && morphTargetManager.vertexCount) {
  25150. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25151. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25152. this.morphTargetManager = null;
  25153. return;
  25154. }
  25155. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  25156. var morphTarget = morphTargetManager.getActiveTarget(index);
  25157. var positions = morphTarget.getPositions();
  25158. if (!positions) {
  25159. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  25160. return;
  25161. }
  25162. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  25163. var normals = morphTarget.getNormals();
  25164. if (normals) {
  25165. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  25166. }
  25167. var tangents = morphTarget.getTangents();
  25168. if (tangents) {
  25169. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  25170. }
  25171. }
  25172. }
  25173. else {
  25174. var index = 0;
  25175. // Positions
  25176. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25177. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25178. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25179. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25180. }
  25181. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  25182. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  25183. }
  25184. index++;
  25185. }
  25186. }
  25187. };
  25188. // Statics
  25189. /**
  25190. * Returns a new Mesh object parsed from the source provided.
  25191. * The parameter `parsedMesh` is the source.
  25192. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25193. */
  25194. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25195. var mesh;
  25196. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25197. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25198. }
  25199. else {
  25200. mesh = new Mesh(parsedMesh.name, scene);
  25201. }
  25202. mesh.id = parsedMesh.id;
  25203. if (BABYLON.Tags) {
  25204. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25205. }
  25206. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25207. if (parsedMesh.metadata !== undefined) {
  25208. mesh.metadata = parsedMesh.metadata;
  25209. }
  25210. if (parsedMesh.rotationQuaternion) {
  25211. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25212. }
  25213. else if (parsedMesh.rotation) {
  25214. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25215. }
  25216. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25217. if (parsedMesh.localMatrix) {
  25218. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25219. }
  25220. else if (parsedMesh.pivotMatrix) {
  25221. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25222. }
  25223. mesh.setEnabled(parsedMesh.isEnabled);
  25224. mesh.isVisible = parsedMesh.isVisible;
  25225. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25226. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25227. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25228. if (parsedMesh.applyFog !== undefined) {
  25229. mesh.applyFog = parsedMesh.applyFog;
  25230. }
  25231. if (parsedMesh.pickable !== undefined) {
  25232. mesh.isPickable = parsedMesh.pickable;
  25233. }
  25234. if (parsedMesh.alphaIndex !== undefined) {
  25235. mesh.alphaIndex = parsedMesh.alphaIndex;
  25236. }
  25237. mesh.receiveShadows = parsedMesh.receiveShadows;
  25238. mesh.billboardMode = parsedMesh.billboardMode;
  25239. if (parsedMesh.visibility !== undefined) {
  25240. mesh.visibility = parsedMesh.visibility;
  25241. }
  25242. mesh.checkCollisions = parsedMesh.checkCollisions;
  25243. if (parsedMesh.isBlocker !== undefined) {
  25244. mesh.isBlocker = parsedMesh.isBlocker;
  25245. }
  25246. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25247. // freezeWorldMatrix
  25248. if (parsedMesh.freezeWorldMatrix) {
  25249. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25250. }
  25251. // Parent
  25252. if (parsedMesh.parentId) {
  25253. mesh._waitingParentId = parsedMesh.parentId;
  25254. }
  25255. // Actions
  25256. if (parsedMesh.actions !== undefined) {
  25257. mesh._waitingActions = parsedMesh.actions;
  25258. }
  25259. // Overlay
  25260. if (parsedMesh.overlayAlpha !== undefined) {
  25261. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25262. }
  25263. if (parsedMesh.overlayColor !== undefined) {
  25264. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25265. }
  25266. if (parsedMesh.renderOverlay !== undefined) {
  25267. mesh.renderOverlay = parsedMesh.renderOverlay;
  25268. }
  25269. // Geometry
  25270. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  25271. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25272. if (parsedMesh.delayLoadingFile) {
  25273. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25274. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25275. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25276. if (parsedMesh._binaryInfo) {
  25277. mesh._binaryInfo = parsedMesh._binaryInfo;
  25278. }
  25279. mesh._delayInfo = [];
  25280. if (parsedMesh.hasUVs) {
  25281. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25282. }
  25283. if (parsedMesh.hasUVs2) {
  25284. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25285. }
  25286. if (parsedMesh.hasUVs3) {
  25287. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25288. }
  25289. if (parsedMesh.hasUVs4) {
  25290. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25291. }
  25292. if (parsedMesh.hasUVs5) {
  25293. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25294. }
  25295. if (parsedMesh.hasUVs6) {
  25296. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25297. }
  25298. if (parsedMesh.hasColors) {
  25299. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25300. }
  25301. if (parsedMesh.hasMatricesIndices) {
  25302. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25303. }
  25304. if (parsedMesh.hasMatricesWeights) {
  25305. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25306. }
  25307. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25308. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25309. mesh._checkDelayState();
  25310. }
  25311. }
  25312. else {
  25313. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25314. }
  25315. // Material
  25316. if (parsedMesh.materialId) {
  25317. mesh.setMaterialByID(parsedMesh.materialId);
  25318. }
  25319. else {
  25320. mesh.material = null;
  25321. }
  25322. // Morph targets
  25323. if (parsedMesh.morphTargetManagerId > -1) {
  25324. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25325. }
  25326. // Skeleton
  25327. if (parsedMesh.skeletonId > -1) {
  25328. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25329. if (parsedMesh.numBoneInfluencers) {
  25330. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25331. }
  25332. }
  25333. // Animations
  25334. if (parsedMesh.animations) {
  25335. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25336. var parsedAnimation = parsedMesh.animations[animationIndex];
  25337. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25338. }
  25339. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25340. }
  25341. if (parsedMesh.autoAnimate) {
  25342. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25343. }
  25344. // Layer Mask
  25345. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25346. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25347. }
  25348. else {
  25349. mesh.layerMask = 0x0FFFFFFF;
  25350. }
  25351. // Physics
  25352. if (parsedMesh.physicsImpostor) {
  25353. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25354. mass: parsedMesh.physicsMass,
  25355. friction: parsedMesh.physicsFriction,
  25356. restitution: parsedMesh.physicsRestitution
  25357. }, scene);
  25358. }
  25359. // Instances
  25360. if (parsedMesh.instances) {
  25361. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25362. var parsedInstance = parsedMesh.instances[index];
  25363. var instance = mesh.createInstance(parsedInstance.name);
  25364. if (parsedInstance.id) {
  25365. instance.id = parsedInstance.id;
  25366. }
  25367. if (BABYLON.Tags) {
  25368. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25369. }
  25370. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25371. if (parsedInstance.parentId) {
  25372. instance._waitingParentId = parsedInstance.parentId;
  25373. }
  25374. if (parsedInstance.rotationQuaternion) {
  25375. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25376. }
  25377. else if (parsedInstance.rotation) {
  25378. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25379. }
  25380. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25381. instance.checkCollisions = mesh.checkCollisions;
  25382. if (parsedMesh.animations) {
  25383. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25384. parsedAnimation = parsedMesh.animations[animationIndex];
  25385. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25386. }
  25387. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25388. }
  25389. }
  25390. }
  25391. return mesh;
  25392. };
  25393. /**
  25394. * Creates a ribbon mesh.
  25395. * Please consider using the same method from the MeshBuilder class instead.
  25396. * 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.
  25397. *
  25398. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25399. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25400. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25401. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25402. * 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.
  25403. * 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.
  25404. * 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
  25405. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25406. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25407. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25408. */
  25409. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25410. if (closeArray === void 0) { closeArray = false; }
  25411. if (updatable === void 0) { updatable = false; }
  25412. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25413. pathArray: pathArray,
  25414. closeArray: closeArray,
  25415. closePath: closePath,
  25416. offset: offset,
  25417. updatable: updatable,
  25418. sideOrientation: sideOrientation,
  25419. instance: instance
  25420. }, scene);
  25421. };
  25422. /**
  25423. * Creates a plane polygonal mesh. By default, this is a disc.
  25424. * Please consider using the same method from the MeshBuilder class instead.
  25425. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25426. * 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.
  25427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25430. */
  25431. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25432. if (scene === void 0) { scene = null; }
  25433. var options = {
  25434. radius: radius,
  25435. tessellation: tessellation,
  25436. sideOrientation: sideOrientation,
  25437. updatable: updatable
  25438. };
  25439. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25440. };
  25441. /**
  25442. * Creates a box mesh.
  25443. * Please consider using the same method from the MeshBuilder class instead.
  25444. * The parameter `size` sets the size (float) of each box side (default 1).
  25445. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25446. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25447. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25448. */
  25449. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25450. if (scene === void 0) { scene = null; }
  25451. var options = {
  25452. size: size,
  25453. sideOrientation: sideOrientation,
  25454. updatable: updatable
  25455. };
  25456. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25457. };
  25458. /**
  25459. * Creates a sphere mesh.
  25460. * Please consider using the same method from the MeshBuilder class instead.
  25461. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25462. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25464. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25466. */
  25467. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25468. var options = {
  25469. segments: segments,
  25470. diameterX: diameter,
  25471. diameterY: diameter,
  25472. diameterZ: diameter,
  25473. sideOrientation: sideOrientation,
  25474. updatable: updatable
  25475. };
  25476. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25477. };
  25478. /**
  25479. * Creates a cylinder or a cone mesh.
  25480. * Please consider using the same method from the MeshBuilder class instead.
  25481. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25482. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25483. * 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.
  25484. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25485. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25489. */
  25490. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25491. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25492. if (scene !== undefined) {
  25493. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25494. updatable = scene;
  25495. }
  25496. scene = subdivisions;
  25497. subdivisions = 1;
  25498. }
  25499. var options = {
  25500. height: height,
  25501. diameterTop: diameterTop,
  25502. diameterBottom: diameterBottom,
  25503. tessellation: tessellation,
  25504. subdivisions: subdivisions,
  25505. sideOrientation: sideOrientation,
  25506. updatable: updatable
  25507. };
  25508. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25509. };
  25510. // Torus (Code from SharpDX.org)
  25511. /**
  25512. * Creates a torus mesh.
  25513. * Please consider using the same method from the MeshBuilder class instead.
  25514. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25515. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25516. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25520. */
  25521. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25522. var options = {
  25523. diameter: diameter,
  25524. thickness: thickness,
  25525. tessellation: tessellation,
  25526. sideOrientation: sideOrientation,
  25527. updatable: updatable
  25528. };
  25529. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25530. };
  25531. /**
  25532. * Creates a torus knot mesh.
  25533. * Please consider using the same method from the MeshBuilder class instead.
  25534. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25535. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25536. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25537. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25541. */
  25542. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25543. var options = {
  25544. radius: radius,
  25545. tube: tube,
  25546. radialSegments: radialSegments,
  25547. tubularSegments: tubularSegments,
  25548. p: p,
  25549. q: q,
  25550. sideOrientation: sideOrientation,
  25551. updatable: updatable
  25552. };
  25553. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25554. };
  25555. /**
  25556. * Creates a line mesh.
  25557. * Please consider using the same method from the MeshBuilder class instead.
  25558. * 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.
  25559. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25560. * The parameter `points` is an array successive Vector3.
  25561. * 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
  25562. * When updating an instance, remember that only point positions can change, not the number of points.
  25563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25564. */
  25565. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25566. if (scene === void 0) { scene = null; }
  25567. if (updatable === void 0) { updatable = false; }
  25568. if (instance === void 0) { instance = null; }
  25569. var options = {
  25570. points: points,
  25571. updatable: updatable,
  25572. instance: instance
  25573. };
  25574. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25575. };
  25576. /**
  25577. * Creates a dashed line mesh.
  25578. * Please consider using the same method from the MeshBuilder class instead.
  25579. * 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.
  25580. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25581. * The parameter `points` is an array successive Vector3.
  25582. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25583. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25584. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25585. * 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
  25586. * When updating an instance, remember that only point positions can change, not the number of points.
  25587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25588. */
  25589. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25590. if (scene === void 0) { scene = null; }
  25591. var options = {
  25592. points: points,
  25593. dashSize: dashSize,
  25594. gapSize: gapSize,
  25595. dashNb: dashNb,
  25596. updatable: updatable,
  25597. instance: instance
  25598. };
  25599. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25600. };
  25601. /**
  25602. * Creates a polygon mesh.
  25603. * Please consider using the same method from the MeshBuilder class instead.
  25604. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25605. * 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.
  25606. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25608. * Remember you can only change the shape positions, not their number when updating a polygon.
  25609. */
  25610. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25611. var options = {
  25612. shape: shape,
  25613. holes: holes,
  25614. updatable: updatable,
  25615. sideOrientation: sideOrientation
  25616. };
  25617. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25618. };
  25619. /**
  25620. * Creates an extruded polygon mesh, with depth in the Y direction.
  25621. * Please consider using the same method from the MeshBuilder class instead.
  25622. */
  25623. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25624. var options = {
  25625. shape: shape,
  25626. holes: holes,
  25627. depth: depth,
  25628. updatable: updatable,
  25629. sideOrientation: sideOrientation
  25630. };
  25631. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25632. };
  25633. /**
  25634. * Creates an extruded shape mesh.
  25635. * 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.
  25636. * Please consider using the same method from the MeshBuilder class instead.
  25637. *
  25638. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25639. * 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
  25640. * extruded along the Z axis.
  25641. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25642. * 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.
  25643. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25644. * 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
  25645. * 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
  25646. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25647. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25648. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25650. */
  25651. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25652. if (scene === void 0) { scene = null; }
  25653. var options = {
  25654. shape: shape,
  25655. path: path,
  25656. scale: scale,
  25657. rotation: rotation,
  25658. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25659. sideOrientation: sideOrientation,
  25660. instance: instance,
  25661. updatable: updatable
  25662. };
  25663. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25664. };
  25665. /**
  25666. * Creates an custom extruded shape mesh.
  25667. * 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.
  25668. * Please consider using the same method from the MeshBuilder class instead.
  25669. *
  25670. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25671. * 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
  25672. * extruded along the Z axis.
  25673. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25674. * 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
  25675. * and the distance of this point from the begining of the path :
  25676. * ```javascript
  25677. * var rotationFunction = function(i, distance) {
  25678. * // do things
  25679. * return rotationValue; }
  25680. * ```
  25681. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25682. * 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
  25683. * and the distance of this point from the begining of the path :
  25684. * ```javascript
  25685. * var scaleFunction = function(i, distance) {
  25686. * // do things
  25687. * return scaleValue;}
  25688. * ```
  25689. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25690. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25691. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25692. * 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
  25693. * 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
  25694. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25698. */
  25699. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25700. var options = {
  25701. shape: shape,
  25702. path: path,
  25703. scaleFunction: scaleFunction,
  25704. rotationFunction: rotationFunction,
  25705. ribbonCloseArray: ribbonCloseArray,
  25706. ribbonClosePath: ribbonClosePath,
  25707. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25708. sideOrientation: sideOrientation,
  25709. instance: instance,
  25710. updatable: updatable
  25711. };
  25712. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25713. };
  25714. /**
  25715. * Creates lathe mesh.
  25716. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25717. * Please consider using the same method from the MeshBuilder class instead.
  25718. * 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
  25719. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25720. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25721. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25722. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25723. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25725. */
  25726. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25727. var options = {
  25728. shape: shape,
  25729. radius: radius,
  25730. tessellation: tessellation,
  25731. sideOrientation: sideOrientation,
  25732. updatable: updatable
  25733. };
  25734. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25735. };
  25736. /**
  25737. * Creates a plane mesh.
  25738. * Please consider using the same method from the MeshBuilder class instead.
  25739. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25743. */
  25744. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25745. var options = {
  25746. size: size,
  25747. width: size,
  25748. height: size,
  25749. sideOrientation: sideOrientation,
  25750. updatable: updatable
  25751. };
  25752. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25753. };
  25754. /**
  25755. * Creates a ground mesh.
  25756. * Please consider using the same method from the MeshBuilder class instead.
  25757. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25758. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25760. */
  25761. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25762. var options = {
  25763. width: width,
  25764. height: height,
  25765. subdivisions: subdivisions,
  25766. updatable: updatable
  25767. };
  25768. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25769. };
  25770. /**
  25771. * Creates a tiled ground mesh.
  25772. * Please consider using the same method from the MeshBuilder class instead.
  25773. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25774. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25775. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25776. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25777. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25778. * numbers of subdivisions on the ground width and height of each tile.
  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.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25782. var options = {
  25783. xmin: xmin,
  25784. zmin: zmin,
  25785. xmax: xmax,
  25786. zmax: zmax,
  25787. subdivisions: subdivisions,
  25788. precision: precision,
  25789. updatable: updatable
  25790. };
  25791. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25792. };
  25793. /**
  25794. * Creates a ground mesh from a height map.
  25795. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25796. * Please consider using the same method from the MeshBuilder class instead.
  25797. * The parameter `url` sets the URL of the height map image resource.
  25798. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25799. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25800. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25801. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25802. * 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).
  25803. * This function is passed the newly built mesh :
  25804. * ```javascript
  25805. * function(mesh) { // do things
  25806. * return; }
  25807. * ```
  25808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25809. */
  25810. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25811. var options = {
  25812. width: width,
  25813. height: height,
  25814. subdivisions: subdivisions,
  25815. minHeight: minHeight,
  25816. maxHeight: maxHeight,
  25817. updatable: updatable,
  25818. onReady: onReady
  25819. };
  25820. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25821. };
  25822. /**
  25823. * Creates a tube mesh.
  25824. * 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.
  25825. * Please consider using the same method from the MeshBuilder class instead.
  25826. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25827. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25828. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25829. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25830. * 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.
  25831. * It must return a radius value (positive float) :
  25832. * ```javascript
  25833. * var radiusFunction = function(i, distance) {
  25834. * // do things
  25835. * return radius; }
  25836. * ```
  25837. * 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
  25838. * 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
  25839. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25840. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25844. var options = {
  25845. path: path,
  25846. radius: radius,
  25847. tessellation: tessellation,
  25848. radiusFunction: radiusFunction,
  25849. arc: 1,
  25850. cap: cap,
  25851. updatable: updatable,
  25852. sideOrientation: sideOrientation,
  25853. instance: instance
  25854. };
  25855. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25856. };
  25857. /**
  25858. * Creates a polyhedron mesh.
  25859. * Please consider using the same method from the MeshBuilder class instead.
  25860. * 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
  25861. * to choose the wanted type.
  25862. * The parameter `size` (positive float, default 1) sets the polygon size.
  25863. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25864. * 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`.
  25865. * 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
  25866. * 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)`).
  25867. * 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
  25868. * 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.
  25869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25872. */
  25873. Mesh.CreatePolyhedron = function (name, options, scene) {
  25874. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25875. };
  25876. /**
  25877. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25878. * Please consider using the same method from the MeshBuilder class instead.
  25879. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25880. * 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`).
  25881. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25882. * 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.
  25883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25884. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25886. */
  25887. Mesh.CreateIcoSphere = function (name, options, scene) {
  25888. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25889. };
  25890. /**
  25891. * Creates a decal mesh.
  25892. * Please consider using the same method from the MeshBuilder class instead.
  25893. * 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.
  25894. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25895. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25896. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25897. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25898. */
  25899. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25900. var options = {
  25901. position: position,
  25902. normal: normal,
  25903. size: size,
  25904. angle: angle
  25905. };
  25906. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25907. };
  25908. // Skeletons
  25909. /**
  25910. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25911. */
  25912. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25913. if (!this._sourcePositions) {
  25914. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25915. if (!source) {
  25916. return this._sourcePositions;
  25917. }
  25918. this._sourcePositions = new Float32Array(source);
  25919. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25920. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25921. }
  25922. }
  25923. return this._sourcePositions;
  25924. };
  25925. /**
  25926. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25927. */
  25928. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25929. if (!this._sourceNormals) {
  25930. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25931. if (!source) {
  25932. return this._sourceNormals;
  25933. }
  25934. this._sourceNormals = new Float32Array(source);
  25935. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25936. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25937. }
  25938. }
  25939. return this._sourceNormals;
  25940. };
  25941. /**
  25942. * Updates the vertex buffer by applying transformation from the bones.
  25943. * Returns the Mesh.
  25944. *
  25945. * @param {skeleton} skeleton to apply
  25946. */
  25947. Mesh.prototype.applySkeleton = function (skeleton) {
  25948. if (!this.geometry) {
  25949. return this;
  25950. }
  25951. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25952. return this;
  25953. }
  25954. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25955. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25956. return this;
  25957. }
  25958. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25959. return this;
  25960. }
  25961. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25962. return this;
  25963. }
  25964. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25965. return this;
  25966. }
  25967. if (!this._sourcePositions) {
  25968. var submeshes = this.subMeshes.slice();
  25969. this.setPositionsForCPUSkinning();
  25970. this.subMeshes = submeshes;
  25971. }
  25972. if (!this._sourceNormals) {
  25973. this.setNormalsForCPUSkinning();
  25974. }
  25975. // positionsData checks for not being Float32Array will only pass at most once
  25976. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25977. if (!positionsData) {
  25978. return this;
  25979. }
  25980. if (!(positionsData instanceof Float32Array)) {
  25981. positionsData = new Float32Array(positionsData);
  25982. }
  25983. // normalsData checks for not being Float32Array will only pass at most once
  25984. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25985. if (!normalsData) {
  25986. return this;
  25987. }
  25988. if (!(normalsData instanceof Float32Array)) {
  25989. normalsData = new Float32Array(normalsData);
  25990. }
  25991. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25992. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25993. if (!matricesWeightsData || !matricesIndicesData) {
  25994. return this;
  25995. }
  25996. var needExtras = this.numBoneInfluencers > 4;
  25997. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25998. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25999. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26000. var tempVector3 = BABYLON.Vector3.Zero();
  26001. var finalMatrix = new BABYLON.Matrix();
  26002. var tempMatrix = new BABYLON.Matrix();
  26003. var matWeightIdx = 0;
  26004. var inf;
  26005. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26006. var weight;
  26007. for (inf = 0; inf < 4; inf++) {
  26008. weight = matricesWeightsData[matWeightIdx + inf];
  26009. if (weight > 0) {
  26010. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26011. finalMatrix.addToSelf(tempMatrix);
  26012. }
  26013. else
  26014. break;
  26015. }
  26016. if (needExtras) {
  26017. for (inf = 0; inf < 4; inf++) {
  26018. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26019. if (weight > 0) {
  26020. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26021. finalMatrix.addToSelf(tempMatrix);
  26022. }
  26023. else
  26024. break;
  26025. }
  26026. }
  26027. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26028. tempVector3.toArray(positionsData, index);
  26029. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26030. tempVector3.toArray(normalsData, index);
  26031. finalMatrix.reset();
  26032. }
  26033. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26034. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26035. return this;
  26036. };
  26037. // Tools
  26038. /**
  26039. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26040. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26041. */
  26042. Mesh.MinMax = function (meshes) {
  26043. var minVector = null;
  26044. var maxVector = null;
  26045. meshes.forEach(function (mesh, index, array) {
  26046. var boundingInfo = mesh.getBoundingInfo();
  26047. var boundingBox = boundingInfo.boundingBox;
  26048. if (!minVector || !maxVector) {
  26049. minVector = boundingBox.minimumWorld;
  26050. maxVector = boundingBox.maximumWorld;
  26051. }
  26052. else {
  26053. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26054. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26055. }
  26056. });
  26057. if (!minVector || !maxVector) {
  26058. return {
  26059. min: BABYLON.Vector3.Zero(),
  26060. max: BABYLON.Vector3.Zero()
  26061. };
  26062. }
  26063. return {
  26064. min: minVector,
  26065. max: maxVector
  26066. };
  26067. };
  26068. /**
  26069. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26070. */
  26071. Mesh.Center = function (meshesOrMinMaxVector) {
  26072. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26073. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26074. };
  26075. /**
  26076. * Merge the array of meshes into a single mesh for performance reasons.
  26077. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26078. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26079. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26080. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26081. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26082. */
  26083. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26084. if (disposeSource === void 0) { disposeSource = true; }
  26085. var index;
  26086. if (!allow32BitsIndices) {
  26087. var totalVertices = 0;
  26088. // Counting vertices
  26089. for (index = 0; index < meshes.length; index++) {
  26090. if (meshes[index]) {
  26091. totalVertices += meshes[index].getTotalVertices();
  26092. if (totalVertices > 65536) {
  26093. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26094. return null;
  26095. }
  26096. }
  26097. }
  26098. }
  26099. // Merge
  26100. var vertexData = null;
  26101. var otherVertexData;
  26102. var indiceArray = new Array();
  26103. var source = null;
  26104. for (index = 0; index < meshes.length; index++) {
  26105. if (meshes[index]) {
  26106. meshes[index].computeWorldMatrix(true);
  26107. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26108. otherVertexData.transform(meshes[index].getWorldMatrix());
  26109. if (vertexData) {
  26110. vertexData.merge(otherVertexData);
  26111. }
  26112. else {
  26113. vertexData = otherVertexData;
  26114. source = meshes[index];
  26115. }
  26116. if (subdivideWithSubMeshes) {
  26117. indiceArray.push(meshes[index].getTotalIndices());
  26118. }
  26119. }
  26120. }
  26121. source = source;
  26122. if (!meshSubclass) {
  26123. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26124. }
  26125. vertexData.applyToMesh(meshSubclass);
  26126. // Setting properties
  26127. meshSubclass.material = source.material;
  26128. meshSubclass.checkCollisions = source.checkCollisions;
  26129. // Cleaning
  26130. if (disposeSource) {
  26131. for (index = 0; index < meshes.length; index++) {
  26132. if (meshes[index]) {
  26133. meshes[index].dispose();
  26134. }
  26135. }
  26136. }
  26137. // Subdivide
  26138. if (subdivideWithSubMeshes) {
  26139. //-- Suppresions du submesh global
  26140. meshSubclass.releaseSubMeshes();
  26141. index = 0;
  26142. var offset = 0;
  26143. //-- aplique la subdivision en fonction du tableau d'indices
  26144. while (index < indiceArray.length) {
  26145. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26146. offset += indiceArray[index];
  26147. index++;
  26148. }
  26149. }
  26150. return meshSubclass;
  26151. };
  26152. // Consts
  26153. Mesh._FRONTSIDE = 0;
  26154. Mesh._BACKSIDE = 1;
  26155. Mesh._DOUBLESIDE = 2;
  26156. Mesh._DEFAULTSIDE = 0;
  26157. Mesh._NO_CAP = 0;
  26158. Mesh._CAP_START = 1;
  26159. Mesh._CAP_END = 2;
  26160. Mesh._CAP_ALL = 3;
  26161. return Mesh;
  26162. }(BABYLON.AbstractMesh));
  26163. BABYLON.Mesh = Mesh;
  26164. })(BABYLON || (BABYLON = {}));
  26165. //# sourceMappingURL=babylon.mesh.js.map
  26166. var BABYLON;
  26167. (function (BABYLON) {
  26168. var BaseSubMesh = /** @class */ (function () {
  26169. function BaseSubMesh() {
  26170. }
  26171. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  26172. get: function () {
  26173. return this._materialEffect;
  26174. },
  26175. enumerable: true,
  26176. configurable: true
  26177. });
  26178. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  26179. if (defines === void 0) { defines = null; }
  26180. if (this._materialEffect === effect) {
  26181. if (!effect) {
  26182. this._materialDefines = null;
  26183. }
  26184. return;
  26185. }
  26186. this._materialDefines = defines;
  26187. this._materialEffect = effect;
  26188. };
  26189. return BaseSubMesh;
  26190. }());
  26191. BABYLON.BaseSubMesh = BaseSubMesh;
  26192. var SubMesh = /** @class */ (function (_super) {
  26193. __extends(SubMesh, _super);
  26194. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26195. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26196. var _this = _super.call(this) || this;
  26197. _this.materialIndex = materialIndex;
  26198. _this.verticesStart = verticesStart;
  26199. _this.verticesCount = verticesCount;
  26200. _this.indexStart = indexStart;
  26201. _this.indexCount = indexCount;
  26202. _this._renderId = 0;
  26203. _this._mesh = mesh;
  26204. _this._renderingMesh = renderingMesh || mesh;
  26205. mesh.subMeshes.push(_this);
  26206. _this._trianglePlanes = [];
  26207. _this._id = mesh.subMeshes.length - 1;
  26208. if (createBoundingBox) {
  26209. _this.refreshBoundingInfo();
  26210. mesh.computeWorldMatrix(true);
  26211. }
  26212. return _this;
  26213. }
  26214. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26215. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26216. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26217. };
  26218. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26219. get: function () {
  26220. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26221. },
  26222. enumerable: true,
  26223. configurable: true
  26224. });
  26225. /**
  26226. * Returns the submesh BoudingInfo object.
  26227. */
  26228. SubMesh.prototype.getBoundingInfo = function () {
  26229. if (this.IsGlobal) {
  26230. return this._mesh.getBoundingInfo();
  26231. }
  26232. return this._boundingInfo;
  26233. };
  26234. /**
  26235. * Sets the submesh BoundingInfo.
  26236. * Return the SubMesh.
  26237. */
  26238. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26239. this._boundingInfo = boundingInfo;
  26240. return this;
  26241. };
  26242. /**
  26243. * Returns the mesh of the current submesh.
  26244. */
  26245. SubMesh.prototype.getMesh = function () {
  26246. return this._mesh;
  26247. };
  26248. /**
  26249. * Returns the rendering mesh of the submesh.
  26250. */
  26251. SubMesh.prototype.getRenderingMesh = function () {
  26252. return this._renderingMesh;
  26253. };
  26254. /**
  26255. * Returns the submesh material.
  26256. */
  26257. SubMesh.prototype.getMaterial = function () {
  26258. var rootMaterial = this._renderingMesh.material;
  26259. if (rootMaterial && rootMaterial.getSubMaterial) {
  26260. var multiMaterial = rootMaterial;
  26261. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26262. if (this._currentMaterial !== effectiveMaterial) {
  26263. this._currentMaterial = effectiveMaterial;
  26264. this._materialDefines = null;
  26265. }
  26266. return effectiveMaterial;
  26267. }
  26268. if (!rootMaterial) {
  26269. return this._mesh.getScene().defaultMaterial;
  26270. }
  26271. return rootMaterial;
  26272. };
  26273. // Methods
  26274. /**
  26275. * Sets a new updated BoundingInfo object to the submesh.
  26276. * Returns the SubMesh.
  26277. */
  26278. SubMesh.prototype.refreshBoundingInfo = function () {
  26279. this._lastColliderWorldVertices = null;
  26280. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26281. return this;
  26282. }
  26283. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26284. if (!data) {
  26285. this._boundingInfo = this._mesh.getBoundingInfo();
  26286. return this;
  26287. }
  26288. var indices = this._renderingMesh.getIndices();
  26289. var extend;
  26290. //is this the only submesh?
  26291. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26292. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26293. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26294. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26295. }
  26296. else {
  26297. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26298. }
  26299. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26300. return this;
  26301. };
  26302. SubMesh.prototype._checkCollision = function (collider) {
  26303. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26304. return boundingInfo._checkCollision(collider);
  26305. };
  26306. /**
  26307. * Updates the submesh BoundingInfo.
  26308. * Returns the Submesh.
  26309. */
  26310. SubMesh.prototype.updateBoundingInfo = function (world) {
  26311. var boundingInfo = this.getBoundingInfo();
  26312. if (!boundingInfo) {
  26313. this.refreshBoundingInfo();
  26314. boundingInfo = this.getBoundingInfo();
  26315. }
  26316. boundingInfo.update(world);
  26317. return this;
  26318. };
  26319. /**
  26320. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26321. * Boolean returned.
  26322. */
  26323. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26324. var boundingInfo = this.getBoundingInfo();
  26325. if (!boundingInfo) {
  26326. return false;
  26327. }
  26328. return boundingInfo.isInFrustum(frustumPlanes);
  26329. };
  26330. /**
  26331. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26332. * Boolean returned.
  26333. */
  26334. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26335. var boundingInfo = this.getBoundingInfo();
  26336. if (!boundingInfo) {
  26337. return false;
  26338. }
  26339. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26340. };
  26341. /**
  26342. * Renders the submesh.
  26343. * Returns it.
  26344. */
  26345. SubMesh.prototype.render = function (enableAlphaMode) {
  26346. this._renderingMesh.render(this, enableAlphaMode);
  26347. return this;
  26348. };
  26349. /**
  26350. * Returns a new Index Buffer.
  26351. * Type returned : WebGLBuffer.
  26352. */
  26353. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26354. if (!this._linesIndexBuffer) {
  26355. var linesIndices = [];
  26356. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26357. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26358. }
  26359. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26360. this.linesIndexCount = linesIndices.length;
  26361. }
  26362. return this._linesIndexBuffer;
  26363. };
  26364. /**
  26365. * True is the passed Ray intersects the submesh bounding box.
  26366. * Boolean returned.
  26367. */
  26368. SubMesh.prototype.canIntersects = function (ray) {
  26369. var boundingInfo = this.getBoundingInfo();
  26370. if (!boundingInfo) {
  26371. return false;
  26372. }
  26373. return ray.intersectsBox(boundingInfo.boundingBox);
  26374. };
  26375. /**
  26376. * Returns an object IntersectionInfo.
  26377. */
  26378. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26379. var intersectInfo = null;
  26380. // LineMesh first as it's also a Mesh...
  26381. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26382. var lineMesh = this._mesh;
  26383. // Line test
  26384. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26385. var p0 = positions[indices[index]];
  26386. var p1 = positions[indices[index + 1]];
  26387. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26388. if (length < 0) {
  26389. continue;
  26390. }
  26391. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26392. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26393. if (fastCheck) {
  26394. break;
  26395. }
  26396. }
  26397. }
  26398. }
  26399. else {
  26400. // Triangles test
  26401. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26402. var p0 = positions[indices[index]];
  26403. var p1 = positions[indices[index + 1]];
  26404. var p2 = positions[indices[index + 2]];
  26405. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26406. if (currentIntersectInfo) {
  26407. if (currentIntersectInfo.distance < 0) {
  26408. continue;
  26409. }
  26410. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26411. intersectInfo = currentIntersectInfo;
  26412. intersectInfo.faceId = index / 3;
  26413. if (fastCheck) {
  26414. break;
  26415. }
  26416. }
  26417. }
  26418. }
  26419. }
  26420. return intersectInfo;
  26421. };
  26422. SubMesh.prototype._rebuild = function () {
  26423. if (this._linesIndexBuffer) {
  26424. this._linesIndexBuffer = null;
  26425. }
  26426. };
  26427. // Clone
  26428. /**
  26429. * Creates a new Submesh from the passed Mesh.
  26430. */
  26431. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26432. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26433. if (!this.IsGlobal) {
  26434. var boundingInfo = this.getBoundingInfo();
  26435. if (!boundingInfo) {
  26436. return result;
  26437. }
  26438. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26439. }
  26440. return result;
  26441. };
  26442. // Dispose
  26443. /**
  26444. * Disposes the Submesh.
  26445. * Returns nothing.
  26446. */
  26447. SubMesh.prototype.dispose = function () {
  26448. if (this._linesIndexBuffer) {
  26449. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26450. this._linesIndexBuffer = null;
  26451. }
  26452. // Remove from mesh
  26453. var index = this._mesh.subMeshes.indexOf(this);
  26454. this._mesh.subMeshes.splice(index, 1);
  26455. };
  26456. // Statics
  26457. /**
  26458. * Creates a new Submesh from the passed parameters :
  26459. * - materialIndex (integer) : the index of the main mesh material.
  26460. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26461. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26462. * - mesh (Mesh) : the main mesh to create the submesh from.
  26463. * - renderingMesh (optional Mesh) : rendering mesh.
  26464. */
  26465. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26466. var minVertexIndex = Number.MAX_VALUE;
  26467. var maxVertexIndex = -Number.MAX_VALUE;
  26468. renderingMesh = (renderingMesh || mesh);
  26469. var indices = renderingMesh.getIndices();
  26470. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26471. var vertexIndex = indices[index];
  26472. if (vertexIndex < minVertexIndex)
  26473. minVertexIndex = vertexIndex;
  26474. if (vertexIndex > maxVertexIndex)
  26475. maxVertexIndex = vertexIndex;
  26476. }
  26477. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26478. };
  26479. return SubMesh;
  26480. }(BaseSubMesh));
  26481. BABYLON.SubMesh = SubMesh;
  26482. })(BABYLON || (BABYLON = {}));
  26483. //# sourceMappingURL=babylon.subMesh.js.map
  26484. var BABYLON;
  26485. (function (BABYLON) {
  26486. var EffectFallbacks = /** @class */ (function () {
  26487. function EffectFallbacks() {
  26488. this._defines = {};
  26489. this._currentRank = 32;
  26490. this._maxRank = -1;
  26491. }
  26492. EffectFallbacks.prototype.unBindMesh = function () {
  26493. this._mesh = null;
  26494. };
  26495. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26496. if (!this._defines[rank]) {
  26497. if (rank < this._currentRank) {
  26498. this._currentRank = rank;
  26499. }
  26500. if (rank > this._maxRank) {
  26501. this._maxRank = rank;
  26502. }
  26503. this._defines[rank] = new Array();
  26504. }
  26505. this._defines[rank].push(define);
  26506. };
  26507. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26508. this._mesh = mesh;
  26509. if (rank < this._currentRank) {
  26510. this._currentRank = rank;
  26511. }
  26512. if (rank > this._maxRank) {
  26513. this._maxRank = rank;
  26514. }
  26515. };
  26516. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26517. get: function () {
  26518. return this._currentRank <= this._maxRank;
  26519. },
  26520. enumerable: true,
  26521. configurable: true
  26522. });
  26523. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26524. // First we try to switch to CPU skinning
  26525. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26526. this._mesh.computeBonesUsingShaders = false;
  26527. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26528. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26529. var scene = this._mesh.getScene();
  26530. for (var index = 0; index < scene.meshes.length; index++) {
  26531. var otherMesh = scene.meshes[index];
  26532. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26533. otherMesh.computeBonesUsingShaders = false;
  26534. }
  26535. }
  26536. }
  26537. else {
  26538. var currentFallbacks = this._defines[this._currentRank];
  26539. if (currentFallbacks) {
  26540. for (var index = 0; index < currentFallbacks.length; index++) {
  26541. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26542. }
  26543. }
  26544. this._currentRank++;
  26545. }
  26546. return currentDefines;
  26547. };
  26548. return EffectFallbacks;
  26549. }());
  26550. BABYLON.EffectFallbacks = EffectFallbacks;
  26551. var EffectCreationOptions = /** @class */ (function () {
  26552. function EffectCreationOptions() {
  26553. }
  26554. return EffectCreationOptions;
  26555. }());
  26556. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26557. var Effect = /** @class */ (function () {
  26558. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26559. if (samplers === void 0) { samplers = null; }
  26560. if (defines === void 0) { defines = null; }
  26561. if (fallbacks === void 0) { fallbacks = null; }
  26562. if (onCompiled === void 0) { onCompiled = null; }
  26563. if (onError === void 0) { onError = null; }
  26564. var _this = this;
  26565. this.uniqueId = 0;
  26566. this.onCompileObservable = new BABYLON.Observable();
  26567. this.onErrorObservable = new BABYLON.Observable();
  26568. this.onBindObservable = new BABYLON.Observable();
  26569. this._uniformBuffersNames = {};
  26570. this._isReady = false;
  26571. this._compilationError = "";
  26572. this.name = baseName;
  26573. if (attributesNamesOrOptions.attributes) {
  26574. var options = attributesNamesOrOptions;
  26575. this._engine = uniformsNamesOrEngine;
  26576. this._attributesNames = options.attributes;
  26577. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26578. this._samplers = options.samplers;
  26579. this.defines = options.defines;
  26580. this.onError = options.onError;
  26581. this.onCompiled = options.onCompiled;
  26582. this._fallbacks = options.fallbacks;
  26583. this._indexParameters = options.indexParameters;
  26584. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26585. if (options.uniformBuffersNames) {
  26586. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26587. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26588. }
  26589. }
  26590. }
  26591. else {
  26592. this._engine = engine;
  26593. this.defines = defines;
  26594. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26595. this._samplers = samplers;
  26596. this._attributesNames = attributesNamesOrOptions;
  26597. this.onError = onError;
  26598. this.onCompiled = onCompiled;
  26599. this._indexParameters = indexParameters;
  26600. this._fallbacks = fallbacks;
  26601. }
  26602. this.uniqueId = Effect._uniqueIdSeed++;
  26603. var vertexSource;
  26604. var fragmentSource;
  26605. if (baseName.vertexElement) {
  26606. vertexSource = document.getElementById(baseName.vertexElement);
  26607. if (!vertexSource) {
  26608. vertexSource = baseName.vertexElement;
  26609. }
  26610. }
  26611. else {
  26612. vertexSource = baseName.vertex || baseName;
  26613. }
  26614. if (baseName.fragmentElement) {
  26615. fragmentSource = document.getElementById(baseName.fragmentElement);
  26616. if (!fragmentSource) {
  26617. fragmentSource = baseName.fragmentElement;
  26618. }
  26619. }
  26620. else {
  26621. fragmentSource = baseName.fragment || baseName;
  26622. }
  26623. this._loadVertexShader(vertexSource, function (vertexCode) {
  26624. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26625. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26626. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26627. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26628. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26629. if (baseName) {
  26630. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26631. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26632. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26633. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26634. }
  26635. else {
  26636. _this._vertexSourceCode = migratedVertexCode;
  26637. _this._fragmentSourceCode = migratedFragmentCode;
  26638. }
  26639. _this._prepareEffect();
  26640. });
  26641. });
  26642. });
  26643. });
  26644. });
  26645. });
  26646. }
  26647. Object.defineProperty(Effect.prototype, "key", {
  26648. get: function () {
  26649. return this._key;
  26650. },
  26651. enumerable: true,
  26652. configurable: true
  26653. });
  26654. // Properties
  26655. Effect.prototype.isReady = function () {
  26656. return this._isReady;
  26657. };
  26658. Effect.prototype.getEngine = function () {
  26659. return this._engine;
  26660. };
  26661. Effect.prototype.getProgram = function () {
  26662. return this._program;
  26663. };
  26664. Effect.prototype.getAttributesNames = function () {
  26665. return this._attributesNames;
  26666. };
  26667. Effect.prototype.getAttributeLocation = function (index) {
  26668. return this._attributes[index];
  26669. };
  26670. Effect.prototype.getAttributeLocationByName = function (name) {
  26671. var index = this._attributesNames.indexOf(name);
  26672. return this._attributes[index];
  26673. };
  26674. Effect.prototype.getAttributesCount = function () {
  26675. return this._attributes.length;
  26676. };
  26677. Effect.prototype.getUniformIndex = function (uniformName) {
  26678. return this._uniformsNames.indexOf(uniformName);
  26679. };
  26680. Effect.prototype.getUniform = function (uniformName) {
  26681. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26682. };
  26683. Effect.prototype.getSamplers = function () {
  26684. return this._samplers;
  26685. };
  26686. Effect.prototype.getCompilationError = function () {
  26687. return this._compilationError;
  26688. };
  26689. // Methods
  26690. Effect.prototype.executeWhenCompiled = function (func) {
  26691. if (this.isReady()) {
  26692. func(this);
  26693. return;
  26694. }
  26695. this.onCompileObservable.add(function (effect) {
  26696. func(effect);
  26697. });
  26698. };
  26699. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26700. if (BABYLON.Tools.IsWindowObjectExist()) {
  26701. // DOM element ?
  26702. if (vertex instanceof HTMLElement) {
  26703. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26704. callback(vertexCode);
  26705. return;
  26706. }
  26707. }
  26708. // Base64 encoded ?
  26709. if (vertex.substr(0, 7) === "base64:") {
  26710. var vertexBinary = window.atob(vertex.substr(7));
  26711. callback(vertexBinary);
  26712. return;
  26713. }
  26714. // Is in local store ?
  26715. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26716. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26717. return;
  26718. }
  26719. var vertexShaderUrl;
  26720. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26721. vertexShaderUrl = vertex;
  26722. }
  26723. else {
  26724. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26725. }
  26726. // Vertex shader
  26727. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26728. };
  26729. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26730. if (BABYLON.Tools.IsWindowObjectExist()) {
  26731. // DOM element ?
  26732. if (fragment instanceof HTMLElement) {
  26733. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26734. callback(fragmentCode);
  26735. return;
  26736. }
  26737. }
  26738. // Base64 encoded ?
  26739. if (fragment.substr(0, 7) === "base64:") {
  26740. var fragmentBinary = window.atob(fragment.substr(7));
  26741. callback(fragmentBinary);
  26742. return;
  26743. }
  26744. // Is in local store ?
  26745. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26746. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26747. return;
  26748. }
  26749. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26750. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26751. return;
  26752. }
  26753. var fragmentShaderUrl;
  26754. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26755. fragmentShaderUrl = fragment;
  26756. }
  26757. else {
  26758. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26759. }
  26760. // Fragment shader
  26761. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26762. };
  26763. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26764. // Rebuild shaders source code
  26765. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26766. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26767. vertexCode = prefix + vertexCode;
  26768. fragmentCode = prefix + fragmentCode;
  26769. // Number lines of shaders source code
  26770. var i = 2;
  26771. var regex = /\n/gm;
  26772. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26773. i = 2;
  26774. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26775. // Dump shaders name and formatted source code
  26776. if (this.name.vertexElement) {
  26777. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26778. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26779. }
  26780. else if (this.name.vertex) {
  26781. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26782. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26783. }
  26784. else {
  26785. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26786. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26787. }
  26788. };
  26789. ;
  26790. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26791. var preparedSourceCode = this._processPrecision(sourceCode);
  26792. if (this._engine.webGLVersion == 1) {
  26793. callback(preparedSourceCode);
  26794. return;
  26795. }
  26796. // Already converted
  26797. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26798. callback(preparedSourceCode.replace("#version 300 es", ""));
  26799. return;
  26800. }
  26801. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26802. // Remove extensions
  26803. // #extension GL_OES_standard_derivatives : enable
  26804. // #extension GL_EXT_shader_texture_lod : enable
  26805. // #extension GL_EXT_frag_depth : enable
  26806. // #extension GL_EXT_draw_buffers : require
  26807. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26808. var result = preparedSourceCode.replace(regex, "");
  26809. // Migrate to GLSL v300
  26810. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26811. result = result.replace(/attribute[ \t]/g, "in ");
  26812. result = result.replace(/[ \t]attribute/g, " in");
  26813. if (isFragment) {
  26814. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26815. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26816. result = result.replace(/texture2D\s*\(/g, "texture(");
  26817. result = result.replace(/textureCube\s*\(/g, "texture(");
  26818. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26819. result = result.replace(/gl_FragColor/g, "glFragColor");
  26820. result = result.replace(/gl_FragData/g, "glFragData");
  26821. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26822. }
  26823. callback(result);
  26824. };
  26825. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26826. var _this = this;
  26827. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26828. var match = regex.exec(sourceCode);
  26829. var returnValue = new String(sourceCode);
  26830. while (match != null) {
  26831. var includeFile = match[1];
  26832. // Uniform declaration
  26833. if (includeFile.indexOf("__decl__") !== -1) {
  26834. includeFile = includeFile.replace(/__decl__/, "");
  26835. if (this._engine.supportsUniformBuffers) {
  26836. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26837. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26838. }
  26839. includeFile = includeFile + "Declaration";
  26840. }
  26841. if (Effect.IncludesShadersStore[includeFile]) {
  26842. // Substitution
  26843. var includeContent = Effect.IncludesShadersStore[includeFile];
  26844. if (match[2]) {
  26845. var splits = match[3].split(",");
  26846. for (var index = 0; index < splits.length; index += 2) {
  26847. var source = new RegExp(splits[index], "g");
  26848. var dest = splits[index + 1];
  26849. includeContent = includeContent.replace(source, dest);
  26850. }
  26851. }
  26852. if (match[4]) {
  26853. var indexString = match[5];
  26854. if (indexString.indexOf("..") !== -1) {
  26855. var indexSplits = indexString.split("..");
  26856. var minIndex = parseInt(indexSplits[0]);
  26857. var maxIndex = parseInt(indexSplits[1]);
  26858. var sourceIncludeContent = includeContent.slice(0);
  26859. includeContent = "";
  26860. if (isNaN(maxIndex)) {
  26861. maxIndex = this._indexParameters[indexSplits[1]];
  26862. }
  26863. for (var i = minIndex; i < maxIndex; i++) {
  26864. if (!this._engine.supportsUniformBuffers) {
  26865. // Ubo replacement
  26866. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26867. return p1 + "{X}";
  26868. });
  26869. }
  26870. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26871. }
  26872. }
  26873. else {
  26874. if (!this._engine.supportsUniformBuffers) {
  26875. // Ubo replacement
  26876. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26877. return p1 + "{X}";
  26878. });
  26879. }
  26880. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26881. }
  26882. }
  26883. // Replace
  26884. returnValue = returnValue.replace(match[0], includeContent);
  26885. }
  26886. else {
  26887. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26888. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26889. Effect.IncludesShadersStore[includeFile] = fileContent;
  26890. _this._processIncludes(returnValue, callback);
  26891. });
  26892. return;
  26893. }
  26894. match = regex.exec(sourceCode);
  26895. }
  26896. callback(returnValue);
  26897. };
  26898. Effect.prototype._processPrecision = function (source) {
  26899. if (source.indexOf("precision highp float") === -1) {
  26900. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26901. source = "precision mediump float;\n" + source;
  26902. }
  26903. else {
  26904. source = "precision highp float;\n" + source;
  26905. }
  26906. }
  26907. else {
  26908. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26909. source = source.replace("precision highp float", "precision mediump float");
  26910. }
  26911. }
  26912. return source;
  26913. };
  26914. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26915. var _this = this;
  26916. this._isReady = false;
  26917. this._vertexSourceCodeOverride = vertexSourceCode;
  26918. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26919. this.onError = function (effect, error) {
  26920. if (onError) {
  26921. onError(error);
  26922. }
  26923. };
  26924. this.onCompiled = function () {
  26925. var scenes = _this.getEngine().scenes;
  26926. for (var i = 0; i < scenes.length; i++) {
  26927. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26928. }
  26929. if (onCompiled) {
  26930. onCompiled(_this._program);
  26931. }
  26932. };
  26933. this._fallbacks = null;
  26934. this._prepareEffect();
  26935. };
  26936. Effect.prototype._prepareEffect = function () {
  26937. var attributesNames = this._attributesNames;
  26938. var defines = this.defines;
  26939. var fallbacks = this._fallbacks;
  26940. this._valueCache = {};
  26941. var previousProgram = this._program;
  26942. try {
  26943. var engine = this._engine;
  26944. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26945. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26946. }
  26947. else {
  26948. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26949. }
  26950. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26951. if (engine.supportsUniformBuffers) {
  26952. for (var name in this._uniformBuffersNames) {
  26953. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26954. }
  26955. }
  26956. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26957. this._attributes = engine.getAttributes(this._program, attributesNames);
  26958. var index;
  26959. for (index = 0; index < this._samplers.length; index++) {
  26960. var sampler = this.getUniform(this._samplers[index]);
  26961. if (sampler == null) {
  26962. this._samplers.splice(index, 1);
  26963. index--;
  26964. }
  26965. }
  26966. engine.bindSamplers(this);
  26967. this._compilationError = "";
  26968. this._isReady = true;
  26969. if (this.onCompiled) {
  26970. this.onCompiled(this);
  26971. }
  26972. this.onCompileObservable.notifyObservers(this);
  26973. this.onCompileObservable.clear();
  26974. // Unbind mesh reference in fallbacks
  26975. if (this._fallbacks) {
  26976. this._fallbacks.unBindMesh();
  26977. }
  26978. if (previousProgram) {
  26979. this.getEngine()._deleteProgram(previousProgram);
  26980. }
  26981. }
  26982. catch (e) {
  26983. this._compilationError = e.message;
  26984. // Let's go through fallbacks then
  26985. BABYLON.Tools.Error("Unable to compile effect:");
  26986. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26987. return " " + uniform;
  26988. }));
  26989. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26990. return " " + attribute;
  26991. }));
  26992. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26993. BABYLON.Tools.Error("Error: " + this._compilationError);
  26994. if (previousProgram) {
  26995. this._program = previousProgram;
  26996. this._isReady = true;
  26997. if (this.onError) {
  26998. this.onError(this, this._compilationError);
  26999. }
  27000. this.onErrorObservable.notifyObservers(this);
  27001. }
  27002. if (fallbacks && fallbacks.isMoreFallbacks) {
  27003. BABYLON.Tools.Error("Trying next fallback.");
  27004. this.defines = fallbacks.reduce(this.defines);
  27005. this._prepareEffect();
  27006. }
  27007. else {
  27008. if (this.onError) {
  27009. this.onError(this, this._compilationError);
  27010. }
  27011. this.onErrorObservable.notifyObservers(this);
  27012. this.onErrorObservable.clear();
  27013. // Unbind mesh reference in fallbacks
  27014. if (this._fallbacks) {
  27015. this._fallbacks.unBindMesh();
  27016. }
  27017. }
  27018. }
  27019. };
  27020. Object.defineProperty(Effect.prototype, "isSupported", {
  27021. get: function () {
  27022. return this._compilationError === "";
  27023. },
  27024. enumerable: true,
  27025. configurable: true
  27026. });
  27027. Effect.prototype._bindTexture = function (channel, texture) {
  27028. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  27029. };
  27030. Effect.prototype.setTexture = function (channel, texture) {
  27031. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  27032. };
  27033. Effect.prototype.setTextureArray = function (channel, textures) {
  27034. if (this._samplers.indexOf(channel + "Ex") === -1) {
  27035. var initialPos = this._samplers.indexOf(channel);
  27036. for (var index = 1; index < textures.length; index++) {
  27037. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  27038. }
  27039. }
  27040. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  27041. };
  27042. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  27043. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  27044. };
  27045. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  27046. var cache = this._valueCache[uniformName];
  27047. var flag = matrix.updateFlag;
  27048. if (cache !== undefined && cache === flag) {
  27049. return false;
  27050. }
  27051. this._valueCache[uniformName] = flag;
  27052. return true;
  27053. };
  27054. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  27055. var cache = this._valueCache[uniformName];
  27056. if (!cache) {
  27057. cache = [x, y];
  27058. this._valueCache[uniformName] = cache;
  27059. return true;
  27060. }
  27061. var changed = false;
  27062. if (cache[0] !== x) {
  27063. cache[0] = x;
  27064. changed = true;
  27065. }
  27066. if (cache[1] !== y) {
  27067. cache[1] = y;
  27068. changed = true;
  27069. }
  27070. return changed;
  27071. };
  27072. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  27073. var cache = this._valueCache[uniformName];
  27074. if (!cache) {
  27075. cache = [x, y, z];
  27076. this._valueCache[uniformName] = cache;
  27077. return true;
  27078. }
  27079. var changed = false;
  27080. if (cache[0] !== x) {
  27081. cache[0] = x;
  27082. changed = true;
  27083. }
  27084. if (cache[1] !== y) {
  27085. cache[1] = y;
  27086. changed = true;
  27087. }
  27088. if (cache[2] !== z) {
  27089. cache[2] = z;
  27090. changed = true;
  27091. }
  27092. return changed;
  27093. };
  27094. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  27095. var cache = this._valueCache[uniformName];
  27096. if (!cache) {
  27097. cache = [x, y, z, w];
  27098. this._valueCache[uniformName] = cache;
  27099. return true;
  27100. }
  27101. var changed = false;
  27102. if (cache[0] !== x) {
  27103. cache[0] = x;
  27104. changed = true;
  27105. }
  27106. if (cache[1] !== y) {
  27107. cache[1] = y;
  27108. changed = true;
  27109. }
  27110. if (cache[2] !== z) {
  27111. cache[2] = z;
  27112. changed = true;
  27113. }
  27114. if (cache[3] !== w) {
  27115. cache[3] = w;
  27116. changed = true;
  27117. }
  27118. return changed;
  27119. };
  27120. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  27121. var bufferName = this._uniformBuffersNames[name];
  27122. if (Effect._baseCache[bufferName] === buffer) {
  27123. return;
  27124. }
  27125. Effect._baseCache[bufferName] = buffer;
  27126. this._engine.bindUniformBufferBase(buffer, bufferName);
  27127. };
  27128. Effect.prototype.bindUniformBlock = function (blockName, index) {
  27129. this._engine.bindUniformBlock(this._program, blockName, index);
  27130. };
  27131. Effect.prototype.setIntArray = function (uniformName, array) {
  27132. this._valueCache[uniformName] = null;
  27133. this._engine.setIntArray(this.getUniform(uniformName), array);
  27134. return this;
  27135. };
  27136. Effect.prototype.setIntArray2 = function (uniformName, array) {
  27137. this._valueCache[uniformName] = null;
  27138. this._engine.setIntArray2(this.getUniform(uniformName), array);
  27139. return this;
  27140. };
  27141. Effect.prototype.setIntArray3 = function (uniformName, array) {
  27142. this._valueCache[uniformName] = null;
  27143. this._engine.setIntArray3(this.getUniform(uniformName), array);
  27144. return this;
  27145. };
  27146. Effect.prototype.setIntArray4 = function (uniformName, array) {
  27147. this._valueCache[uniformName] = null;
  27148. this._engine.setIntArray4(this.getUniform(uniformName), array);
  27149. return this;
  27150. };
  27151. Effect.prototype.setFloatArray = function (uniformName, array) {
  27152. this._valueCache[uniformName] = null;
  27153. this._engine.setFloatArray(this.getUniform(uniformName), array);
  27154. return this;
  27155. };
  27156. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  27157. this._valueCache[uniformName] = null;
  27158. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  27159. return this;
  27160. };
  27161. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  27162. this._valueCache[uniformName] = null;
  27163. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  27164. return this;
  27165. };
  27166. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  27167. this._valueCache[uniformName] = null;
  27168. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  27169. return this;
  27170. };
  27171. Effect.prototype.setArray = function (uniformName, array) {
  27172. this._valueCache[uniformName] = null;
  27173. this._engine.setArray(this.getUniform(uniformName), array);
  27174. return this;
  27175. };
  27176. Effect.prototype.setArray2 = function (uniformName, array) {
  27177. this._valueCache[uniformName] = null;
  27178. this._engine.setArray2(this.getUniform(uniformName), array);
  27179. return this;
  27180. };
  27181. Effect.prototype.setArray3 = function (uniformName, array) {
  27182. this._valueCache[uniformName] = null;
  27183. this._engine.setArray3(this.getUniform(uniformName), array);
  27184. return this;
  27185. };
  27186. Effect.prototype.setArray4 = function (uniformName, array) {
  27187. this._valueCache[uniformName] = null;
  27188. this._engine.setArray4(this.getUniform(uniformName), array);
  27189. return this;
  27190. };
  27191. Effect.prototype.setMatrices = function (uniformName, matrices) {
  27192. if (!matrices) {
  27193. return this;
  27194. }
  27195. this._valueCache[uniformName] = null;
  27196. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  27197. return this;
  27198. };
  27199. Effect.prototype.setMatrix = function (uniformName, matrix) {
  27200. if (this._cacheMatrix(uniformName, matrix)) {
  27201. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  27202. }
  27203. return this;
  27204. };
  27205. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27206. this._valueCache[uniformName] = null;
  27207. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27208. return this;
  27209. };
  27210. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27211. this._valueCache[uniformName] = null;
  27212. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27213. return this;
  27214. };
  27215. Effect.prototype.setFloat = function (uniformName, value) {
  27216. var cache = this._valueCache[uniformName];
  27217. if (cache !== undefined && cache === value)
  27218. return this;
  27219. this._valueCache[uniformName] = value;
  27220. this._engine.setFloat(this.getUniform(uniformName), value);
  27221. return this;
  27222. };
  27223. Effect.prototype.setBool = function (uniformName, bool) {
  27224. var cache = this._valueCache[uniformName];
  27225. if (cache !== undefined && cache === bool)
  27226. return this;
  27227. this._valueCache[uniformName] = bool;
  27228. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27229. return this;
  27230. };
  27231. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27232. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27233. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27234. }
  27235. return this;
  27236. };
  27237. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27238. if (this._cacheFloat2(uniformName, x, y)) {
  27239. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27240. }
  27241. return this;
  27242. };
  27243. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27244. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27245. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27246. }
  27247. return this;
  27248. };
  27249. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27250. if (this._cacheFloat3(uniformName, x, y, z)) {
  27251. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27252. }
  27253. return this;
  27254. };
  27255. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27256. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27257. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27258. }
  27259. return this;
  27260. };
  27261. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27262. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27263. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27264. }
  27265. return this;
  27266. };
  27267. Effect.prototype.setColor3 = function (uniformName, color3) {
  27268. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27269. this._engine.setColor3(this.getUniform(uniformName), color3);
  27270. }
  27271. return this;
  27272. };
  27273. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27274. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27275. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27276. }
  27277. return this;
  27278. };
  27279. Effect.ResetCache = function () {
  27280. Effect._baseCache = {};
  27281. };
  27282. Effect._uniqueIdSeed = 0;
  27283. Effect._baseCache = {};
  27284. // Statics
  27285. Effect.ShadersStore = {};
  27286. Effect.IncludesShadersStore = {};
  27287. return Effect;
  27288. }());
  27289. BABYLON.Effect = Effect;
  27290. })(BABYLON || (BABYLON = {}));
  27291. //# sourceMappingURL=babylon.effect.js.map
  27292. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27293. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27294. s = arguments[i];
  27295. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27296. t[p] = s[p];
  27297. }
  27298. return t;
  27299. };
  27300. var BABYLON;
  27301. (function (BABYLON) {
  27302. var MaterialDefines = /** @class */ (function () {
  27303. function MaterialDefines() {
  27304. this._isDirty = true;
  27305. this._areLightsDirty = true;
  27306. this._areAttributesDirty = true;
  27307. this._areTexturesDirty = true;
  27308. this._areFresnelDirty = true;
  27309. this._areMiscDirty = true;
  27310. this._areImageProcessingDirty = true;
  27311. this._normals = false;
  27312. this._uvs = false;
  27313. this._needNormals = false;
  27314. this._needUVs = false;
  27315. }
  27316. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27317. get: function () {
  27318. return this._isDirty;
  27319. },
  27320. enumerable: true,
  27321. configurable: true
  27322. });
  27323. MaterialDefines.prototype.markAsProcessed = function () {
  27324. this._isDirty = false;
  27325. this._areAttributesDirty = false;
  27326. this._areTexturesDirty = false;
  27327. this._areFresnelDirty = false;
  27328. this._areLightsDirty = false;
  27329. this._areMiscDirty = false;
  27330. this._areImageProcessingDirty = false;
  27331. };
  27332. MaterialDefines.prototype.markAsUnprocessed = function () {
  27333. this._isDirty = true;
  27334. };
  27335. MaterialDefines.prototype.markAllAsDirty = function () {
  27336. this._areTexturesDirty = true;
  27337. this._areAttributesDirty = true;
  27338. this._areLightsDirty = true;
  27339. this._areFresnelDirty = true;
  27340. this._areMiscDirty = true;
  27341. this._areImageProcessingDirty = true;
  27342. this._isDirty = true;
  27343. };
  27344. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27345. this._areImageProcessingDirty = true;
  27346. this._isDirty = true;
  27347. };
  27348. MaterialDefines.prototype.markAsLightDirty = function () {
  27349. this._areLightsDirty = true;
  27350. this._isDirty = true;
  27351. };
  27352. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27353. this._areAttributesDirty = true;
  27354. this._isDirty = true;
  27355. };
  27356. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27357. this._areTexturesDirty = true;
  27358. this._isDirty = true;
  27359. };
  27360. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27361. this._areFresnelDirty = true;
  27362. this._isDirty = true;
  27363. };
  27364. MaterialDefines.prototype.markAsMiscDirty = function () {
  27365. this._areMiscDirty = true;
  27366. this._isDirty = true;
  27367. };
  27368. MaterialDefines.prototype.rebuild = function () {
  27369. if (this._keys) {
  27370. delete this._keys;
  27371. }
  27372. this._keys = [];
  27373. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27374. var key = _a[_i];
  27375. if (key[0] === "_") {
  27376. continue;
  27377. }
  27378. this._keys.push(key);
  27379. }
  27380. };
  27381. MaterialDefines.prototype.isEqual = function (other) {
  27382. if (this._keys.length !== other._keys.length) {
  27383. return false;
  27384. }
  27385. for (var index = 0; index < this._keys.length; index++) {
  27386. var prop = this._keys[index];
  27387. if (this[prop] !== other[prop]) {
  27388. return false;
  27389. }
  27390. }
  27391. return true;
  27392. };
  27393. MaterialDefines.prototype.cloneTo = function (other) {
  27394. if (this._keys.length !== other._keys.length) {
  27395. other._keys = this._keys.slice(0);
  27396. }
  27397. for (var index = 0; index < this._keys.length; index++) {
  27398. var prop = this._keys[index];
  27399. other[prop] = this[prop];
  27400. }
  27401. };
  27402. MaterialDefines.prototype.reset = function () {
  27403. for (var index = 0; index < this._keys.length; index++) {
  27404. var prop = this._keys[index];
  27405. if (typeof (this[prop]) === "number") {
  27406. this[prop] = 0;
  27407. }
  27408. else {
  27409. this[prop] = false;
  27410. }
  27411. }
  27412. };
  27413. MaterialDefines.prototype.toString = function () {
  27414. var result = "";
  27415. for (var index = 0; index < this._keys.length; index++) {
  27416. var prop = this._keys[index];
  27417. var value = this[prop];
  27418. if (typeof (value) === "number") {
  27419. result += "#define " + prop + " " + this[prop] + "\n";
  27420. }
  27421. else if (value) {
  27422. result += "#define " + prop + "\n";
  27423. }
  27424. }
  27425. return result;
  27426. };
  27427. return MaterialDefines;
  27428. }());
  27429. BABYLON.MaterialDefines = MaterialDefines;
  27430. var Material = /** @class */ (function () {
  27431. function Material(name, scene, doNotAdd) {
  27432. this.checkReadyOnEveryCall = false;
  27433. this.checkReadyOnlyOnce = false;
  27434. this.state = "";
  27435. this.alpha = 1.0;
  27436. this._backFaceCulling = true;
  27437. this.doNotSerialize = false;
  27438. this.storeEffectOnSubMeshes = false;
  27439. /**
  27440. * An event triggered when the material is disposed.
  27441. * @type {BABYLON.Observable}
  27442. */
  27443. this.onDisposeObservable = new BABYLON.Observable();
  27444. /**
  27445. * An event triggered when the material is bound.
  27446. * @type {BABYLON.Observable}
  27447. */
  27448. this.onBindObservable = new BABYLON.Observable();
  27449. /**
  27450. * An event triggered when the material is unbound.
  27451. * @type {BABYLON.Observable}
  27452. */
  27453. this.onUnBindObservable = new BABYLON.Observable();
  27454. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27455. this._needDepthPrePass = false;
  27456. this.disableDepthWrite = false;
  27457. this.forceDepthWrite = false;
  27458. this.separateCullingPass = false;
  27459. this._fogEnabled = true;
  27460. this.pointSize = 1.0;
  27461. this.zOffset = 0;
  27462. this._wasPreviouslyReady = false;
  27463. this._fillMode = Material.TriangleFillMode;
  27464. this.name = name;
  27465. this.id = name || BABYLON.Tools.RandomId();
  27466. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27467. if (this._scene.useRightHandedSystem) {
  27468. this.sideOrientation = Material.ClockWiseSideOrientation;
  27469. }
  27470. else {
  27471. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27472. }
  27473. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27474. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27475. if (!doNotAdd) {
  27476. this._scene.materials.push(this);
  27477. }
  27478. }
  27479. Object.defineProperty(Material, "TriangleFillMode", {
  27480. get: function () {
  27481. return Material._TriangleFillMode;
  27482. },
  27483. enumerable: true,
  27484. configurable: true
  27485. });
  27486. Object.defineProperty(Material, "WireFrameFillMode", {
  27487. get: function () {
  27488. return Material._WireFrameFillMode;
  27489. },
  27490. enumerable: true,
  27491. configurable: true
  27492. });
  27493. Object.defineProperty(Material, "PointFillMode", {
  27494. get: function () {
  27495. return Material._PointFillMode;
  27496. },
  27497. enumerable: true,
  27498. configurable: true
  27499. });
  27500. Object.defineProperty(Material, "PointListDrawMode", {
  27501. get: function () {
  27502. return Material._PointListDrawMode;
  27503. },
  27504. enumerable: true,
  27505. configurable: true
  27506. });
  27507. Object.defineProperty(Material, "LineListDrawMode", {
  27508. get: function () {
  27509. return Material._LineListDrawMode;
  27510. },
  27511. enumerable: true,
  27512. configurable: true
  27513. });
  27514. Object.defineProperty(Material, "LineLoopDrawMode", {
  27515. get: function () {
  27516. return Material._LineLoopDrawMode;
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. Object.defineProperty(Material, "LineStripDrawMode", {
  27522. get: function () {
  27523. return Material._LineStripDrawMode;
  27524. },
  27525. enumerable: true,
  27526. configurable: true
  27527. });
  27528. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27529. get: function () {
  27530. return Material._TriangleStripDrawMode;
  27531. },
  27532. enumerable: true,
  27533. configurable: true
  27534. });
  27535. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27536. get: function () {
  27537. return Material._TriangleFanDrawMode;
  27538. },
  27539. enumerable: true,
  27540. configurable: true
  27541. });
  27542. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27543. get: function () {
  27544. return Material._ClockWiseSideOrientation;
  27545. },
  27546. enumerable: true,
  27547. configurable: true
  27548. });
  27549. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27550. get: function () {
  27551. return Material._CounterClockWiseSideOrientation;
  27552. },
  27553. enumerable: true,
  27554. configurable: true
  27555. });
  27556. Object.defineProperty(Material, "TextureDirtyFlag", {
  27557. get: function () {
  27558. return Material._TextureDirtyFlag;
  27559. },
  27560. enumerable: true,
  27561. configurable: true
  27562. });
  27563. Object.defineProperty(Material, "LightDirtyFlag", {
  27564. get: function () {
  27565. return Material._LightDirtyFlag;
  27566. },
  27567. enumerable: true,
  27568. configurable: true
  27569. });
  27570. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27571. get: function () {
  27572. return Material._FresnelDirtyFlag;
  27573. },
  27574. enumerable: true,
  27575. configurable: true
  27576. });
  27577. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27578. get: function () {
  27579. return Material._AttributesDirtyFlag;
  27580. },
  27581. enumerable: true,
  27582. configurable: true
  27583. });
  27584. Object.defineProperty(Material, "MiscDirtyFlag", {
  27585. get: function () {
  27586. return Material._MiscDirtyFlag;
  27587. },
  27588. enumerable: true,
  27589. configurable: true
  27590. });
  27591. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27592. get: function () {
  27593. return this._backFaceCulling;
  27594. },
  27595. set: function (value) {
  27596. if (this._backFaceCulling === value) {
  27597. return;
  27598. }
  27599. this._backFaceCulling = value;
  27600. this.markAsDirty(Material.TextureDirtyFlag);
  27601. },
  27602. enumerable: true,
  27603. configurable: true
  27604. });
  27605. Object.defineProperty(Material.prototype, "onDispose", {
  27606. set: function (callback) {
  27607. if (this._onDisposeObserver) {
  27608. this.onDisposeObservable.remove(this._onDisposeObserver);
  27609. }
  27610. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27611. },
  27612. enumerable: true,
  27613. configurable: true
  27614. });
  27615. Object.defineProperty(Material.prototype, "onBind", {
  27616. set: function (callback) {
  27617. if (this._onBindObserver) {
  27618. this.onBindObservable.remove(this._onBindObserver);
  27619. }
  27620. this._onBindObserver = this.onBindObservable.add(callback);
  27621. },
  27622. enumerable: true,
  27623. configurable: true
  27624. });
  27625. Object.defineProperty(Material.prototype, "alphaMode", {
  27626. get: function () {
  27627. return this._alphaMode;
  27628. },
  27629. set: function (value) {
  27630. if (this._alphaMode === value) {
  27631. return;
  27632. }
  27633. this._alphaMode = value;
  27634. this.markAsDirty(Material.TextureDirtyFlag);
  27635. },
  27636. enumerable: true,
  27637. configurable: true
  27638. });
  27639. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27640. get: function () {
  27641. return this._needDepthPrePass;
  27642. },
  27643. set: function (value) {
  27644. if (this._needDepthPrePass === value) {
  27645. return;
  27646. }
  27647. this._needDepthPrePass = value;
  27648. if (this._needDepthPrePass) {
  27649. this.checkReadyOnEveryCall = true;
  27650. }
  27651. },
  27652. enumerable: true,
  27653. configurable: true
  27654. });
  27655. Object.defineProperty(Material.prototype, "fogEnabled", {
  27656. get: function () {
  27657. return this._fogEnabled;
  27658. },
  27659. set: function (value) {
  27660. if (this._fogEnabled === value) {
  27661. return;
  27662. }
  27663. this._fogEnabled = value;
  27664. this.markAsDirty(Material.MiscDirtyFlag);
  27665. },
  27666. enumerable: true,
  27667. configurable: true
  27668. });
  27669. Object.defineProperty(Material.prototype, "wireframe", {
  27670. get: function () {
  27671. return this._fillMode === Material.WireFrameFillMode;
  27672. },
  27673. set: function (value) {
  27674. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27675. },
  27676. enumerable: true,
  27677. configurable: true
  27678. });
  27679. Object.defineProperty(Material.prototype, "pointsCloud", {
  27680. get: function () {
  27681. return this._fillMode === Material.PointFillMode;
  27682. },
  27683. set: function (value) {
  27684. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27685. },
  27686. enumerable: true,
  27687. configurable: true
  27688. });
  27689. Object.defineProperty(Material.prototype, "fillMode", {
  27690. get: function () {
  27691. return this._fillMode;
  27692. },
  27693. set: function (value) {
  27694. if (this._fillMode === value) {
  27695. return;
  27696. }
  27697. this._fillMode = value;
  27698. this.markAsDirty(Material.MiscDirtyFlag);
  27699. },
  27700. enumerable: true,
  27701. configurable: true
  27702. });
  27703. /**
  27704. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27705. * subclasses should override adding information pertainent to themselves
  27706. */
  27707. Material.prototype.toString = function (fullDetails) {
  27708. var ret = "Name: " + this.name;
  27709. if (fullDetails) {
  27710. }
  27711. return ret;
  27712. };
  27713. /**
  27714. * Child classes can use it to update shaders
  27715. */
  27716. Material.prototype.getClassName = function () {
  27717. return "Material";
  27718. };
  27719. Object.defineProperty(Material.prototype, "isFrozen", {
  27720. get: function () {
  27721. return this.checkReadyOnlyOnce;
  27722. },
  27723. enumerable: true,
  27724. configurable: true
  27725. });
  27726. Material.prototype.freeze = function () {
  27727. this.checkReadyOnlyOnce = true;
  27728. };
  27729. Material.prototype.unfreeze = function () {
  27730. this.checkReadyOnlyOnce = false;
  27731. };
  27732. Material.prototype.isReady = function (mesh, useInstances) {
  27733. return true;
  27734. };
  27735. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27736. return false;
  27737. };
  27738. Material.prototype.getEffect = function () {
  27739. return this._effect;
  27740. };
  27741. Material.prototype.getScene = function () {
  27742. return this._scene;
  27743. };
  27744. Material.prototype.needAlphaBlending = function () {
  27745. return (this.alpha < 1.0);
  27746. };
  27747. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27748. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27749. };
  27750. Material.prototype.needAlphaTesting = function () {
  27751. return false;
  27752. };
  27753. Material.prototype.getAlphaTestTexture = function () {
  27754. return null;
  27755. };
  27756. Material.prototype.markDirty = function () {
  27757. this._wasPreviouslyReady = false;
  27758. };
  27759. Material.prototype._preBind = function (effect, overrideOrientation) {
  27760. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27761. var engine = this._scene.getEngine();
  27762. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27763. var reverse = orientation === Material.ClockWiseSideOrientation;
  27764. engine.enableEffect(effect ? effect : this._effect);
  27765. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27766. return reverse;
  27767. };
  27768. Material.prototype.bind = function (world, mesh) {
  27769. };
  27770. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27771. };
  27772. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27773. };
  27774. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27775. sceneUbo.bindToEffect(effect, "Scene");
  27776. };
  27777. Material.prototype.bindView = function (effect) {
  27778. if (!this._useUBO) {
  27779. effect.setMatrix("view", this.getScene().getViewMatrix());
  27780. }
  27781. else {
  27782. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27783. }
  27784. };
  27785. Material.prototype.bindViewProjection = function (effect) {
  27786. if (!this._useUBO) {
  27787. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27788. }
  27789. else {
  27790. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27791. }
  27792. };
  27793. Material.prototype._afterBind = function (mesh) {
  27794. this._scene._cachedMaterial = this;
  27795. if (mesh) {
  27796. this._scene._cachedVisibility = mesh.visibility;
  27797. }
  27798. else {
  27799. this._scene._cachedVisibility = 1;
  27800. }
  27801. if (mesh) {
  27802. this.onBindObservable.notifyObservers(mesh);
  27803. }
  27804. if (this.disableDepthWrite) {
  27805. var engine = this._scene.getEngine();
  27806. this._cachedDepthWriteState = engine.getDepthWrite();
  27807. engine.setDepthWrite(false);
  27808. }
  27809. };
  27810. Material.prototype.unbind = function () {
  27811. this.onUnBindObservable.notifyObservers(this);
  27812. if (this.disableDepthWrite) {
  27813. var engine = this._scene.getEngine();
  27814. engine.setDepthWrite(this._cachedDepthWriteState);
  27815. }
  27816. };
  27817. Material.prototype.getActiveTextures = function () {
  27818. return [];
  27819. };
  27820. Material.prototype.hasTexture = function (texture) {
  27821. return false;
  27822. };
  27823. Material.prototype.clone = function (name) {
  27824. return null;
  27825. };
  27826. Material.prototype.getBindedMeshes = function () {
  27827. var result = new Array();
  27828. for (var index = 0; index < this._scene.meshes.length; index++) {
  27829. var mesh = this._scene.meshes[index];
  27830. if (mesh.material === this) {
  27831. result.push(mesh);
  27832. }
  27833. }
  27834. return result;
  27835. };
  27836. /**
  27837. * Force shader compilation including textures ready check
  27838. */
  27839. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27840. var _this = this;
  27841. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  27842. var subMesh = new BABYLON.BaseSubMesh();
  27843. var scene = this.getScene();
  27844. var engine = scene.getEngine();
  27845. var checkReady = function () {
  27846. if (!_this._scene || !_this._scene.getEngine()) {
  27847. return;
  27848. }
  27849. if (subMesh._materialDefines) {
  27850. subMesh._materialDefines._renderId = -1;
  27851. }
  27852. var alphaTestState = engine.getAlphaTesting();
  27853. var clipPlaneState = scene.clipPlane;
  27854. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  27855. if (localOptions.clipPlane) {
  27856. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27857. }
  27858. if (_this.storeEffectOnSubMeshes) {
  27859. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27860. if (onCompiled) {
  27861. onCompiled(_this);
  27862. }
  27863. }
  27864. else {
  27865. setTimeout(checkReady, 16);
  27866. }
  27867. }
  27868. else {
  27869. if (_this.isReady(mesh)) {
  27870. if (onCompiled) {
  27871. onCompiled(_this);
  27872. }
  27873. }
  27874. else {
  27875. setTimeout(checkReady, 16);
  27876. }
  27877. }
  27878. engine.setAlphaTesting(alphaTestState);
  27879. if (options && options.clipPlane) {
  27880. scene.clipPlane = clipPlaneState;
  27881. }
  27882. };
  27883. checkReady();
  27884. };
  27885. Material.prototype.markAsDirty = function (flag) {
  27886. if (flag & Material.TextureDirtyFlag) {
  27887. this._markAllSubMeshesAsTexturesDirty();
  27888. }
  27889. if (flag & Material.LightDirtyFlag) {
  27890. this._markAllSubMeshesAsLightsDirty();
  27891. }
  27892. if (flag & Material.FresnelDirtyFlag) {
  27893. this._markAllSubMeshesAsFresnelDirty();
  27894. }
  27895. if (flag & Material.AttributesDirtyFlag) {
  27896. this._markAllSubMeshesAsAttributesDirty();
  27897. }
  27898. if (flag & Material.MiscDirtyFlag) {
  27899. this._markAllSubMeshesAsMiscDirty();
  27900. }
  27901. this.getScene().resetCachedMaterial();
  27902. };
  27903. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27904. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27905. var mesh = _a[_i];
  27906. if (!mesh.subMeshes) {
  27907. continue;
  27908. }
  27909. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27910. var subMesh = _c[_b];
  27911. if (subMesh.getMaterial() !== this) {
  27912. continue;
  27913. }
  27914. if (!subMesh._materialDefines) {
  27915. continue;
  27916. }
  27917. func(subMesh._materialDefines);
  27918. }
  27919. }
  27920. };
  27921. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27922. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27923. };
  27924. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27925. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27926. };
  27927. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27928. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27929. };
  27930. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27931. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27932. };
  27933. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27934. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27935. };
  27936. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27937. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27938. };
  27939. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27940. // Animations
  27941. this.getScene().stopAnimation(this);
  27942. // Remove from scene
  27943. var index = this._scene.materials.indexOf(this);
  27944. if (index >= 0) {
  27945. this._scene.materials.splice(index, 1);
  27946. }
  27947. // Remove from meshes
  27948. for (index = 0; index < this._scene.meshes.length; index++) {
  27949. var mesh = this._scene.meshes[index];
  27950. if (mesh.material === this) {
  27951. mesh.material = null;
  27952. if (mesh.geometry) {
  27953. var geometry = (mesh.geometry);
  27954. if (this.storeEffectOnSubMeshes) {
  27955. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27956. var subMesh = _a[_i];
  27957. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27958. if (forceDisposeEffect && subMesh._materialEffect) {
  27959. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27960. }
  27961. }
  27962. }
  27963. else {
  27964. geometry._releaseVertexArrayObject(this._effect);
  27965. }
  27966. }
  27967. }
  27968. }
  27969. this._uniformBuffer.dispose();
  27970. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27971. if (forceDisposeEffect && this._effect) {
  27972. if (!this.storeEffectOnSubMeshes) {
  27973. this._scene.getEngine()._releaseEffect(this._effect);
  27974. }
  27975. this._effect = null;
  27976. }
  27977. // Callback
  27978. this.onDisposeObservable.notifyObservers(this);
  27979. this.onDisposeObservable.clear();
  27980. this.onBindObservable.clear();
  27981. this.onUnBindObservable.clear();
  27982. };
  27983. Material.prototype.serialize = function () {
  27984. return BABYLON.SerializationHelper.Serialize(this);
  27985. };
  27986. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27987. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27988. multiMaterial.id = parsedMultiMaterial.id;
  27989. if (BABYLON.Tags) {
  27990. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27991. }
  27992. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27993. var subMatId = parsedMultiMaterial.materials[matIndex];
  27994. if (subMatId) {
  27995. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27996. }
  27997. else {
  27998. multiMaterial.subMaterials.push(null);
  27999. }
  28000. }
  28001. return multiMaterial;
  28002. };
  28003. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28004. if (!parsedMaterial.customType) {
  28005. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28006. }
  28007. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28008. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28009. if (!BABYLON.LegacyPBRMaterial) {
  28010. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28011. return;
  28012. }
  28013. }
  28014. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28015. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28016. ;
  28017. };
  28018. // Triangle views
  28019. Material._TriangleFillMode = 0;
  28020. Material._WireFrameFillMode = 1;
  28021. Material._PointFillMode = 2;
  28022. // Draw modes
  28023. Material._PointListDrawMode = 3;
  28024. Material._LineListDrawMode = 4;
  28025. Material._LineLoopDrawMode = 5;
  28026. Material._LineStripDrawMode = 6;
  28027. Material._TriangleStripDrawMode = 7;
  28028. Material._TriangleFanDrawMode = 8;
  28029. Material._ClockWiseSideOrientation = 0;
  28030. Material._CounterClockWiseSideOrientation = 1;
  28031. Material._TextureDirtyFlag = 1;
  28032. Material._LightDirtyFlag = 2;
  28033. Material._FresnelDirtyFlag = 4;
  28034. Material._AttributesDirtyFlag = 8;
  28035. Material._MiscDirtyFlag = 16;
  28036. __decorate([
  28037. BABYLON.serialize()
  28038. ], Material.prototype, "id", void 0);
  28039. __decorate([
  28040. BABYLON.serialize()
  28041. ], Material.prototype, "name", void 0);
  28042. __decorate([
  28043. BABYLON.serialize()
  28044. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28045. __decorate([
  28046. BABYLON.serialize()
  28047. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28048. __decorate([
  28049. BABYLON.serialize()
  28050. ], Material.prototype, "state", void 0);
  28051. __decorate([
  28052. BABYLON.serialize()
  28053. ], Material.prototype, "alpha", void 0);
  28054. __decorate([
  28055. BABYLON.serialize("backFaceCulling")
  28056. ], Material.prototype, "_backFaceCulling", void 0);
  28057. __decorate([
  28058. BABYLON.serialize()
  28059. ], Material.prototype, "sideOrientation", void 0);
  28060. __decorate([
  28061. BABYLON.serialize("alphaMode")
  28062. ], Material.prototype, "_alphaMode", void 0);
  28063. __decorate([
  28064. BABYLON.serialize()
  28065. ], Material.prototype, "_needDepthPrePass", void 0);
  28066. __decorate([
  28067. BABYLON.serialize()
  28068. ], Material.prototype, "disableDepthWrite", void 0);
  28069. __decorate([
  28070. BABYLON.serialize()
  28071. ], Material.prototype, "forceDepthWrite", void 0);
  28072. __decorate([
  28073. BABYLON.serialize()
  28074. ], Material.prototype, "separateCullingPass", void 0);
  28075. __decorate([
  28076. BABYLON.serialize("fogEnabled")
  28077. ], Material.prototype, "_fogEnabled", void 0);
  28078. __decorate([
  28079. BABYLON.serialize()
  28080. ], Material.prototype, "pointSize", void 0);
  28081. __decorate([
  28082. BABYLON.serialize()
  28083. ], Material.prototype, "zOffset", void 0);
  28084. __decorate([
  28085. BABYLON.serialize()
  28086. ], Material.prototype, "wireframe", null);
  28087. __decorate([
  28088. BABYLON.serialize()
  28089. ], Material.prototype, "pointsCloud", null);
  28090. __decorate([
  28091. BABYLON.serialize()
  28092. ], Material.prototype, "fillMode", null);
  28093. return Material;
  28094. }());
  28095. BABYLON.Material = Material;
  28096. })(BABYLON || (BABYLON = {}));
  28097. //# sourceMappingURL=babylon.material.js.map
  28098. var BABYLON;
  28099. (function (BABYLON) {
  28100. var UniformBuffer = /** @class */ (function () {
  28101. /**
  28102. * Uniform buffer objects.
  28103. *
  28104. * Handles blocks of uniform on the GPU.
  28105. *
  28106. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28107. *
  28108. * For more information, please refer to :
  28109. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28110. */
  28111. function UniformBuffer(engine, data, dynamic) {
  28112. this._engine = engine;
  28113. this._noUBO = !engine.supportsUniformBuffers;
  28114. this._dynamic = dynamic;
  28115. this._data = data || [];
  28116. this._uniformLocations = {};
  28117. this._uniformSizes = {};
  28118. this._uniformLocationPointer = 0;
  28119. this._needSync = false;
  28120. if (this._noUBO) {
  28121. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28122. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28123. this.updateFloat = this._updateFloatForEffect;
  28124. this.updateFloat2 = this._updateFloat2ForEffect;
  28125. this.updateFloat3 = this._updateFloat3ForEffect;
  28126. this.updateFloat4 = this._updateFloat4ForEffect;
  28127. this.updateMatrix = this._updateMatrixForEffect;
  28128. this.updateVector3 = this._updateVector3ForEffect;
  28129. this.updateVector4 = this._updateVector4ForEffect;
  28130. this.updateColor3 = this._updateColor3ForEffect;
  28131. this.updateColor4 = this._updateColor4ForEffect;
  28132. }
  28133. else {
  28134. this._engine._uniformBuffers.push(this);
  28135. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28136. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28137. this.updateFloat = this._updateFloatForUniform;
  28138. this.updateFloat2 = this._updateFloat2ForUniform;
  28139. this.updateFloat3 = this._updateFloat3ForUniform;
  28140. this.updateFloat4 = this._updateFloat4ForUniform;
  28141. this.updateMatrix = this._updateMatrixForUniform;
  28142. this.updateVector3 = this._updateVector3ForUniform;
  28143. this.updateVector4 = this._updateVector4ForUniform;
  28144. this.updateColor3 = this._updateColor3ForUniform;
  28145. this.updateColor4 = this._updateColor4ForUniform;
  28146. }
  28147. }
  28148. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28149. // Properties
  28150. /**
  28151. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28152. * or just falling back on setUniformXXX calls.
  28153. */
  28154. get: function () {
  28155. return !this._noUBO;
  28156. },
  28157. enumerable: true,
  28158. configurable: true
  28159. });
  28160. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28161. /**
  28162. * Indicates if the WebGL underlying uniform buffer is in sync
  28163. * with the javascript cache data.
  28164. */
  28165. get: function () {
  28166. return !this._needSync;
  28167. },
  28168. enumerable: true,
  28169. configurable: true
  28170. });
  28171. /**
  28172. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28173. * Also, a dynamic UniformBuffer will disable cache verification and always
  28174. * update the underlying WebGL uniform buffer to the GPU.
  28175. */
  28176. UniformBuffer.prototype.isDynamic = function () {
  28177. return this._dynamic !== undefined;
  28178. };
  28179. /**
  28180. * The data cache on JS side.
  28181. */
  28182. UniformBuffer.prototype.getData = function () {
  28183. return this._bufferData;
  28184. };
  28185. /**
  28186. * The underlying WebGL Uniform buffer.
  28187. */
  28188. UniformBuffer.prototype.getBuffer = function () {
  28189. return this._buffer;
  28190. };
  28191. /**
  28192. * std140 layout specifies how to align data within an UBO structure.
  28193. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28194. * for specs.
  28195. */
  28196. UniformBuffer.prototype._fillAlignment = function (size) {
  28197. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28198. // and 4x4 matrices
  28199. // TODO : change if other types are used
  28200. var alignment;
  28201. if (size <= 2) {
  28202. alignment = size;
  28203. }
  28204. else {
  28205. alignment = 4;
  28206. }
  28207. if ((this._uniformLocationPointer % alignment) !== 0) {
  28208. var oldPointer = this._uniformLocationPointer;
  28209. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28210. var diff = this._uniformLocationPointer - oldPointer;
  28211. for (var i = 0; i < diff; i++) {
  28212. this._data.push(0);
  28213. }
  28214. }
  28215. };
  28216. /**
  28217. * Adds an uniform in the buffer.
  28218. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28219. * for the layout to be correct !
  28220. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28221. * @param {number|number[]} size Data size, or data directly.
  28222. */
  28223. UniformBuffer.prototype.addUniform = function (name, size) {
  28224. if (this._noUBO) {
  28225. return;
  28226. }
  28227. if (this._uniformLocations[name] !== undefined) {
  28228. // Already existing uniform
  28229. return;
  28230. }
  28231. // This function must be called in the order of the shader layout !
  28232. // size can be the size of the uniform, or data directly
  28233. var data;
  28234. if (size instanceof Array) {
  28235. data = size;
  28236. size = data.length;
  28237. }
  28238. else {
  28239. size = size;
  28240. data = [];
  28241. // Fill with zeros
  28242. for (var i = 0; i < size; i++) {
  28243. data.push(0);
  28244. }
  28245. }
  28246. this._fillAlignment(size);
  28247. this._uniformSizes[name] = size;
  28248. this._uniformLocations[name] = this._uniformLocationPointer;
  28249. this._uniformLocationPointer += size;
  28250. for (var i = 0; i < size; i++) {
  28251. this._data.push(data[i]);
  28252. }
  28253. this._needSync = true;
  28254. };
  28255. /**
  28256. * Wrapper for addUniform.
  28257. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28258. * @param {Matrix} mat A 4x4 matrix.
  28259. */
  28260. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28261. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28262. };
  28263. /**
  28264. * Wrapper for addUniform.
  28265. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28266. * @param {number} x
  28267. * @param {number} y
  28268. */
  28269. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28270. var temp = [x, y];
  28271. this.addUniform(name, temp);
  28272. };
  28273. /**
  28274. * Wrapper for addUniform.
  28275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28276. * @param {number} x
  28277. * @param {number} y
  28278. * @param {number} z
  28279. */
  28280. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28281. var temp = [x, y, z];
  28282. this.addUniform(name, temp);
  28283. };
  28284. /**
  28285. * Wrapper for addUniform.
  28286. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28287. * @param {Color3} color
  28288. */
  28289. UniformBuffer.prototype.addColor3 = function (name, color) {
  28290. var temp = new Array();
  28291. color.toArray(temp);
  28292. this.addUniform(name, temp);
  28293. };
  28294. /**
  28295. * Wrapper for addUniform.
  28296. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28297. * @param {Color3} color
  28298. * @param {number} alpha
  28299. */
  28300. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28301. var temp = new Array();
  28302. color.toArray(temp);
  28303. temp.push(alpha);
  28304. this.addUniform(name, temp);
  28305. };
  28306. /**
  28307. * Wrapper for addUniform.
  28308. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28309. * @param {Vector3} vector
  28310. */
  28311. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28312. var temp = new Array();
  28313. vector.toArray(temp);
  28314. this.addUniform(name, temp);
  28315. };
  28316. /**
  28317. * Wrapper for addUniform.
  28318. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28319. */
  28320. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28321. this.addUniform(name, 12);
  28322. };
  28323. /**
  28324. * Wrapper for addUniform.
  28325. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28326. */
  28327. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28328. this.addUniform(name, 8);
  28329. };
  28330. /**
  28331. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28332. */
  28333. UniformBuffer.prototype.create = function () {
  28334. if (this._noUBO) {
  28335. return;
  28336. }
  28337. if (this._buffer) {
  28338. return; // nothing to do
  28339. }
  28340. // See spec, alignment must be filled as a vec4
  28341. this._fillAlignment(4);
  28342. this._bufferData = new Float32Array(this._data);
  28343. this._rebuild();
  28344. this._needSync = true;
  28345. };
  28346. UniformBuffer.prototype._rebuild = function () {
  28347. if (this._noUBO) {
  28348. return;
  28349. }
  28350. if (this._dynamic) {
  28351. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28352. }
  28353. else {
  28354. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28355. }
  28356. };
  28357. /**
  28358. * Updates the WebGL Uniform Buffer on the GPU.
  28359. * If the `dynamic` flag is set to true, no cache comparison is done.
  28360. * Otherwise, the buffer will be updated only if the cache differs.
  28361. */
  28362. UniformBuffer.prototype.update = function () {
  28363. if (!this._buffer) {
  28364. this.create();
  28365. return;
  28366. }
  28367. if (!this._dynamic && !this._needSync) {
  28368. return;
  28369. }
  28370. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28371. this._needSync = false;
  28372. };
  28373. /**
  28374. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28375. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28376. * @param {number[]|Float32Array} data Flattened data
  28377. * @param {number} size Size of the data.
  28378. */
  28379. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28380. var location = this._uniformLocations[uniformName];
  28381. if (location === undefined) {
  28382. if (this._buffer) {
  28383. // Cannot add an uniform if the buffer is already created
  28384. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28385. return;
  28386. }
  28387. this.addUniform(uniformName, size);
  28388. location = this._uniformLocations[uniformName];
  28389. }
  28390. if (!this._buffer) {
  28391. this.create();
  28392. }
  28393. if (!this._dynamic) {
  28394. // Cache for static uniform buffers
  28395. var changed = false;
  28396. for (var i = 0; i < size; i++) {
  28397. if (this._bufferData[location + i] !== data[i]) {
  28398. changed = true;
  28399. this._bufferData[location + i] = data[i];
  28400. }
  28401. }
  28402. this._needSync = this._needSync || changed;
  28403. }
  28404. else {
  28405. // No cache for dynamic
  28406. for (var i = 0; i < size; i++) {
  28407. this._bufferData[location + i] = data[i];
  28408. }
  28409. }
  28410. };
  28411. // Update methods
  28412. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28413. // To match std140, matrix must be realigned
  28414. for (var i = 0; i < 3; i++) {
  28415. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28416. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28417. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28418. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28419. }
  28420. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28421. };
  28422. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28423. this._currentEffect.setMatrix3x3(name, matrix);
  28424. };
  28425. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28426. this._currentEffect.setMatrix2x2(name, matrix);
  28427. };
  28428. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28429. // To match std140, matrix must be realigned
  28430. for (var i = 0; i < 2; i++) {
  28431. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28432. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28433. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28434. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28435. }
  28436. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28437. };
  28438. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28439. this._currentEffect.setFloat(name, x);
  28440. };
  28441. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28442. UniformBuffer._tempBuffer[0] = x;
  28443. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28444. };
  28445. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28446. if (suffix === void 0) { suffix = ""; }
  28447. this._currentEffect.setFloat2(name + suffix, x, y);
  28448. };
  28449. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28450. if (suffix === void 0) { suffix = ""; }
  28451. UniformBuffer._tempBuffer[0] = x;
  28452. UniformBuffer._tempBuffer[1] = y;
  28453. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28454. };
  28455. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28456. if (suffix === void 0) { suffix = ""; }
  28457. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28458. };
  28459. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28460. if (suffix === void 0) { suffix = ""; }
  28461. UniformBuffer._tempBuffer[0] = x;
  28462. UniformBuffer._tempBuffer[1] = y;
  28463. UniformBuffer._tempBuffer[2] = z;
  28464. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28465. };
  28466. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28467. if (suffix === void 0) { suffix = ""; }
  28468. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28469. };
  28470. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28471. if (suffix === void 0) { suffix = ""; }
  28472. UniformBuffer._tempBuffer[0] = x;
  28473. UniformBuffer._tempBuffer[1] = y;
  28474. UniformBuffer._tempBuffer[2] = z;
  28475. UniformBuffer._tempBuffer[3] = w;
  28476. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28477. };
  28478. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28479. this._currentEffect.setMatrix(name, mat);
  28480. };
  28481. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28482. this.updateUniform(name, mat.toArray(), 16);
  28483. };
  28484. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28485. this._currentEffect.setVector3(name, vector);
  28486. };
  28487. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28488. vector.toArray(UniformBuffer._tempBuffer);
  28489. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28490. };
  28491. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28492. this._currentEffect.setVector4(name, vector);
  28493. };
  28494. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28495. vector.toArray(UniformBuffer._tempBuffer);
  28496. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28497. };
  28498. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28499. if (suffix === void 0) { suffix = ""; }
  28500. this._currentEffect.setColor3(name + suffix, color);
  28501. };
  28502. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28503. if (suffix === void 0) { suffix = ""; }
  28504. color.toArray(UniformBuffer._tempBuffer);
  28505. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28506. };
  28507. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28508. if (suffix === void 0) { suffix = ""; }
  28509. this._currentEffect.setColor4(name + suffix, color, alpha);
  28510. };
  28511. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28512. if (suffix === void 0) { suffix = ""; }
  28513. color.toArray(UniformBuffer._tempBuffer);
  28514. UniformBuffer._tempBuffer[3] = alpha;
  28515. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28516. };
  28517. /**
  28518. * Sets a sampler uniform on the effect.
  28519. * @param {string} name Name of the sampler.
  28520. * @param {Texture} texture
  28521. */
  28522. UniformBuffer.prototype.setTexture = function (name, texture) {
  28523. this._currentEffect.setTexture(name, texture);
  28524. };
  28525. /**
  28526. * Directly updates the value of the uniform in the cache AND on the GPU.
  28527. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28528. * @param {number[]|Float32Array} data Flattened data
  28529. */
  28530. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28531. this.updateUniform(uniformName, data, data.length);
  28532. this.update();
  28533. };
  28534. /**
  28535. * Binds this uniform buffer to an effect.
  28536. * @param {Effect} effect
  28537. * @param {string} name Name of the uniform block in the shader.
  28538. */
  28539. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28540. this._currentEffect = effect;
  28541. if (this._noUBO || !this._buffer) {
  28542. return;
  28543. }
  28544. effect.bindUniformBuffer(this._buffer, name);
  28545. };
  28546. /**
  28547. * Disposes the uniform buffer.
  28548. */
  28549. UniformBuffer.prototype.dispose = function () {
  28550. if (this._noUBO) {
  28551. return;
  28552. }
  28553. var index = this._engine._uniformBuffers.indexOf(this);
  28554. if (index !== -1) {
  28555. this._engine._uniformBuffers.splice(index, 1);
  28556. }
  28557. if (!this._buffer) {
  28558. return;
  28559. }
  28560. if (this._engine._releaseBuffer(this._buffer)) {
  28561. this._buffer = null;
  28562. }
  28563. };
  28564. // Pool for avoiding memory leaks
  28565. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28566. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28567. return UniformBuffer;
  28568. }());
  28569. BABYLON.UniformBuffer = UniformBuffer;
  28570. })(BABYLON || (BABYLON = {}));
  28571. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28572. var BABYLON;
  28573. (function (BABYLON) {
  28574. var VertexData = /** @class */ (function () {
  28575. function VertexData() {
  28576. }
  28577. VertexData.prototype.set = function (data, kind) {
  28578. switch (kind) {
  28579. case BABYLON.VertexBuffer.PositionKind:
  28580. this.positions = data;
  28581. break;
  28582. case BABYLON.VertexBuffer.NormalKind:
  28583. this.normals = data;
  28584. break;
  28585. case BABYLON.VertexBuffer.TangentKind:
  28586. this.tangents = data;
  28587. break;
  28588. case BABYLON.VertexBuffer.UVKind:
  28589. this.uvs = data;
  28590. break;
  28591. case BABYLON.VertexBuffer.UV2Kind:
  28592. this.uvs2 = data;
  28593. break;
  28594. case BABYLON.VertexBuffer.UV3Kind:
  28595. this.uvs3 = data;
  28596. break;
  28597. case BABYLON.VertexBuffer.UV4Kind:
  28598. this.uvs4 = data;
  28599. break;
  28600. case BABYLON.VertexBuffer.UV5Kind:
  28601. this.uvs5 = data;
  28602. break;
  28603. case BABYLON.VertexBuffer.UV6Kind:
  28604. this.uvs6 = data;
  28605. break;
  28606. case BABYLON.VertexBuffer.ColorKind:
  28607. this.colors = data;
  28608. break;
  28609. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28610. this.matricesIndices = data;
  28611. break;
  28612. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28613. this.matricesWeights = data;
  28614. break;
  28615. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28616. this.matricesIndicesExtra = data;
  28617. break;
  28618. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28619. this.matricesWeightsExtra = data;
  28620. break;
  28621. }
  28622. };
  28623. /**
  28624. * Associates the vertexData to the passed Mesh.
  28625. * Sets it as updatable or not (default `false`).
  28626. * Returns the VertexData.
  28627. */
  28628. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28629. this._applyTo(mesh, updatable);
  28630. return this;
  28631. };
  28632. /**
  28633. * Associates the vertexData to the passed Geometry.
  28634. * Sets it as updatable or not (default `false`).
  28635. * Returns the VertexData.
  28636. */
  28637. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28638. this._applyTo(geometry, updatable);
  28639. return this;
  28640. };
  28641. /**
  28642. * Updates the associated mesh.
  28643. * Returns the VertexData.
  28644. */
  28645. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28646. this._update(mesh);
  28647. return this;
  28648. };
  28649. /**
  28650. * Updates the associated geometry.
  28651. * Returns the VertexData.
  28652. */
  28653. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28654. this._update(geometry);
  28655. return this;
  28656. };
  28657. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28658. if (updatable === void 0) { updatable = false; }
  28659. if (this.positions) {
  28660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28661. }
  28662. if (this.normals) {
  28663. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28664. }
  28665. if (this.tangents) {
  28666. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28667. }
  28668. if (this.uvs) {
  28669. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28670. }
  28671. if (this.uvs2) {
  28672. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28673. }
  28674. if (this.uvs3) {
  28675. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28676. }
  28677. if (this.uvs4) {
  28678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28679. }
  28680. if (this.uvs5) {
  28681. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28682. }
  28683. if (this.uvs6) {
  28684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28685. }
  28686. if (this.colors) {
  28687. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28688. }
  28689. if (this.matricesIndices) {
  28690. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28691. }
  28692. if (this.matricesWeights) {
  28693. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28694. }
  28695. if (this.matricesIndicesExtra) {
  28696. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28697. }
  28698. if (this.matricesWeightsExtra) {
  28699. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28700. }
  28701. if (this.indices) {
  28702. meshOrGeometry.setIndices(this.indices, null, updatable);
  28703. }
  28704. return this;
  28705. };
  28706. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28707. if (this.positions) {
  28708. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28709. }
  28710. if (this.normals) {
  28711. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28712. }
  28713. if (this.tangents) {
  28714. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28715. }
  28716. if (this.uvs) {
  28717. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28718. }
  28719. if (this.uvs2) {
  28720. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28721. }
  28722. if (this.uvs3) {
  28723. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28724. }
  28725. if (this.uvs4) {
  28726. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28727. }
  28728. if (this.uvs5) {
  28729. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28730. }
  28731. if (this.uvs6) {
  28732. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28733. }
  28734. if (this.colors) {
  28735. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28736. }
  28737. if (this.matricesIndices) {
  28738. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28739. }
  28740. if (this.matricesWeights) {
  28741. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28742. }
  28743. if (this.matricesIndicesExtra) {
  28744. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28745. }
  28746. if (this.matricesWeightsExtra) {
  28747. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28748. }
  28749. if (this.indices) {
  28750. meshOrGeometry.setIndices(this.indices, null);
  28751. }
  28752. return this;
  28753. };
  28754. /**
  28755. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28756. * Returns the VertexData.
  28757. */
  28758. VertexData.prototype.transform = function (matrix) {
  28759. var transformed = BABYLON.Vector3.Zero();
  28760. var index;
  28761. if (this.positions) {
  28762. var position = BABYLON.Vector3.Zero();
  28763. for (index = 0; index < this.positions.length; index += 3) {
  28764. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28765. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28766. this.positions[index] = transformed.x;
  28767. this.positions[index + 1] = transformed.y;
  28768. this.positions[index + 2] = transformed.z;
  28769. }
  28770. }
  28771. if (this.normals) {
  28772. var normal = BABYLON.Vector3.Zero();
  28773. for (index = 0; index < this.normals.length; index += 3) {
  28774. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28775. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28776. this.normals[index] = transformed.x;
  28777. this.normals[index + 1] = transformed.y;
  28778. this.normals[index + 2] = transformed.z;
  28779. }
  28780. }
  28781. if (this.tangents) {
  28782. var tangent = BABYLON.Vector4.Zero();
  28783. var tangentTransformed = BABYLON.Vector4.Zero();
  28784. for (index = 0; index < this.tangents.length; index += 4) {
  28785. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28786. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28787. this.tangents[index] = tangentTransformed.x;
  28788. this.tangents[index + 1] = tangentTransformed.y;
  28789. this.tangents[index + 2] = tangentTransformed.z;
  28790. this.tangents[index + 3] = tangentTransformed.w;
  28791. }
  28792. }
  28793. return this;
  28794. };
  28795. /**
  28796. * Merges the passed VertexData into the current one.
  28797. * Returns the modified VertexData.
  28798. */
  28799. VertexData.prototype.merge = function (other, options) {
  28800. options = options || {};
  28801. if (other.indices) {
  28802. if (!this.indices) {
  28803. this.indices = [];
  28804. }
  28805. var offset = this.positions ? this.positions.length / 3 : 0;
  28806. for (var index = 0; index < other.indices.length; index++) {
  28807. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28808. this.indices.push(other.indices[index] + offset);
  28809. }
  28810. }
  28811. this.positions = this._mergeElement(this.positions, other.positions);
  28812. if (!this.positions) {
  28813. return this;
  28814. }
  28815. var count = this.positions.length / 3;
  28816. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28817. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28818. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28819. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28820. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28821. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28822. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28823. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28824. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  28825. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28826. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28827. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28828. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28829. return this;
  28830. };
  28831. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  28832. if (length === void 0) { length = 0; }
  28833. if (defaultValue === void 0) { defaultValue = 0; }
  28834. if (!other && !source) {
  28835. return null;
  28836. }
  28837. if (!other) {
  28838. var padding = new Float32Array(source.length);
  28839. padding.fill(defaultValue);
  28840. return this._mergeElement(source, padding, length);
  28841. }
  28842. if (!source) {
  28843. if (length === 0 || length === other.length) {
  28844. return other;
  28845. }
  28846. var padding = new Float32Array(length - other.length);
  28847. padding.fill(defaultValue);
  28848. return this._mergeElement(padding, other, length);
  28849. }
  28850. var len = other.length + source.length;
  28851. var isSrcTypedArray = source instanceof Float32Array;
  28852. var isOthTypedArray = other instanceof Float32Array;
  28853. // use non-loop method when the source is Float32Array
  28854. if (isSrcTypedArray) {
  28855. var ret32 = new Float32Array(len);
  28856. ret32.set(source);
  28857. ret32.set(other, source.length);
  28858. return ret32;
  28859. // source is number[], when other is also use concat
  28860. }
  28861. else if (!isOthTypedArray) {
  28862. return source.concat(other);
  28863. // source is a number[], but other is a Float32Array, loop required
  28864. }
  28865. else {
  28866. var ret = source.slice(0); // copy source to a separate array
  28867. for (var i = 0, len = other.length; i < len; i++) {
  28868. ret.push(other[i]);
  28869. }
  28870. return ret;
  28871. }
  28872. };
  28873. /**
  28874. * Serializes the VertexData.
  28875. * Returns a serialized object.
  28876. */
  28877. VertexData.prototype.serialize = function () {
  28878. var serializationObject = this.serialize();
  28879. if (this.positions) {
  28880. serializationObject.positions = this.positions;
  28881. }
  28882. if (this.normals) {
  28883. serializationObject.normals = this.normals;
  28884. }
  28885. if (this.tangents) {
  28886. serializationObject.tangents = this.tangents;
  28887. }
  28888. if (this.uvs) {
  28889. serializationObject.uvs = this.uvs;
  28890. }
  28891. if (this.uvs2) {
  28892. serializationObject.uvs2 = this.uvs2;
  28893. }
  28894. if (this.uvs3) {
  28895. serializationObject.uvs3 = this.uvs3;
  28896. }
  28897. if (this.uvs4) {
  28898. serializationObject.uvs4 = this.uvs4;
  28899. }
  28900. if (this.uvs5) {
  28901. serializationObject.uvs5 = this.uvs5;
  28902. }
  28903. if (this.uvs6) {
  28904. serializationObject.uvs6 = this.uvs6;
  28905. }
  28906. if (this.colors) {
  28907. serializationObject.colors = this.colors;
  28908. }
  28909. if (this.matricesIndices) {
  28910. serializationObject.matricesIndices = this.matricesIndices;
  28911. serializationObject.matricesIndices._isExpanded = true;
  28912. }
  28913. if (this.matricesWeights) {
  28914. serializationObject.matricesWeights = this.matricesWeights;
  28915. }
  28916. if (this.matricesIndicesExtra) {
  28917. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28918. serializationObject.matricesIndicesExtra._isExpanded = true;
  28919. }
  28920. if (this.matricesWeightsExtra) {
  28921. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28922. }
  28923. serializationObject.indices = this.indices;
  28924. return serializationObject;
  28925. };
  28926. // Statics
  28927. /**
  28928. * Returns the object VertexData associated to the passed mesh.
  28929. */
  28930. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28931. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28932. };
  28933. /**
  28934. * Returns the object VertexData associated to the passed geometry.
  28935. */
  28936. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28937. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28938. };
  28939. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28940. var result = new VertexData();
  28941. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28942. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28943. }
  28944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28945. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28946. }
  28947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28948. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28949. }
  28950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28951. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28952. }
  28953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28954. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28955. }
  28956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28957. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28958. }
  28959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28960. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28961. }
  28962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28963. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28964. }
  28965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28966. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28967. }
  28968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28969. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28970. }
  28971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28972. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28973. }
  28974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28975. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28976. }
  28977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28978. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28979. }
  28980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28981. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28982. }
  28983. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28984. return result;
  28985. };
  28986. /**
  28987. * Creates the vertexData of the Ribbon.
  28988. */
  28989. VertexData.CreateRibbon = function (options) {
  28990. var pathArray = options.pathArray;
  28991. var closeArray = options.closeArray || false;
  28992. var closePath = options.closePath || false;
  28993. var invertUV = options.invertUV || false;
  28994. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28995. var offset = options.offset || defaultOffset;
  28996. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28998. var customUV = options.uvs;
  28999. var customColors = options.colors;
  29000. var positions = [];
  29001. var indices = [];
  29002. var normals = [];
  29003. var uvs = [];
  29004. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29005. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29006. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29007. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29008. var minlg; // minimal length among all paths from pathArray
  29009. var lg = []; // array of path lengths : nb of vertex per path
  29010. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29011. var p; // path iterator
  29012. var i; // point iterator
  29013. var j; // point iterator
  29014. // if single path in pathArray
  29015. if (pathArray.length < 2) {
  29016. var ar1 = [];
  29017. var ar2 = [];
  29018. for (i = 0; i < pathArray[0].length - offset; i++) {
  29019. ar1.push(pathArray[0][i]);
  29020. ar2.push(pathArray[0][i + offset]);
  29021. }
  29022. pathArray = [ar1, ar2];
  29023. }
  29024. // positions and horizontal distances (u)
  29025. var idc = 0;
  29026. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29027. var path;
  29028. var l;
  29029. minlg = pathArray[0].length;
  29030. var vectlg;
  29031. var dist;
  29032. for (p = 0; p < pathArray.length; p++) {
  29033. uTotalDistance[p] = 0;
  29034. us[p] = [0];
  29035. path = pathArray[p];
  29036. l = path.length;
  29037. minlg = (minlg < l) ? minlg : l;
  29038. j = 0;
  29039. while (j < l) {
  29040. positions.push(path[j].x, path[j].y, path[j].z);
  29041. if (j > 0) {
  29042. vectlg = path[j].subtract(path[j - 1]).length();
  29043. dist = vectlg + uTotalDistance[p];
  29044. us[p].push(dist);
  29045. uTotalDistance[p] = dist;
  29046. }
  29047. j++;
  29048. }
  29049. if (closePath) {
  29050. j--;
  29051. positions.push(path[0].x, path[0].y, path[0].z);
  29052. vectlg = path[j].subtract(path[0]).length();
  29053. dist = vectlg + uTotalDistance[p];
  29054. us[p].push(dist);
  29055. uTotalDistance[p] = dist;
  29056. }
  29057. lg[p] = l + closePathCorr;
  29058. idx[p] = idc;
  29059. idc += (l + closePathCorr);
  29060. }
  29061. // vertical distances (v)
  29062. var path1;
  29063. var path2;
  29064. var vertex1 = null;
  29065. var vertex2 = null;
  29066. for (i = 0; i < minlg + closePathCorr; i++) {
  29067. vTotalDistance[i] = 0;
  29068. vs[i] = [0];
  29069. for (p = 0; p < pathArray.length - 1; p++) {
  29070. path1 = pathArray[p];
  29071. path2 = pathArray[p + 1];
  29072. if (i === minlg) {
  29073. vertex1 = path1[0];
  29074. vertex2 = path2[0];
  29075. }
  29076. else {
  29077. vertex1 = path1[i];
  29078. vertex2 = path2[i];
  29079. }
  29080. vectlg = vertex2.subtract(vertex1).length();
  29081. dist = vectlg + vTotalDistance[i];
  29082. vs[i].push(dist);
  29083. vTotalDistance[i] = dist;
  29084. }
  29085. if (closeArray && vertex2 && vertex1) {
  29086. path1 = pathArray[p];
  29087. path2 = pathArray[0];
  29088. if (i === minlg) {
  29089. vertex2 = path2[0];
  29090. }
  29091. vectlg = vertex2.subtract(vertex1).length();
  29092. dist = vectlg + vTotalDistance[i];
  29093. vTotalDistance[i] = dist;
  29094. }
  29095. }
  29096. // uvs
  29097. var u;
  29098. var v;
  29099. if (customUV) {
  29100. for (p = 0; p < customUV.length; p++) {
  29101. uvs.push(customUV[p].x, customUV[p].y);
  29102. }
  29103. }
  29104. else {
  29105. for (p = 0; p < pathArray.length; p++) {
  29106. for (i = 0; i < minlg + closePathCorr; i++) {
  29107. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29108. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29109. if (invertUV) {
  29110. uvs.push(v, u);
  29111. }
  29112. else {
  29113. uvs.push(u, v);
  29114. }
  29115. }
  29116. }
  29117. }
  29118. // indices
  29119. p = 0; // path index
  29120. var pi = 0; // positions array index
  29121. var l1 = lg[p] - 1; // path1 length
  29122. var l2 = lg[p + 1] - 1; // path2 length
  29123. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29124. var shft = idx[1] - idx[0]; // shift
  29125. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29126. while (pi <= min && p < path1nb) {
  29127. // 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
  29128. indices.push(pi, pi + shft, pi + 1);
  29129. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29130. pi += 1;
  29131. if (pi === min) {
  29132. p++;
  29133. if (p === lg.length - 1) {
  29134. shft = idx[0] - idx[p];
  29135. l1 = lg[p] - 1;
  29136. l2 = lg[0] - 1;
  29137. }
  29138. else {
  29139. shft = idx[p + 1] - idx[p];
  29140. l1 = lg[p] - 1;
  29141. l2 = lg[p + 1] - 1;
  29142. }
  29143. pi = idx[p];
  29144. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29145. }
  29146. }
  29147. // normals
  29148. VertexData.ComputeNormals(positions, indices, normals);
  29149. if (closePath) {
  29150. var indexFirst = 0;
  29151. var indexLast = 0;
  29152. for (p = 0; p < pathArray.length; p++) {
  29153. indexFirst = idx[p] * 3;
  29154. if (p + 1 < pathArray.length) {
  29155. indexLast = (idx[p + 1] - 1) * 3;
  29156. }
  29157. else {
  29158. indexLast = normals.length - 3;
  29159. }
  29160. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29161. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29162. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29163. normals[indexLast] = normals[indexFirst];
  29164. normals[indexLast + 1] = normals[indexFirst + 1];
  29165. normals[indexLast + 2] = normals[indexFirst + 2];
  29166. }
  29167. }
  29168. // sides
  29169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29170. // Colors
  29171. var colors = null;
  29172. if (customColors) {
  29173. colors = new Float32Array(customColors.length * 4);
  29174. for (var c = 0; c < customColors.length; c++) {
  29175. colors[c * 4] = customColors[c].r;
  29176. colors[c * 4 + 1] = customColors[c].g;
  29177. colors[c * 4 + 2] = customColors[c].b;
  29178. colors[c * 4 + 3] = customColors[c].a;
  29179. }
  29180. }
  29181. // Result
  29182. var vertexData = new VertexData();
  29183. var positions32 = new Float32Array(positions);
  29184. var normals32 = new Float32Array(normals);
  29185. var uvs32 = new Float32Array(uvs);
  29186. vertexData.indices = indices;
  29187. vertexData.positions = positions32;
  29188. vertexData.normals = normals32;
  29189. vertexData.uvs = uvs32;
  29190. if (colors) {
  29191. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29192. }
  29193. if (closePath) {
  29194. vertexData._idx = idx;
  29195. }
  29196. return vertexData;
  29197. };
  29198. /**
  29199. * Creates the VertexData of the Box.
  29200. */
  29201. VertexData.CreateBox = function (options) {
  29202. var normalsSource = [
  29203. new BABYLON.Vector3(0, 0, 1),
  29204. new BABYLON.Vector3(0, 0, -1),
  29205. new BABYLON.Vector3(1, 0, 0),
  29206. new BABYLON.Vector3(-1, 0, 0),
  29207. new BABYLON.Vector3(0, 1, 0),
  29208. new BABYLON.Vector3(0, -1, 0)
  29209. ];
  29210. var indices = [];
  29211. var positions = [];
  29212. var normals = [];
  29213. var uvs = [];
  29214. var width = options.width || options.size || 1;
  29215. var height = options.height || options.size || 1;
  29216. var depth = options.depth || options.size || 1;
  29217. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29218. var faceUV = options.faceUV || new Array(6);
  29219. var faceColors = options.faceColors;
  29220. var colors = [];
  29221. // default face colors and UV if undefined
  29222. for (var f = 0; f < 6; f++) {
  29223. if (faceUV[f] === undefined) {
  29224. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29225. }
  29226. if (faceColors && faceColors[f] === undefined) {
  29227. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29228. }
  29229. }
  29230. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29231. // Create each face in turn.
  29232. for (var index = 0; index < normalsSource.length; index++) {
  29233. var normal = normalsSource[index];
  29234. // Get two vectors perpendicular to the face normal and to each other.
  29235. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29236. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29237. // Six indices (two triangles) per face.
  29238. var verticesLength = positions.length / 3;
  29239. indices.push(verticesLength);
  29240. indices.push(verticesLength + 1);
  29241. indices.push(verticesLength + 2);
  29242. indices.push(verticesLength);
  29243. indices.push(verticesLength + 2);
  29244. indices.push(verticesLength + 3);
  29245. // Four vertices per face.
  29246. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29247. positions.push(vertex.x, vertex.y, vertex.z);
  29248. normals.push(normal.x, normal.y, normal.z);
  29249. uvs.push(faceUV[index].z, faceUV[index].w);
  29250. if (faceColors) {
  29251. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29252. }
  29253. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29254. positions.push(vertex.x, vertex.y, vertex.z);
  29255. normals.push(normal.x, normal.y, normal.z);
  29256. uvs.push(faceUV[index].x, faceUV[index].w);
  29257. if (faceColors) {
  29258. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29259. }
  29260. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29261. positions.push(vertex.x, vertex.y, vertex.z);
  29262. normals.push(normal.x, normal.y, normal.z);
  29263. uvs.push(faceUV[index].x, faceUV[index].y);
  29264. if (faceColors) {
  29265. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29266. }
  29267. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29268. positions.push(vertex.x, vertex.y, vertex.z);
  29269. normals.push(normal.x, normal.y, normal.z);
  29270. uvs.push(faceUV[index].z, faceUV[index].y);
  29271. if (faceColors) {
  29272. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29273. }
  29274. }
  29275. // sides
  29276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29277. // Result
  29278. var vertexData = new VertexData();
  29279. vertexData.indices = indices;
  29280. vertexData.positions = positions;
  29281. vertexData.normals = normals;
  29282. vertexData.uvs = uvs;
  29283. if (faceColors) {
  29284. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29285. vertexData.colors = totalColors;
  29286. }
  29287. return vertexData;
  29288. };
  29289. /**
  29290. * Creates the VertexData of the Sphere.
  29291. */
  29292. VertexData.CreateSphere = function (options) {
  29293. var segments = options.segments || 32;
  29294. var diameterX = options.diameterX || options.diameter || 1;
  29295. var diameterY = options.diameterY || options.diameter || 1;
  29296. var diameterZ = options.diameterZ || options.diameter || 1;
  29297. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29298. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29300. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29301. var totalZRotationSteps = 2 + segments;
  29302. var totalYRotationSteps = 2 * totalZRotationSteps;
  29303. var indices = [];
  29304. var positions = [];
  29305. var normals = [];
  29306. var uvs = [];
  29307. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29308. var normalizedZ = zRotationStep / totalZRotationSteps;
  29309. var angleZ = normalizedZ * Math.PI * slice;
  29310. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29311. var normalizedY = yRotationStep / totalYRotationSteps;
  29312. var angleY = normalizedY * Math.PI * 2 * arc;
  29313. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29314. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29315. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29316. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29317. var vertex = complete.multiply(radius);
  29318. var normal = complete.divide(radius).normalize();
  29319. positions.push(vertex.x, vertex.y, vertex.z);
  29320. normals.push(normal.x, normal.y, normal.z);
  29321. uvs.push(normalizedY, normalizedZ);
  29322. }
  29323. if (zRotationStep > 0) {
  29324. var verticesCount = positions.length / 3;
  29325. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29326. indices.push((firstIndex));
  29327. indices.push((firstIndex + 1));
  29328. indices.push(firstIndex + totalYRotationSteps + 1);
  29329. indices.push((firstIndex + totalYRotationSteps + 1));
  29330. indices.push((firstIndex + 1));
  29331. indices.push((firstIndex + totalYRotationSteps + 2));
  29332. }
  29333. }
  29334. }
  29335. // Sides
  29336. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29337. // Result
  29338. var vertexData = new VertexData();
  29339. vertexData.indices = indices;
  29340. vertexData.positions = positions;
  29341. vertexData.normals = normals;
  29342. vertexData.uvs = uvs;
  29343. return vertexData;
  29344. };
  29345. /**
  29346. * Creates the VertexData of the Cylinder or Cone.
  29347. */
  29348. VertexData.CreateCylinder = function (options) {
  29349. var height = options.height || 2;
  29350. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29351. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29352. var tessellation = options.tessellation || 24;
  29353. var subdivisions = options.subdivisions || 1;
  29354. var hasRings = options.hasRings ? true : false;
  29355. var enclose = options.enclose ? true : false;
  29356. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29357. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29358. var faceUV = options.faceUV || new Array(3);
  29359. var faceColors = options.faceColors;
  29360. // default face colors and UV if undefined
  29361. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29362. var ringNb = (hasRings) ? subdivisions : 1;
  29363. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29364. var f;
  29365. for (f = 0; f < surfaceNb; f++) {
  29366. if (faceColors && faceColors[f] === undefined) {
  29367. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29368. }
  29369. }
  29370. for (f = 0; f < surfaceNb; f++) {
  29371. if (faceUV && faceUV[f] === undefined) {
  29372. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29373. }
  29374. }
  29375. var indices = new Array();
  29376. var positions = new Array();
  29377. var normals = new Array();
  29378. var uvs = new Array();
  29379. var colors = new Array();
  29380. var angle_step = Math.PI * 2 * arc / tessellation;
  29381. var angle;
  29382. var h;
  29383. var radius;
  29384. var tan = (diameterBottom - diameterTop) / 2 / height;
  29385. var ringVertex = BABYLON.Vector3.Zero();
  29386. var ringNormal = BABYLON.Vector3.Zero();
  29387. var ringFirstVertex = BABYLON.Vector3.Zero();
  29388. var ringFirstNormal = BABYLON.Vector3.Zero();
  29389. var quadNormal = BABYLON.Vector3.Zero();
  29390. var Y = BABYLON.Axis.Y;
  29391. // positions, normals, uvs
  29392. var i;
  29393. var j;
  29394. var r;
  29395. var ringIdx = 1;
  29396. var s = 1; // surface index
  29397. var cs = 0;
  29398. var v = 0;
  29399. for (i = 0; i <= subdivisions; i++) {
  29400. h = i / subdivisions;
  29401. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29402. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29403. for (r = 0; r < ringIdx; r++) {
  29404. if (hasRings) {
  29405. s += r;
  29406. }
  29407. if (enclose) {
  29408. s += 2 * r;
  29409. }
  29410. for (j = 0; j <= tessellation; j++) {
  29411. angle = j * angle_step;
  29412. // position
  29413. ringVertex.x = Math.cos(-angle) * radius;
  29414. ringVertex.y = -height / 2 + h * height;
  29415. ringVertex.z = Math.sin(-angle) * radius;
  29416. // normal
  29417. if (diameterTop === 0 && i === subdivisions) {
  29418. // if no top cap, reuse former normals
  29419. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29420. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29421. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29422. }
  29423. else {
  29424. ringNormal.x = ringVertex.x;
  29425. ringNormal.z = ringVertex.z;
  29426. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29427. ringNormal.normalize();
  29428. }
  29429. // keep first ring vertex values for enclose
  29430. if (j === 0) {
  29431. ringFirstVertex.copyFrom(ringVertex);
  29432. ringFirstNormal.copyFrom(ringNormal);
  29433. }
  29434. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29435. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29436. if (hasRings) {
  29437. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29438. }
  29439. else {
  29440. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29441. }
  29442. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29443. if (faceColors) {
  29444. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29445. }
  29446. }
  29447. // if enclose, add four vertices and their dedicated normals
  29448. if (arc !== 1 && enclose) {
  29449. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29450. positions.push(0, ringVertex.y, 0);
  29451. positions.push(0, ringVertex.y, 0);
  29452. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29453. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29454. quadNormal.normalize();
  29455. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29456. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29457. quadNormal.normalize();
  29458. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29459. if (hasRings) {
  29460. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29461. }
  29462. else {
  29463. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29464. }
  29465. uvs.push(faceUV[s + 1].x, v);
  29466. uvs.push(faceUV[s + 1].z, v);
  29467. if (hasRings) {
  29468. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29469. }
  29470. else {
  29471. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29472. }
  29473. uvs.push(faceUV[s + 2].x, v);
  29474. uvs.push(faceUV[s + 2].z, v);
  29475. if (faceColors) {
  29476. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29477. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29478. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29479. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29480. }
  29481. }
  29482. if (cs !== s) {
  29483. cs = s;
  29484. }
  29485. }
  29486. }
  29487. // indices
  29488. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29489. var s;
  29490. i = 0;
  29491. for (s = 0; s < subdivisions; s++) {
  29492. var i0 = 0;
  29493. var i1 = 0;
  29494. var i2 = 0;
  29495. var i3 = 0;
  29496. for (j = 0; j < tessellation; j++) {
  29497. i0 = i * (e + 1) + j;
  29498. i1 = (i + 1) * (e + 1) + j;
  29499. i2 = i * (e + 1) + (j + 1);
  29500. i3 = (i + 1) * (e + 1) + (j + 1);
  29501. indices.push(i0, i1, i2);
  29502. indices.push(i3, i2, i1);
  29503. }
  29504. if (arc !== 1 && enclose) {
  29505. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29506. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29507. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29508. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29509. }
  29510. i = (hasRings) ? (i + 2) : (i + 1);
  29511. }
  29512. // Caps
  29513. var createCylinderCap = function (isTop) {
  29514. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29515. if (radius === 0) {
  29516. return;
  29517. }
  29518. // Cap positions, normals & uvs
  29519. var angle;
  29520. var circleVector;
  29521. var i;
  29522. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29523. var c = null;
  29524. if (faceColors) {
  29525. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29526. }
  29527. // cap center
  29528. var vbase = positions.length / 3;
  29529. var offset = isTop ? height / 2 : -height / 2;
  29530. var center = new BABYLON.Vector3(0, offset, 0);
  29531. positions.push(center.x, center.y, center.z);
  29532. normals.push(0, isTop ? 1 : -1, 0);
  29533. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29534. if (c) {
  29535. colors.push(c.r, c.g, c.b, c.a);
  29536. }
  29537. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29538. for (i = 0; i <= tessellation; i++) {
  29539. angle = Math.PI * 2 * i * arc / tessellation;
  29540. var cos = Math.cos(-angle);
  29541. var sin = Math.sin(-angle);
  29542. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29543. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29544. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29545. normals.push(0, isTop ? 1 : -1, 0);
  29546. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29547. if (c) {
  29548. colors.push(c.r, c.g, c.b, c.a);
  29549. }
  29550. }
  29551. // Cap indices
  29552. for (i = 0; i < tessellation; i++) {
  29553. if (!isTop) {
  29554. indices.push(vbase);
  29555. indices.push(vbase + (i + 1));
  29556. indices.push(vbase + (i + 2));
  29557. }
  29558. else {
  29559. indices.push(vbase);
  29560. indices.push(vbase + (i + 2));
  29561. indices.push(vbase + (i + 1));
  29562. }
  29563. }
  29564. };
  29565. // add caps to geometry
  29566. createCylinderCap(false);
  29567. createCylinderCap(true);
  29568. // Sides
  29569. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29570. var vertexData = new VertexData();
  29571. vertexData.indices = indices;
  29572. vertexData.positions = positions;
  29573. vertexData.normals = normals;
  29574. vertexData.uvs = uvs;
  29575. if (faceColors) {
  29576. vertexData.colors = colors;
  29577. }
  29578. return vertexData;
  29579. };
  29580. /**
  29581. * Creates the VertexData of the Torus.
  29582. */
  29583. VertexData.CreateTorus = function (options) {
  29584. var indices = [];
  29585. var positions = [];
  29586. var normals = [];
  29587. var uvs = [];
  29588. var diameter = options.diameter || 1;
  29589. var thickness = options.thickness || 0.5;
  29590. var tessellation = options.tessellation || 16;
  29591. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29592. var stride = tessellation + 1;
  29593. for (var i = 0; i <= tessellation; i++) {
  29594. var u = i / tessellation;
  29595. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29596. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29597. for (var j = 0; j <= tessellation; j++) {
  29598. var v = 1 - j / tessellation;
  29599. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29600. var dx = Math.cos(innerAngle);
  29601. var dy = Math.sin(innerAngle);
  29602. // Create a vertex.
  29603. var normal = new BABYLON.Vector3(dx, dy, 0);
  29604. var position = normal.scale(thickness / 2);
  29605. var textureCoordinate = new BABYLON.Vector2(u, v);
  29606. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29607. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29608. positions.push(position.x, position.y, position.z);
  29609. normals.push(normal.x, normal.y, normal.z);
  29610. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29611. // And create indices for two triangles.
  29612. var nextI = (i + 1) % stride;
  29613. var nextJ = (j + 1) % stride;
  29614. indices.push(i * stride + j);
  29615. indices.push(i * stride + nextJ);
  29616. indices.push(nextI * stride + j);
  29617. indices.push(i * stride + nextJ);
  29618. indices.push(nextI * stride + nextJ);
  29619. indices.push(nextI * stride + j);
  29620. }
  29621. }
  29622. // Sides
  29623. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29624. // Result
  29625. var vertexData = new VertexData();
  29626. vertexData.indices = indices;
  29627. vertexData.positions = positions;
  29628. vertexData.normals = normals;
  29629. vertexData.uvs = uvs;
  29630. return vertexData;
  29631. };
  29632. /**
  29633. * Creates the VertexData of the LineSystem.
  29634. */
  29635. VertexData.CreateLineSystem = function (options) {
  29636. var indices = [];
  29637. var positions = [];
  29638. var lines = options.lines;
  29639. var colors = options.colors;
  29640. var vertexColors = [];
  29641. var idx = 0;
  29642. for (var l = 0; l < lines.length; l++) {
  29643. var points = lines[l];
  29644. for (var index = 0; index < points.length; index++) {
  29645. positions.push(points[index].x, points[index].y, points[index].z);
  29646. if (colors) {
  29647. var color = colors[l];
  29648. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29649. }
  29650. if (index > 0) {
  29651. indices.push(idx - 1);
  29652. indices.push(idx);
  29653. }
  29654. idx++;
  29655. }
  29656. }
  29657. var vertexData = new VertexData();
  29658. vertexData.indices = indices;
  29659. vertexData.positions = positions;
  29660. if (colors) {
  29661. vertexData.colors = vertexColors;
  29662. }
  29663. return vertexData;
  29664. };
  29665. /**
  29666. * Create the VertexData of the DashedLines.
  29667. */
  29668. VertexData.CreateDashedLines = function (options) {
  29669. var dashSize = options.dashSize || 3;
  29670. var gapSize = options.gapSize || 1;
  29671. var dashNb = options.dashNb || 200;
  29672. var points = options.points;
  29673. var positions = new Array();
  29674. var indices = new Array();
  29675. var curvect = BABYLON.Vector3.Zero();
  29676. var lg = 0;
  29677. var nb = 0;
  29678. var shft = 0;
  29679. var dashshft = 0;
  29680. var curshft = 0;
  29681. var idx = 0;
  29682. var i = 0;
  29683. for (i = 0; i < points.length - 1; i++) {
  29684. points[i + 1].subtractToRef(points[i], curvect);
  29685. lg += curvect.length();
  29686. }
  29687. shft = lg / dashNb;
  29688. dashshft = dashSize * shft / (dashSize + gapSize);
  29689. for (i = 0; i < points.length - 1; i++) {
  29690. points[i + 1].subtractToRef(points[i], curvect);
  29691. nb = Math.floor(curvect.length() / shft);
  29692. curvect.normalize();
  29693. for (var j = 0; j < nb; j++) {
  29694. curshft = shft * j;
  29695. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29696. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29697. indices.push(idx, idx + 1);
  29698. idx += 2;
  29699. }
  29700. }
  29701. // Result
  29702. var vertexData = new VertexData();
  29703. vertexData.positions = positions;
  29704. vertexData.indices = indices;
  29705. return vertexData;
  29706. };
  29707. /**
  29708. * Creates the VertexData of the Ground.
  29709. */
  29710. VertexData.CreateGround = function (options) {
  29711. var indices = [];
  29712. var positions = [];
  29713. var normals = [];
  29714. var uvs = [];
  29715. var row, col;
  29716. var width = options.width || 1;
  29717. var height = options.height || 1;
  29718. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29719. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29720. for (row = 0; row <= subdivisionsY; row++) {
  29721. for (col = 0; col <= subdivisionsX; col++) {
  29722. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29723. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29724. positions.push(position.x, position.y, position.z);
  29725. normals.push(normal.x, normal.y, normal.z);
  29726. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29727. }
  29728. }
  29729. for (row = 0; row < subdivisionsY; row++) {
  29730. for (col = 0; col < subdivisionsX; col++) {
  29731. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29732. indices.push(col + 1 + row * (subdivisionsX + 1));
  29733. indices.push(col + row * (subdivisionsX + 1));
  29734. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29735. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29736. indices.push(col + row * (subdivisionsX + 1));
  29737. }
  29738. }
  29739. // Result
  29740. var vertexData = new VertexData();
  29741. vertexData.indices = indices;
  29742. vertexData.positions = positions;
  29743. vertexData.normals = normals;
  29744. vertexData.uvs = uvs;
  29745. return vertexData;
  29746. };
  29747. /**
  29748. * Creates the VertexData of the TiledGround.
  29749. */
  29750. VertexData.CreateTiledGround = function (options) {
  29751. var xmin = options.xmin || -1.0;
  29752. var zmin = options.zmin || -1.0;
  29753. var xmax = options.xmax || 1.0;
  29754. var zmax = options.zmax || 1.0;
  29755. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29756. var precision = options.precision || { w: 1, h: 1 };
  29757. var indices = new Array();
  29758. var positions = new Array();
  29759. var normals = new Array();
  29760. var uvs = new Array();
  29761. var row, col, tileRow, tileCol;
  29762. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29763. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29764. precision.w = (precision.w < 1) ? 1 : precision.w;
  29765. precision.h = (precision.h < 1) ? 1 : precision.h;
  29766. var tileSize = {
  29767. 'w': (xmax - xmin) / subdivisions.w,
  29768. 'h': (zmax - zmin) / subdivisions.h
  29769. };
  29770. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29771. // Indices
  29772. var base = positions.length / 3;
  29773. var rowLength = precision.w + 1;
  29774. for (row = 0; row < precision.h; row++) {
  29775. for (col = 0; col < precision.w; col++) {
  29776. var square = [
  29777. base + col + row * rowLength,
  29778. base + (col + 1) + row * rowLength,
  29779. base + (col + 1) + (row + 1) * rowLength,
  29780. base + col + (row + 1) * rowLength
  29781. ];
  29782. indices.push(square[1]);
  29783. indices.push(square[2]);
  29784. indices.push(square[3]);
  29785. indices.push(square[0]);
  29786. indices.push(square[1]);
  29787. indices.push(square[3]);
  29788. }
  29789. }
  29790. // Position, normals and uvs
  29791. var position = BABYLON.Vector3.Zero();
  29792. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29793. for (row = 0; row <= precision.h; row++) {
  29794. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29795. for (col = 0; col <= precision.w; col++) {
  29796. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29797. position.y = 0;
  29798. positions.push(position.x, position.y, position.z);
  29799. normals.push(normal.x, normal.y, normal.z);
  29800. uvs.push(col / precision.w, row / precision.h);
  29801. }
  29802. }
  29803. }
  29804. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29805. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29806. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29807. }
  29808. }
  29809. // Result
  29810. var vertexData = new VertexData();
  29811. vertexData.indices = indices;
  29812. vertexData.positions = positions;
  29813. vertexData.normals = normals;
  29814. vertexData.uvs = uvs;
  29815. return vertexData;
  29816. };
  29817. /**
  29818. * Creates the VertexData of the Ground designed from a heightmap.
  29819. */
  29820. VertexData.CreateGroundFromHeightMap = function (options) {
  29821. var indices = [];
  29822. var positions = [];
  29823. var normals = [];
  29824. var uvs = [];
  29825. var row, col;
  29826. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29827. // Vertices
  29828. for (row = 0; row <= options.subdivisions; row++) {
  29829. for (col = 0; col <= options.subdivisions; col++) {
  29830. 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));
  29831. // Compute height
  29832. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29833. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29834. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29835. var r = options.buffer[pos] / 255.0;
  29836. var g = options.buffer[pos + 1] / 255.0;
  29837. var b = options.buffer[pos + 2] / 255.0;
  29838. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29839. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29840. // Add vertex
  29841. positions.push(position.x, position.y, position.z);
  29842. normals.push(0, 0, 0);
  29843. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29844. }
  29845. }
  29846. // Indices
  29847. for (row = 0; row < options.subdivisions; row++) {
  29848. for (col = 0; col < options.subdivisions; col++) {
  29849. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29850. indices.push(col + 1 + row * (options.subdivisions + 1));
  29851. indices.push(col + row * (options.subdivisions + 1));
  29852. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29853. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29854. indices.push(col + row * (options.subdivisions + 1));
  29855. }
  29856. }
  29857. // Normals
  29858. VertexData.ComputeNormals(positions, indices, normals);
  29859. // Result
  29860. var vertexData = new VertexData();
  29861. vertexData.indices = indices;
  29862. vertexData.positions = positions;
  29863. vertexData.normals = normals;
  29864. vertexData.uvs = uvs;
  29865. return vertexData;
  29866. };
  29867. /**
  29868. * Creates the VertexData of the Plane.
  29869. */
  29870. VertexData.CreatePlane = function (options) {
  29871. var indices = [];
  29872. var positions = [];
  29873. var normals = [];
  29874. var uvs = [];
  29875. var width = options.width || options.size || 1;
  29876. var height = options.height || options.size || 1;
  29877. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29878. // Vertices
  29879. var halfWidth = width / 2.0;
  29880. var halfHeight = height / 2.0;
  29881. positions.push(-halfWidth, -halfHeight, 0);
  29882. normals.push(0, 0, -1.0);
  29883. uvs.push(0.0, 0.0);
  29884. positions.push(halfWidth, -halfHeight, 0);
  29885. normals.push(0, 0, -1.0);
  29886. uvs.push(1.0, 0.0);
  29887. positions.push(halfWidth, halfHeight, 0);
  29888. normals.push(0, 0, -1.0);
  29889. uvs.push(1.0, 1.0);
  29890. positions.push(-halfWidth, halfHeight, 0);
  29891. normals.push(0, 0, -1.0);
  29892. uvs.push(0.0, 1.0);
  29893. // Indices
  29894. indices.push(0);
  29895. indices.push(1);
  29896. indices.push(2);
  29897. indices.push(0);
  29898. indices.push(2);
  29899. indices.push(3);
  29900. // Sides
  29901. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29902. // Result
  29903. var vertexData = new VertexData();
  29904. vertexData.indices = indices;
  29905. vertexData.positions = positions;
  29906. vertexData.normals = normals;
  29907. vertexData.uvs = uvs;
  29908. return vertexData;
  29909. };
  29910. /**
  29911. * Creates the VertexData of the Disc or regular Polygon.
  29912. */
  29913. VertexData.CreateDisc = function (options) {
  29914. var positions = new Array();
  29915. var indices = new Array();
  29916. var normals = new Array();
  29917. var uvs = new Array();
  29918. var radius = options.radius || 0.5;
  29919. var tessellation = options.tessellation || 64;
  29920. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29921. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29922. // positions and uvs
  29923. positions.push(0, 0, 0); // disc center first
  29924. uvs.push(0.5, 0.5);
  29925. var theta = Math.PI * 2 * arc;
  29926. var step = theta / tessellation;
  29927. for (var a = 0; a < theta; a += step) {
  29928. var x = Math.cos(a);
  29929. var y = Math.sin(a);
  29930. var u = (x + 1) / 2;
  29931. var v = (1 - y) / 2;
  29932. positions.push(radius * x, radius * y, 0);
  29933. uvs.push(u, v);
  29934. }
  29935. if (arc === 1) {
  29936. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29937. uvs.push(uvs[2], uvs[3]);
  29938. }
  29939. //indices
  29940. var vertexNb = positions.length / 3;
  29941. for (var i = 1; i < vertexNb - 1; i++) {
  29942. indices.push(i + 1, 0, i);
  29943. }
  29944. // result
  29945. VertexData.ComputeNormals(positions, indices, normals);
  29946. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29947. var vertexData = new VertexData();
  29948. vertexData.indices = indices;
  29949. vertexData.positions = positions;
  29950. vertexData.normals = normals;
  29951. vertexData.uvs = uvs;
  29952. return vertexData;
  29953. };
  29954. /**
  29955. * Re-creates the VertexData of the Polygon for sideOrientation.
  29956. */
  29957. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29958. var faceUV = fUV || new Array(3);
  29959. var faceColors = fColors;
  29960. var colors = [];
  29961. // default face colors and UV if undefined
  29962. for (var f = 0; f < 3; f++) {
  29963. if (faceUV[f] === undefined) {
  29964. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29965. }
  29966. if (faceColors && faceColors[f] === undefined) {
  29967. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29968. }
  29969. }
  29970. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29971. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29972. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29973. var indices = polygon.getIndices();
  29974. // set face colours and textures
  29975. var idx = 0;
  29976. var face = 0;
  29977. for (var index = 0; index < normals.length; index += 3) {
  29978. //Edge Face no. 1
  29979. if (Math.abs(normals[index + 1]) < 0.001) {
  29980. face = 1;
  29981. }
  29982. //Top Face no. 0
  29983. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29984. face = 0;
  29985. }
  29986. //Bottom Face no. 2
  29987. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29988. face = 2;
  29989. }
  29990. idx = index / 3;
  29991. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29992. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29993. if (faceColors) {
  29994. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29995. }
  29996. }
  29997. // sides
  29998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29999. // Result
  30000. var vertexData = new VertexData();
  30001. vertexData.indices = indices;
  30002. vertexData.positions = positions;
  30003. vertexData.normals = normals;
  30004. vertexData.uvs = uvs;
  30005. if (faceColors) {
  30006. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30007. vertexData.colors = totalColors;
  30008. }
  30009. return vertexData;
  30010. };
  30011. /**
  30012. * Creates the VertexData of the IcoSphere.
  30013. */
  30014. VertexData.CreateIcoSphere = function (options) {
  30015. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30016. var radius = options.radius || 1;
  30017. var flat = (options.flat === undefined) ? true : options.flat;
  30018. var subdivisions = options.subdivisions || 4;
  30019. var radiusX = options.radiusX || radius;
  30020. var radiusY = options.radiusY || radius;
  30021. var radiusZ = options.radiusZ || radius;
  30022. var t = (1 + Math.sqrt(5)) / 2;
  30023. // 12 vertex x,y,z
  30024. var ico_vertices = [
  30025. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30026. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30027. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30028. ];
  30029. // index of 3 vertex makes a face of icopshere
  30030. var ico_indices = [
  30031. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30032. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30033. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30034. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30035. ];
  30036. // vertex for uv have aliased position, not for UV
  30037. var vertices_unalias_id = [
  30038. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30039. // vertex alias
  30040. 0,
  30041. 2,
  30042. 3,
  30043. 3,
  30044. 3,
  30045. 4,
  30046. 7,
  30047. 8,
  30048. 9,
  30049. 9,
  30050. 10,
  30051. 11 // 23: B + 12
  30052. ];
  30053. // uv as integer step (not pixels !)
  30054. var ico_vertexuv = [
  30055. 5, 1, 3, 1, 6, 4, 0, 0,
  30056. 5, 3, 4, 2, 2, 2, 4, 0,
  30057. 2, 0, 1, 1, 6, 0, 6, 2,
  30058. // vertex alias (for same vertex on different faces)
  30059. 0, 4,
  30060. 3, 3,
  30061. 4, 4,
  30062. 3, 1,
  30063. 4, 2,
  30064. 4, 4,
  30065. 0, 2,
  30066. 1, 1,
  30067. 2, 2,
  30068. 3, 3,
  30069. 1, 3,
  30070. 2, 4 // 23: B + 12
  30071. ];
  30072. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30073. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30074. // First island of uv mapping
  30075. // v = 4h 3+ 2
  30076. // v = 3h 9+ 4
  30077. // v = 2h 9+ 5 B
  30078. // v = 1h 9 1 0
  30079. // v = 0h 3 8 7 A
  30080. // u = 0 1 2 3 4 5 6 *a
  30081. // Second island of uv mapping
  30082. // v = 4h 0+ B+ 4+
  30083. // v = 3h A+ 2+
  30084. // v = 2h 7+ 6 3+
  30085. // v = 1h 8+ 3+
  30086. // v = 0h
  30087. // u = 0 1 2 3 4 5 6 *a
  30088. // Face layout on texture UV mapping
  30089. // ============
  30090. // \ 4 /\ 16 / ======
  30091. // \ / \ / /\ 11 /
  30092. // \/ 7 \/ / \ /
  30093. // ======= / 10 \/
  30094. // /\ 17 /\ =======
  30095. // / \ / \ \ 15 /\
  30096. // / 8 \/ 12 \ \ / \
  30097. // ============ \/ 6 \
  30098. // \ 18 /\ ============
  30099. // \ / \ \ 5 /\ 0 /
  30100. // \/ 13 \ \ / \ /
  30101. // ======= \/ 1 \/
  30102. // =============
  30103. // /\ 19 /\ 2 /\
  30104. // / \ / \ / \
  30105. // / 14 \/ 9 \/ 3 \
  30106. // ===================
  30107. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30108. var ustep = 138 / 1024;
  30109. var vstep = 239 / 1024;
  30110. var uoffset = 60 / 1024;
  30111. var voffset = 26 / 1024;
  30112. // Second island should have margin, not to touch the first island
  30113. // avoid any borderline artefact in pixel rounding
  30114. var island_u_offset = -40 / 1024;
  30115. var island_v_offset = +20 / 1024;
  30116. // face is either island 0 or 1 :
  30117. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30118. var island = [
  30119. 0, 0, 0, 0, 1,
  30120. 0, 0, 1, 1, 0,
  30121. 0, 0, 1, 1, 0,
  30122. 0, 1, 1, 1, 0 // 15 - 19
  30123. ];
  30124. var indices = new Array();
  30125. var positions = new Array();
  30126. var normals = new Array();
  30127. var uvs = new Array();
  30128. var current_indice = 0;
  30129. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30130. var face_vertex_pos = new Array(3);
  30131. var face_vertex_uv = new Array(3);
  30132. var v012;
  30133. for (v012 = 0; v012 < 3; v012++) {
  30134. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30135. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30136. }
  30137. // create all with normals
  30138. for (var face = 0; face < 20; face++) {
  30139. // 3 vertex per face
  30140. for (v012 = 0; v012 < 3; v012++) {
  30141. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30142. var v_id = ico_indices[3 * face + v012];
  30143. // vertex have 3D position (x,y,z)
  30144. 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]);
  30145. // Normalize to get normal, then scale to radius
  30146. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30147. // uv Coordinates from vertex ID
  30148. 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);
  30149. }
  30150. // Subdivide the face (interpolate pos, norm, uv)
  30151. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30152. // - norm is linear interpolation of vertex corner normal
  30153. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30154. // - uv is linear interpolation
  30155. //
  30156. // Topology is as below for sub-divide by 2
  30157. // vertex shown as v0,v1,v2
  30158. // interp index is i1 to progress in range [v0,v1[
  30159. // interp index is i2 to progress in range [v0,v2[
  30160. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30161. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30162. //
  30163. //
  30164. // i2 v2
  30165. // ^ ^
  30166. // / / \
  30167. // / / \
  30168. // / / \
  30169. // / / (0,1) \
  30170. // / #---------\
  30171. // / / \ (0,0)'/ \
  30172. // / / \ / \
  30173. // / / \ / \
  30174. // / / (0,0) \ / (1,0) \
  30175. // / #---------#---------\
  30176. // v0 v1
  30177. //
  30178. // --------------------> i1
  30179. //
  30180. // interp of (i1,i2):
  30181. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30182. // along i1 : lerp(x0,x1, i1/(S-i2))
  30183. //
  30184. // centroid of triangle is needed to get help normal computation
  30185. // (c1,c2) are used for centroid location
  30186. var interp_vertex = function (i1, i2, c1, c2) {
  30187. // vertex is interpolated from
  30188. // - face_vertex_pos[0..2]
  30189. // - face_vertex_uv[0..2]
  30190. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30191. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30192. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30193. pos_interp.normalize();
  30194. var vertex_normal;
  30195. if (flat) {
  30196. // in flat mode, recalculate normal as face centroid normal
  30197. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30198. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30199. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30200. }
  30201. else {
  30202. // in smooth mode, recalculate normal from each single vertex position
  30203. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30204. }
  30205. // Vertex normal need correction due to X,Y,Z radius scaling
  30206. vertex_normal.x /= radiusX;
  30207. vertex_normal.y /= radiusY;
  30208. vertex_normal.z /= radiusZ;
  30209. vertex_normal.normalize();
  30210. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30211. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30212. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30213. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30214. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30215. uvs.push(uv_interp.x, uv_interp.y);
  30216. // push each vertex has member of a face
  30217. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30218. indices.push(current_indice);
  30219. current_indice++;
  30220. };
  30221. for (var i2 = 0; i2 < subdivisions; i2++) {
  30222. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30223. // face : (i1,i2) for /\ :
  30224. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30225. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30226. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30227. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30228. if (i1 + i2 + 1 < subdivisions) {
  30229. // face : (i1,i2)' for \/ :
  30230. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30231. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30232. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30233. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30234. }
  30235. }
  30236. }
  30237. }
  30238. // Sides
  30239. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30240. // Result
  30241. var vertexData = new VertexData();
  30242. vertexData.indices = indices;
  30243. vertexData.positions = positions;
  30244. vertexData.normals = normals;
  30245. vertexData.uvs = uvs;
  30246. return vertexData;
  30247. };
  30248. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30249. /**
  30250. * Creates the VertexData of the Polyhedron.
  30251. */
  30252. VertexData.CreatePolyhedron = function (options) {
  30253. // provided polyhedron types :
  30254. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30255. // 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)
  30256. var polyhedra = [];
  30257. 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]] };
  30258. 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]] };
  30259. polyhedra[2] = {
  30260. 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]],
  30261. 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]]
  30262. };
  30263. polyhedra[3] = {
  30264. 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]],
  30265. 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]]
  30266. };
  30267. polyhedra[4] = {
  30268. 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]],
  30269. 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]]
  30270. };
  30271. 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]] };
  30272. 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]] };
  30273. 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]] };
  30274. 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]] };
  30275. 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]] };
  30276. 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]] };
  30277. 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]] };
  30278. 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]] };
  30279. 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]] };
  30280. polyhedra[14] = {
  30281. 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]],
  30282. 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]]
  30283. };
  30284. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30285. var size = options.size;
  30286. var sizeX = options.sizeX || size || 1;
  30287. var sizeY = options.sizeY || size || 1;
  30288. var sizeZ = options.sizeZ || size || 1;
  30289. var data = options.custom || polyhedra[type];
  30290. var nbfaces = data.face.length;
  30291. var faceUV = options.faceUV || new Array(nbfaces);
  30292. var faceColors = options.faceColors;
  30293. var flat = (options.flat === undefined) ? true : options.flat;
  30294. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30295. var positions = new Array();
  30296. var indices = new Array();
  30297. var normals = new Array();
  30298. var uvs = new Array();
  30299. var colors = new Array();
  30300. var index = 0;
  30301. var faceIdx = 0; // face cursor in the array "indexes"
  30302. var indexes = new Array();
  30303. var i = 0;
  30304. var f = 0;
  30305. var u, v, ang, x, y, tmp;
  30306. // default face colors and UV if undefined
  30307. if (flat) {
  30308. for (f = 0; f < nbfaces; f++) {
  30309. if (faceColors && faceColors[f] === undefined) {
  30310. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30311. }
  30312. if (faceUV && faceUV[f] === undefined) {
  30313. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30314. }
  30315. }
  30316. }
  30317. if (!flat) {
  30318. for (i = 0; i < data.vertex.length; i++) {
  30319. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30320. uvs.push(0, 0);
  30321. }
  30322. for (f = 0; f < nbfaces; f++) {
  30323. for (i = 0; i < data.face[f].length - 2; i++) {
  30324. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30325. }
  30326. }
  30327. }
  30328. else {
  30329. for (f = 0; f < nbfaces; f++) {
  30330. var fl = data.face[f].length; // number of vertices of the current face
  30331. ang = 2 * Math.PI / fl;
  30332. x = 0.5 * Math.tan(ang / 2);
  30333. y = 0.5;
  30334. // positions, uvs, colors
  30335. for (i = 0; i < fl; i++) {
  30336. // positions
  30337. 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);
  30338. indexes.push(index);
  30339. index++;
  30340. // uvs
  30341. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30342. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30343. uvs.push(u, v);
  30344. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30345. y = x * Math.sin(ang) + y * Math.cos(ang);
  30346. x = tmp;
  30347. // colors
  30348. if (faceColors) {
  30349. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30350. }
  30351. }
  30352. // indices from indexes
  30353. for (i = 0; i < fl - 2; i++) {
  30354. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30355. }
  30356. faceIdx += fl;
  30357. }
  30358. }
  30359. VertexData.ComputeNormals(positions, indices, normals);
  30360. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30361. var vertexData = new VertexData();
  30362. vertexData.positions = positions;
  30363. vertexData.indices = indices;
  30364. vertexData.normals = normals;
  30365. vertexData.uvs = uvs;
  30366. if (faceColors && flat) {
  30367. vertexData.colors = colors;
  30368. }
  30369. return vertexData;
  30370. };
  30371. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30372. /**
  30373. * Creates the VertexData of the Torus Knot.
  30374. */
  30375. VertexData.CreateTorusKnot = function (options) {
  30376. var indices = new Array();
  30377. var positions = new Array();
  30378. var normals = new Array();
  30379. var uvs = new Array();
  30380. var radius = options.radius || 2;
  30381. var tube = options.tube || 0.5;
  30382. var radialSegments = options.radialSegments || 32;
  30383. var tubularSegments = options.tubularSegments || 32;
  30384. var p = options.p || 2;
  30385. var q = options.q || 3;
  30386. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30387. // Helper
  30388. var getPos = function (angle) {
  30389. var cu = Math.cos(angle);
  30390. var su = Math.sin(angle);
  30391. var quOverP = q / p * angle;
  30392. var cs = Math.cos(quOverP);
  30393. var tx = radius * (2 + cs) * 0.5 * cu;
  30394. var ty = radius * (2 + cs) * su * 0.5;
  30395. var tz = radius * Math.sin(quOverP) * 0.5;
  30396. return new BABYLON.Vector3(tx, ty, tz);
  30397. };
  30398. // Vertices
  30399. var i;
  30400. var j;
  30401. for (i = 0; i <= radialSegments; i++) {
  30402. var modI = i % radialSegments;
  30403. var u = modI / radialSegments * 2 * p * Math.PI;
  30404. var p1 = getPos(u);
  30405. var p2 = getPos(u + 0.01);
  30406. var tang = p2.subtract(p1);
  30407. var n = p2.add(p1);
  30408. var bitan = BABYLON.Vector3.Cross(tang, n);
  30409. n = BABYLON.Vector3.Cross(bitan, tang);
  30410. bitan.normalize();
  30411. n.normalize();
  30412. for (j = 0; j < tubularSegments; j++) {
  30413. var modJ = j % tubularSegments;
  30414. var v = modJ / tubularSegments * 2 * Math.PI;
  30415. var cx = -tube * Math.cos(v);
  30416. var cy = tube * Math.sin(v);
  30417. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30418. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30419. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30420. uvs.push(i / radialSegments);
  30421. uvs.push(j / tubularSegments);
  30422. }
  30423. }
  30424. for (i = 0; i < radialSegments; i++) {
  30425. for (j = 0; j < tubularSegments; j++) {
  30426. var jNext = (j + 1) % tubularSegments;
  30427. var a = i * tubularSegments + j;
  30428. var b = (i + 1) * tubularSegments + j;
  30429. var c = (i + 1) * tubularSegments + jNext;
  30430. var d = i * tubularSegments + jNext;
  30431. indices.push(d);
  30432. indices.push(b);
  30433. indices.push(a);
  30434. indices.push(d);
  30435. indices.push(c);
  30436. indices.push(b);
  30437. }
  30438. }
  30439. // Normals
  30440. VertexData.ComputeNormals(positions, indices, normals);
  30441. // Sides
  30442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30443. // Result
  30444. var vertexData = new VertexData();
  30445. vertexData.indices = indices;
  30446. vertexData.positions = positions;
  30447. vertexData.normals = normals;
  30448. vertexData.uvs = uvs;
  30449. return vertexData;
  30450. };
  30451. // Tools
  30452. /**
  30453. * @param {any} - positions (number[] or Float32Array)
  30454. * @param {any} - indices (number[] or Uint16Array)
  30455. * @param {any} - normals (number[] or Float32Array)
  30456. * options (optional) :
  30457. * facetPositions : optional array of facet positions (vector3)
  30458. * facetNormals : optional array of facet normals (vector3)
  30459. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30460. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30461. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30462. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30463. * bInfo : optional bounding info, required for facetPartitioning computation
  30464. * useRightHandedSystem: optional boolean to for right handed system computation
  30465. * depthSort : optional boolean to enable the facet depth sort computation
  30466. * distanceTo : optional Vector3 to compute the facet depth from this location
  30467. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30468. */
  30469. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30470. // temporary scalar variables
  30471. var index = 0; // facet index
  30472. var p1p2x = 0.0; // p1p2 vector x coordinate
  30473. var p1p2y = 0.0; // p1p2 vector y coordinate
  30474. var p1p2z = 0.0; // p1p2 vector z coordinate
  30475. var p3p2x = 0.0; // p3p2 vector x coordinate
  30476. var p3p2y = 0.0; // p3p2 vector y coordinate
  30477. var p3p2z = 0.0; // p3p2 vector z coordinate
  30478. var faceNormalx = 0.0; // facet normal x coordinate
  30479. var faceNormaly = 0.0; // facet normal y coordinate
  30480. var faceNormalz = 0.0; // facet normal z coordinate
  30481. var length = 0.0; // facet normal length before normalization
  30482. var v1x = 0; // vector1 x index in the positions array
  30483. var v1y = 0; // vector1 y index in the positions array
  30484. var v1z = 0; // vector1 z index in the positions array
  30485. var v2x = 0; // vector2 x index in the positions array
  30486. var v2y = 0; // vector2 y index in the positions array
  30487. var v2z = 0; // vector2 z index in the positions array
  30488. var v3x = 0; // vector3 x index in the positions array
  30489. var v3y = 0; // vector3 y index in the positions array
  30490. var v3z = 0; // vector3 z index in the positions array
  30491. var computeFacetNormals = false;
  30492. var computeFacetPositions = false;
  30493. var computeFacetPartitioning = false;
  30494. var computeDepthSort = false;
  30495. var faceNormalSign = 1;
  30496. var ratio = 0;
  30497. var distanceTo = null;
  30498. if (options) {
  30499. computeFacetNormals = (options.facetNormals) ? true : false;
  30500. computeFacetPositions = (options.facetPositions) ? true : false;
  30501. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30502. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30503. ratio = options.ratio || 0;
  30504. computeDepthSort = (options.depthSort) ? true : false;
  30505. distanceTo = (options.distanceTo);
  30506. if (computeDepthSort) {
  30507. if (distanceTo === undefined) {
  30508. distanceTo = BABYLON.Vector3.Zero();
  30509. }
  30510. var depthSortedFacets = options.depthSortedFacets;
  30511. }
  30512. }
  30513. // facetPartitioning reinit if needed
  30514. var xSubRatio = 0;
  30515. var ySubRatio = 0;
  30516. var zSubRatio = 0;
  30517. var subSq = 0;
  30518. if (computeFacetPartitioning && options && options.bbSize) {
  30519. var ox = 0; // X partitioning index for facet position
  30520. var oy = 0; // Y partinioning index for facet position
  30521. var oz = 0; // Z partinioning index for facet position
  30522. var b1x = 0; // X partitioning index for facet v1 vertex
  30523. var b1y = 0; // Y partitioning index for facet v1 vertex
  30524. var b1z = 0; // z partitioning index for facet v1 vertex
  30525. var b2x = 0; // X partitioning index for facet v2 vertex
  30526. var b2y = 0; // Y partitioning index for facet v2 vertex
  30527. var b2z = 0; // Z partitioning index for facet v2 vertex
  30528. var b3x = 0; // X partitioning index for facet v3 vertex
  30529. var b3y = 0; // Y partitioning index for facet v3 vertex
  30530. var b3z = 0; // Z partitioning index for facet v3 vertex
  30531. var block_idx_o = 0; // facet barycenter block index
  30532. var block_idx_v1 = 0; // v1 vertex block index
  30533. var block_idx_v2 = 0; // v2 vertex block index
  30534. var block_idx_v3 = 0; // v3 vertex block index
  30535. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30536. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30537. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30538. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30539. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30540. subSq = options.subDiv.max * options.subDiv.max;
  30541. options.facetPartitioning.length = 0;
  30542. }
  30543. // reset the normals
  30544. for (index = 0; index < positions.length; index++) {
  30545. normals[index] = 0.0;
  30546. }
  30547. // Loop : 1 indice triplet = 1 facet
  30548. var nbFaces = (indices.length / 3) | 0;
  30549. for (index = 0; index < nbFaces; index++) {
  30550. // get the indexes of the coordinates of each vertex of the facet
  30551. v1x = indices[index * 3] * 3;
  30552. v1y = v1x + 1;
  30553. v1z = v1x + 2;
  30554. v2x = indices[index * 3 + 1] * 3;
  30555. v2y = v2x + 1;
  30556. v2z = v2x + 2;
  30557. v3x = indices[index * 3 + 2] * 3;
  30558. v3y = v3x + 1;
  30559. v3z = v3x + 2;
  30560. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30561. p1p2y = positions[v1y] - positions[v2y];
  30562. p1p2z = positions[v1z] - positions[v2z];
  30563. p3p2x = positions[v3x] - positions[v2x];
  30564. p3p2y = positions[v3y] - positions[v2y];
  30565. p3p2z = positions[v3z] - positions[v2z];
  30566. // compute the face normal with the cross product
  30567. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30568. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30569. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30570. // normalize this normal and store it in the array facetData
  30571. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30572. length = (length === 0) ? 1.0 : length;
  30573. faceNormalx /= length;
  30574. faceNormaly /= length;
  30575. faceNormalz /= length;
  30576. if (computeFacetNormals && options) {
  30577. options.facetNormals[index].x = faceNormalx;
  30578. options.facetNormals[index].y = faceNormaly;
  30579. options.facetNormals[index].z = faceNormalz;
  30580. }
  30581. if (computeFacetPositions && options) {
  30582. // compute and the facet barycenter coordinates in the array facetPositions
  30583. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30584. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30585. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30586. }
  30587. if (computeFacetPartitioning && options) {
  30588. // store the facet indexes in arrays in the main facetPartitioning array :
  30589. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30590. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30591. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30592. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30593. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30594. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30595. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30596. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30597. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30598. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30599. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30600. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30601. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30602. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30603. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30604. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30605. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30606. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30607. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30608. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30609. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30610. // push each facet index in each block containing the vertex
  30611. options.facetPartitioning[block_idx_v1].push(index);
  30612. if (block_idx_v2 != block_idx_v1) {
  30613. options.facetPartitioning[block_idx_v2].push(index);
  30614. }
  30615. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30616. options.facetPartitioning[block_idx_v3].push(index);
  30617. }
  30618. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30619. options.facetPartitioning[block_idx_o].push(index);
  30620. }
  30621. }
  30622. if (computeDepthSort && options && options.facetPositions) {
  30623. var dsf = depthSortedFacets[index];
  30624. dsf.ind = index * 3;
  30625. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30626. }
  30627. // compute the normals anyway
  30628. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30629. normals[v1y] += faceNormaly;
  30630. normals[v1z] += faceNormalz;
  30631. normals[v2x] += faceNormalx;
  30632. normals[v2y] += faceNormaly;
  30633. normals[v2z] += faceNormalz;
  30634. normals[v3x] += faceNormalx;
  30635. normals[v3y] += faceNormaly;
  30636. normals[v3z] += faceNormalz;
  30637. }
  30638. // last normalization of each normal
  30639. for (index = 0; index < normals.length / 3; index++) {
  30640. faceNormalx = normals[index * 3];
  30641. faceNormaly = normals[index * 3 + 1];
  30642. faceNormalz = normals[index * 3 + 2];
  30643. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30644. length = (length === 0) ? 1.0 : length;
  30645. faceNormalx /= length;
  30646. faceNormaly /= length;
  30647. faceNormalz /= length;
  30648. normals[index * 3] = faceNormalx;
  30649. normals[index * 3 + 1] = faceNormaly;
  30650. normals[index * 3 + 2] = faceNormalz;
  30651. }
  30652. };
  30653. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30654. var li = indices.length;
  30655. var ln = normals.length;
  30656. var i;
  30657. var n;
  30658. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30659. switch (sideOrientation) {
  30660. case BABYLON.Mesh.FRONTSIDE:
  30661. // nothing changed
  30662. break;
  30663. case BABYLON.Mesh.BACKSIDE:
  30664. var tmp;
  30665. // indices
  30666. for (i = 0; i < li; i += 3) {
  30667. tmp = indices[i];
  30668. indices[i] = indices[i + 2];
  30669. indices[i + 2] = tmp;
  30670. }
  30671. // normals
  30672. for (n = 0; n < ln; n++) {
  30673. normals[n] = -normals[n];
  30674. }
  30675. break;
  30676. case BABYLON.Mesh.DOUBLESIDE:
  30677. // positions
  30678. var lp = positions.length;
  30679. var l = lp / 3;
  30680. for (var p = 0; p < lp; p++) {
  30681. positions[lp + p] = positions[p];
  30682. }
  30683. // indices
  30684. for (i = 0; i < li; i += 3) {
  30685. indices[i + li] = indices[i + 2] + l;
  30686. indices[i + 1 + li] = indices[i + 1] + l;
  30687. indices[i + 2 + li] = indices[i] + l;
  30688. }
  30689. // normals
  30690. for (n = 0; n < ln; n++) {
  30691. normals[ln + n] = -normals[n];
  30692. }
  30693. // uvs
  30694. var lu = uvs.length;
  30695. var u = 0;
  30696. for (u = 0; u < lu; u++) {
  30697. uvs[u + lu] = uvs[u];
  30698. }
  30699. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30700. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30701. u = 0;
  30702. for (i = 0; i < lu / 2; i++) {
  30703. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30704. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30705. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30706. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30707. u += 2;
  30708. }
  30709. break;
  30710. }
  30711. };
  30712. /**
  30713. * Creates a new VertexData from the imported parameters.
  30714. */
  30715. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30716. var vertexData = new VertexData();
  30717. // positions
  30718. var positions = parsedVertexData.positions;
  30719. if (positions) {
  30720. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30721. }
  30722. // normals
  30723. var normals = parsedVertexData.normals;
  30724. if (normals) {
  30725. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30726. }
  30727. // tangents
  30728. var tangents = parsedVertexData.tangents;
  30729. if (tangents) {
  30730. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30731. }
  30732. // uvs
  30733. var uvs = parsedVertexData.uvs;
  30734. if (uvs) {
  30735. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30736. }
  30737. // uv2s
  30738. var uv2s = parsedVertexData.uv2s;
  30739. if (uv2s) {
  30740. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30741. }
  30742. // uv3s
  30743. var uv3s = parsedVertexData.uv3s;
  30744. if (uv3s) {
  30745. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30746. }
  30747. // uv4s
  30748. var uv4s = parsedVertexData.uv4s;
  30749. if (uv4s) {
  30750. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30751. }
  30752. // uv5s
  30753. var uv5s = parsedVertexData.uv5s;
  30754. if (uv5s) {
  30755. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30756. }
  30757. // uv6s
  30758. var uv6s = parsedVertexData.uv6s;
  30759. if (uv6s) {
  30760. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30761. }
  30762. // colors
  30763. var colors = parsedVertexData.colors;
  30764. if (colors) {
  30765. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30766. }
  30767. // matricesIndices
  30768. var matricesIndices = parsedVertexData.matricesIndices;
  30769. if (matricesIndices) {
  30770. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30771. }
  30772. // matricesWeights
  30773. var matricesWeights = parsedVertexData.matricesWeights;
  30774. if (matricesWeights) {
  30775. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30776. }
  30777. // indices
  30778. var indices = parsedVertexData.indices;
  30779. if (indices) {
  30780. vertexData.indices = indices;
  30781. }
  30782. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30783. };
  30784. return VertexData;
  30785. }());
  30786. BABYLON.VertexData = VertexData;
  30787. })(BABYLON || (BABYLON = {}));
  30788. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30789. var BABYLON;
  30790. (function (BABYLON) {
  30791. var Geometry = /** @class */ (function () {
  30792. function Geometry(id, scene, vertexData, updatable, mesh) {
  30793. if (updatable === void 0) { updatable = false; }
  30794. if (mesh === void 0) { mesh = null; }
  30795. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30796. this._totalVertices = 0;
  30797. this._isDisposed = false;
  30798. this._indexBufferIsUpdatable = false;
  30799. this.id = id;
  30800. this._engine = scene.getEngine();
  30801. this._meshes = [];
  30802. this._scene = scene;
  30803. //Init vertex buffer cache
  30804. this._vertexBuffers = {};
  30805. this._indices = [];
  30806. this._updatable = updatable;
  30807. // vertexData
  30808. if (vertexData) {
  30809. this.setAllVerticesData(vertexData, updatable);
  30810. }
  30811. else {
  30812. this._totalVertices = 0;
  30813. this._indices = [];
  30814. }
  30815. if (this._engine.getCaps().vertexArrayObject) {
  30816. this._vertexArrayObjects = {};
  30817. }
  30818. // applyToMesh
  30819. if (mesh) {
  30820. if (mesh.getClassName() === "LinesMesh") {
  30821. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30822. this.updateExtend();
  30823. }
  30824. this.applyToMesh(mesh);
  30825. mesh.computeWorldMatrix(true);
  30826. }
  30827. }
  30828. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30829. /**
  30830. * 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
  30831. * @returns The Bias Vector
  30832. */
  30833. get: function () {
  30834. return this._boundingBias;
  30835. },
  30836. set: function (value) {
  30837. if (this._boundingBias && this._boundingBias.equals(value)) {
  30838. return;
  30839. }
  30840. this._boundingBias = value.clone();
  30841. this.updateBoundingInfo(true, null);
  30842. },
  30843. enumerable: true,
  30844. configurable: true
  30845. });
  30846. Geometry.CreateGeometryForMesh = function (mesh) {
  30847. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30848. geometry.applyToMesh(mesh);
  30849. return geometry;
  30850. };
  30851. Object.defineProperty(Geometry.prototype, "extend", {
  30852. get: function () {
  30853. return this._extend;
  30854. },
  30855. enumerable: true,
  30856. configurable: true
  30857. });
  30858. Geometry.prototype.getScene = function () {
  30859. return this._scene;
  30860. };
  30861. Geometry.prototype.getEngine = function () {
  30862. return this._engine;
  30863. };
  30864. Geometry.prototype.isReady = function () {
  30865. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30866. };
  30867. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30868. get: function () {
  30869. for (var index = 0; index < this._meshes.length; index++) {
  30870. if (!this._meshes[index].doNotSerialize) {
  30871. return false;
  30872. }
  30873. }
  30874. return true;
  30875. },
  30876. enumerable: true,
  30877. configurable: true
  30878. });
  30879. Geometry.prototype._rebuild = function () {
  30880. if (this._vertexArrayObjects) {
  30881. this._vertexArrayObjects = {};
  30882. }
  30883. // Index buffer
  30884. if (this._meshes.length !== 0 && this._indices) {
  30885. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30886. }
  30887. // Vertex buffers
  30888. for (var key in this._vertexBuffers) {
  30889. var vertexBuffer = this._vertexBuffers[key];
  30890. vertexBuffer._rebuild();
  30891. }
  30892. };
  30893. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30894. vertexData.applyToGeometry(this, updatable);
  30895. this.notifyUpdate();
  30896. };
  30897. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30898. if (updatable === void 0) { updatable = false; }
  30899. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30900. this.setVerticesBuffer(buffer);
  30901. };
  30902. Geometry.prototype.removeVerticesData = function (kind) {
  30903. if (this._vertexBuffers[kind]) {
  30904. this._vertexBuffers[kind].dispose();
  30905. delete this._vertexBuffers[kind];
  30906. }
  30907. };
  30908. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30909. var kind = buffer.getKind();
  30910. if (this._vertexBuffers[kind]) {
  30911. this._vertexBuffers[kind].dispose();
  30912. }
  30913. this._vertexBuffers[kind] = buffer;
  30914. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30915. var data = buffer.getData();
  30916. var stride = buffer.getStrideSize();
  30917. this._totalVertices = data.length / stride;
  30918. this.updateExtend(data, stride);
  30919. this._resetPointsArrayCache();
  30920. var meshes = this._meshes;
  30921. var numOfMeshes = meshes.length;
  30922. for (var index = 0; index < numOfMeshes; index++) {
  30923. var mesh = meshes[index];
  30924. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30925. mesh._createGlobalSubMesh(false);
  30926. mesh.computeWorldMatrix(true);
  30927. }
  30928. }
  30929. this.notifyUpdate(kind);
  30930. if (this._vertexArrayObjects) {
  30931. this._disposeVertexArrayObjects();
  30932. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30933. }
  30934. };
  30935. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30936. var vertexBuffer = this.getVertexBuffer(kind);
  30937. if (!vertexBuffer) {
  30938. return;
  30939. }
  30940. vertexBuffer.updateDirectly(data, offset);
  30941. this.notifyUpdate(kind);
  30942. };
  30943. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30944. if (updateExtends === void 0) { updateExtends = false; }
  30945. var vertexBuffer = this.getVertexBuffer(kind);
  30946. if (!vertexBuffer) {
  30947. return;
  30948. }
  30949. vertexBuffer.update(data);
  30950. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30951. var stride = vertexBuffer.getStrideSize();
  30952. this._totalVertices = data.length / stride;
  30953. this.updateBoundingInfo(updateExtends, data);
  30954. }
  30955. this.notifyUpdate(kind);
  30956. };
  30957. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30958. if (updateExtends) {
  30959. this.updateExtend(data);
  30960. }
  30961. var meshes = this._meshes;
  30962. var numOfMeshes = meshes.length;
  30963. this._resetPointsArrayCache();
  30964. for (var index = 0; index < numOfMeshes; index++) {
  30965. var mesh = meshes[index];
  30966. if (updateExtends) {
  30967. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30968. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30969. var subMesh = mesh.subMeshes[subIndex];
  30970. subMesh.refreshBoundingInfo();
  30971. }
  30972. }
  30973. }
  30974. };
  30975. Geometry.prototype._bind = function (effect, indexToBind) {
  30976. if (!effect) {
  30977. return;
  30978. }
  30979. if (indexToBind === undefined) {
  30980. indexToBind = this._indexBuffer;
  30981. }
  30982. var vbs = this.getVertexBuffers();
  30983. if (!vbs) {
  30984. return;
  30985. }
  30986. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30987. this._engine.bindBuffers(vbs, indexToBind, effect);
  30988. return;
  30989. }
  30990. // Using VAO
  30991. if (!this._vertexArrayObjects[effect.key]) {
  30992. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30993. }
  30994. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30995. };
  30996. Geometry.prototype.getTotalVertices = function () {
  30997. if (!this.isReady()) {
  30998. return 0;
  30999. }
  31000. return this._totalVertices;
  31001. };
  31002. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31003. var vertexBuffer = this.getVertexBuffer(kind);
  31004. if (!vertexBuffer) {
  31005. return null;
  31006. }
  31007. var orig = vertexBuffer.getData();
  31008. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31009. return orig;
  31010. }
  31011. else {
  31012. var len = orig.length;
  31013. var copy = [];
  31014. for (var i = 0; i < len; i++) {
  31015. copy.push(orig[i]);
  31016. }
  31017. return copy;
  31018. }
  31019. };
  31020. /**
  31021. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31022. * Possible `kind` values :
  31023. * - BABYLON.VertexBuffer.PositionKind
  31024. * - BABYLON.VertexBuffer.UVKind
  31025. * - BABYLON.VertexBuffer.UV2Kind
  31026. * - BABYLON.VertexBuffer.UV3Kind
  31027. * - BABYLON.VertexBuffer.UV4Kind
  31028. * - BABYLON.VertexBuffer.UV5Kind
  31029. * - BABYLON.VertexBuffer.UV6Kind
  31030. * - BABYLON.VertexBuffer.ColorKind
  31031. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31032. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31033. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31034. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31035. */
  31036. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31037. var vb = this._vertexBuffers[kind];
  31038. if (!vb) {
  31039. return false;
  31040. }
  31041. return vb.isUpdatable();
  31042. };
  31043. Geometry.prototype.getVertexBuffer = function (kind) {
  31044. if (!this.isReady()) {
  31045. return null;
  31046. }
  31047. return this._vertexBuffers[kind];
  31048. };
  31049. Geometry.prototype.getVertexBuffers = function () {
  31050. if (!this.isReady()) {
  31051. return null;
  31052. }
  31053. return this._vertexBuffers;
  31054. };
  31055. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31056. if (!this._vertexBuffers) {
  31057. if (this._delayInfo) {
  31058. return this._delayInfo.indexOf(kind) !== -1;
  31059. }
  31060. return false;
  31061. }
  31062. return this._vertexBuffers[kind] !== undefined;
  31063. };
  31064. Geometry.prototype.getVerticesDataKinds = function () {
  31065. var result = [];
  31066. var kind;
  31067. if (!this._vertexBuffers && this._delayInfo) {
  31068. for (kind in this._delayInfo) {
  31069. result.push(kind);
  31070. }
  31071. }
  31072. else {
  31073. for (kind in this._vertexBuffers) {
  31074. result.push(kind);
  31075. }
  31076. }
  31077. return result;
  31078. };
  31079. Geometry.prototype.updateIndices = function (indices, offset) {
  31080. if (!this._indexBuffer) {
  31081. return;
  31082. }
  31083. if (!this._indexBufferIsUpdatable) {
  31084. this.setIndices(indices, null, true);
  31085. }
  31086. else {
  31087. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31088. }
  31089. };
  31090. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31091. if (totalVertices === void 0) { totalVertices = null; }
  31092. if (updatable === void 0) { updatable = false; }
  31093. if (this._indexBuffer) {
  31094. this._engine._releaseBuffer(this._indexBuffer);
  31095. }
  31096. this._disposeVertexArrayObjects();
  31097. this._indices = indices;
  31098. this._indexBufferIsUpdatable = updatable;
  31099. if (this._meshes.length !== 0 && this._indices) {
  31100. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31101. }
  31102. if (totalVertices != undefined) {
  31103. this._totalVertices = totalVertices;
  31104. }
  31105. var meshes = this._meshes;
  31106. var numOfMeshes = meshes.length;
  31107. for (var index = 0; index < numOfMeshes; index++) {
  31108. meshes[index]._createGlobalSubMesh(true);
  31109. }
  31110. this.notifyUpdate();
  31111. };
  31112. Geometry.prototype.getTotalIndices = function () {
  31113. if (!this.isReady()) {
  31114. return 0;
  31115. }
  31116. return this._indices.length;
  31117. };
  31118. Geometry.prototype.getIndices = function (copyWhenShared) {
  31119. if (!this.isReady()) {
  31120. return null;
  31121. }
  31122. var orig = this._indices;
  31123. if (!copyWhenShared || this._meshes.length === 1) {
  31124. return orig;
  31125. }
  31126. else {
  31127. var len = orig.length;
  31128. var copy = [];
  31129. for (var i = 0; i < len; i++) {
  31130. copy.push(orig[i]);
  31131. }
  31132. return copy;
  31133. }
  31134. };
  31135. Geometry.prototype.getIndexBuffer = function () {
  31136. if (!this.isReady()) {
  31137. return null;
  31138. }
  31139. return this._indexBuffer;
  31140. };
  31141. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31142. if (effect === void 0) { effect = null; }
  31143. if (!effect || !this._vertexArrayObjects) {
  31144. return;
  31145. }
  31146. if (this._vertexArrayObjects[effect.key]) {
  31147. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31148. delete this._vertexArrayObjects[effect.key];
  31149. }
  31150. };
  31151. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31152. var meshes = this._meshes;
  31153. var index = meshes.indexOf(mesh);
  31154. if (index === -1) {
  31155. return;
  31156. }
  31157. meshes.splice(index, 1);
  31158. mesh._geometry = null;
  31159. if (meshes.length === 0 && shouldDispose) {
  31160. this.dispose();
  31161. }
  31162. };
  31163. Geometry.prototype.applyToMesh = function (mesh) {
  31164. if (mesh._geometry === this) {
  31165. return;
  31166. }
  31167. var previousGeometry = mesh._geometry;
  31168. if (previousGeometry) {
  31169. previousGeometry.releaseForMesh(mesh);
  31170. }
  31171. var meshes = this._meshes;
  31172. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31173. mesh._geometry = this;
  31174. this._scene.pushGeometry(this);
  31175. meshes.push(mesh);
  31176. if (this.isReady()) {
  31177. this._applyToMesh(mesh);
  31178. }
  31179. else {
  31180. mesh._boundingInfo = this._boundingInfo;
  31181. }
  31182. };
  31183. Geometry.prototype.updateExtend = function (data, stride) {
  31184. if (data === void 0) { data = null; }
  31185. if (!data) {
  31186. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31187. }
  31188. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31189. };
  31190. Geometry.prototype._applyToMesh = function (mesh) {
  31191. var numOfMeshes = this._meshes.length;
  31192. // vertexBuffers
  31193. for (var kind in this._vertexBuffers) {
  31194. if (numOfMeshes === 1) {
  31195. this._vertexBuffers[kind].create();
  31196. }
  31197. var buffer = this._vertexBuffers[kind].getBuffer();
  31198. if (buffer)
  31199. buffer.references = numOfMeshes;
  31200. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31201. if (!this._extend) {
  31202. this.updateExtend(this._vertexBuffers[kind].getData());
  31203. }
  31204. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31205. mesh._createGlobalSubMesh(false);
  31206. //bounding info was just created again, world matrix should be applied again.
  31207. mesh._updateBoundingInfo();
  31208. }
  31209. }
  31210. // indexBuffer
  31211. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31212. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31213. }
  31214. if (this._indexBuffer) {
  31215. this._indexBuffer.references = numOfMeshes;
  31216. }
  31217. };
  31218. Geometry.prototype.notifyUpdate = function (kind) {
  31219. if (this.onGeometryUpdated) {
  31220. this.onGeometryUpdated(this, kind);
  31221. }
  31222. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31223. var mesh = _a[_i];
  31224. mesh._markSubMeshesAsAttributesDirty();
  31225. }
  31226. };
  31227. Geometry.prototype.load = function (scene, onLoaded) {
  31228. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31229. return;
  31230. }
  31231. if (this.isReady()) {
  31232. if (onLoaded) {
  31233. onLoaded();
  31234. }
  31235. return;
  31236. }
  31237. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31238. this._queueLoad(scene, onLoaded);
  31239. };
  31240. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31241. var _this = this;
  31242. if (!this.delayLoadingFile) {
  31243. return;
  31244. }
  31245. scene._addPendingData(this);
  31246. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31247. if (!_this._delayLoadingFunction) {
  31248. return;
  31249. }
  31250. _this._delayLoadingFunction(JSON.parse(data), _this);
  31251. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31252. _this._delayInfo = [];
  31253. scene._removePendingData(_this);
  31254. var meshes = _this._meshes;
  31255. var numOfMeshes = meshes.length;
  31256. for (var index = 0; index < numOfMeshes; index++) {
  31257. _this._applyToMesh(meshes[index]);
  31258. }
  31259. if (onLoaded) {
  31260. onLoaded();
  31261. }
  31262. }, function () { }, scene.database);
  31263. };
  31264. /**
  31265. * Invert the geometry to move from a right handed system to a left handed one.
  31266. */
  31267. Geometry.prototype.toLeftHanded = function () {
  31268. // Flip faces
  31269. var tIndices = this.getIndices(false);
  31270. if (tIndices != null && tIndices.length > 0) {
  31271. for (var i = 0; i < tIndices.length; i += 3) {
  31272. var tTemp = tIndices[i + 0];
  31273. tIndices[i + 0] = tIndices[i + 2];
  31274. tIndices[i + 2] = tTemp;
  31275. }
  31276. this.setIndices(tIndices);
  31277. }
  31278. // Negate position.z
  31279. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31280. if (tPositions != null && tPositions.length > 0) {
  31281. for (var i = 0; i < tPositions.length; i += 3) {
  31282. tPositions[i + 2] = -tPositions[i + 2];
  31283. }
  31284. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31285. }
  31286. // Negate normal.z
  31287. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31288. if (tNormals != null && tNormals.length > 0) {
  31289. for (var i = 0; i < tNormals.length; i += 3) {
  31290. tNormals[i + 2] = -tNormals[i + 2];
  31291. }
  31292. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31293. }
  31294. };
  31295. // Cache
  31296. Geometry.prototype._resetPointsArrayCache = function () {
  31297. this._positions = null;
  31298. };
  31299. Geometry.prototype._generatePointsArray = function () {
  31300. if (this._positions)
  31301. return true;
  31302. this._positions = [];
  31303. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31304. if (!data) {
  31305. return false;
  31306. }
  31307. for (var index = 0; index < data.length; index += 3) {
  31308. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31309. }
  31310. return true;
  31311. };
  31312. Geometry.prototype.isDisposed = function () {
  31313. return this._isDisposed;
  31314. };
  31315. Geometry.prototype._disposeVertexArrayObjects = function () {
  31316. if (this._vertexArrayObjects) {
  31317. for (var kind in this._vertexArrayObjects) {
  31318. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31319. }
  31320. this._vertexArrayObjects = {};
  31321. }
  31322. };
  31323. Geometry.prototype.dispose = function () {
  31324. var meshes = this._meshes;
  31325. var numOfMeshes = meshes.length;
  31326. var index;
  31327. for (index = 0; index < numOfMeshes; index++) {
  31328. this.releaseForMesh(meshes[index]);
  31329. }
  31330. this._meshes = [];
  31331. this._disposeVertexArrayObjects();
  31332. for (var kind in this._vertexBuffers) {
  31333. this._vertexBuffers[kind].dispose();
  31334. }
  31335. this._vertexBuffers = {};
  31336. this._totalVertices = 0;
  31337. if (this._indexBuffer) {
  31338. this._engine._releaseBuffer(this._indexBuffer);
  31339. }
  31340. this._indexBuffer = null;
  31341. this._indices = [];
  31342. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31343. this.delayLoadingFile = null;
  31344. this._delayLoadingFunction = null;
  31345. this._delayInfo = [];
  31346. this._boundingInfo = null;
  31347. this._scene.removeGeometry(this);
  31348. this._isDisposed = true;
  31349. };
  31350. Geometry.prototype.copy = function (id) {
  31351. var vertexData = new BABYLON.VertexData();
  31352. vertexData.indices = [];
  31353. var indices = this.getIndices();
  31354. if (indices) {
  31355. for (var index = 0; index < indices.length; index++) {
  31356. vertexData.indices.push(indices[index]);
  31357. }
  31358. }
  31359. var updatable = false;
  31360. var stopChecking = false;
  31361. var kind;
  31362. for (kind in this._vertexBuffers) {
  31363. // using slice() to make a copy of the array and not just reference it
  31364. var data = this.getVerticesData(kind);
  31365. if (data instanceof Float32Array) {
  31366. vertexData.set(new Float32Array(data), kind);
  31367. }
  31368. else {
  31369. vertexData.set(data.slice(0), kind);
  31370. }
  31371. if (!stopChecking) {
  31372. var vb = this.getVertexBuffer(kind);
  31373. if (vb) {
  31374. updatable = vb.isUpdatable();
  31375. stopChecking = !updatable;
  31376. }
  31377. }
  31378. }
  31379. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31380. geometry.delayLoadState = this.delayLoadState;
  31381. geometry.delayLoadingFile = this.delayLoadingFile;
  31382. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31383. for (kind in this._delayInfo) {
  31384. geometry._delayInfo = geometry._delayInfo || [];
  31385. geometry._delayInfo.push(kind);
  31386. }
  31387. // Bounding info
  31388. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31389. return geometry;
  31390. };
  31391. Geometry.prototype.serialize = function () {
  31392. var serializationObject = {};
  31393. serializationObject.id = this.id;
  31394. serializationObject.updatable = this._updatable;
  31395. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31396. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31397. }
  31398. return serializationObject;
  31399. };
  31400. Geometry.prototype.toNumberArray = function (origin) {
  31401. if (Array.isArray(origin)) {
  31402. return origin;
  31403. }
  31404. else {
  31405. return Array.prototype.slice.call(origin);
  31406. }
  31407. };
  31408. Geometry.prototype.serializeVerticeData = function () {
  31409. var serializationObject = this.serialize();
  31410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31411. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31412. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31413. serializationObject.positions._updatable = true;
  31414. }
  31415. }
  31416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31417. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31418. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31419. serializationObject.normals._updatable = true;
  31420. }
  31421. }
  31422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31423. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31424. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31425. serializationObject.uvs._updatable = true;
  31426. }
  31427. }
  31428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31429. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31430. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31431. serializationObject.uv2s._updatable = true;
  31432. }
  31433. }
  31434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31435. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31436. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31437. serializationObject.uv3s._updatable = true;
  31438. }
  31439. }
  31440. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31441. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31442. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31443. serializationObject.uv4s._updatable = true;
  31444. }
  31445. }
  31446. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31447. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31448. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31449. serializationObject.uv5s._updatable = true;
  31450. }
  31451. }
  31452. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31453. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31454. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31455. serializationObject.uv6s._updatable = true;
  31456. }
  31457. }
  31458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31459. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31460. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31461. serializationObject.colors._updatable = true;
  31462. }
  31463. }
  31464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31465. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31466. serializationObject.matricesIndices._isExpanded = true;
  31467. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31468. serializationObject.matricesIndices._updatable = true;
  31469. }
  31470. }
  31471. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31472. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31473. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31474. serializationObject.matricesWeights._updatable = true;
  31475. }
  31476. }
  31477. serializationObject.indices = this.toNumberArray(this.getIndices());
  31478. return serializationObject;
  31479. };
  31480. // Statics
  31481. Geometry.ExtractFromMesh = function (mesh, id) {
  31482. var geometry = mesh._geometry;
  31483. if (!geometry) {
  31484. return null;
  31485. }
  31486. return geometry.copy(id);
  31487. };
  31488. /**
  31489. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31490. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31491. * Be aware Math.random() could cause collisions, but:
  31492. * "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"
  31493. */
  31494. Geometry.RandomId = function () {
  31495. return BABYLON.Tools.RandomId();
  31496. };
  31497. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31498. var scene = mesh.getScene();
  31499. // Geometry
  31500. var geometryId = parsedGeometry.geometryId;
  31501. if (geometryId) {
  31502. var geometry = scene.getGeometryByID(geometryId);
  31503. if (geometry) {
  31504. geometry.applyToMesh(mesh);
  31505. }
  31506. }
  31507. else if (parsedGeometry instanceof ArrayBuffer) {
  31508. var binaryInfo = mesh._binaryInfo;
  31509. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31510. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31511. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31512. }
  31513. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31514. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31515. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31516. }
  31517. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31518. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31519. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31520. }
  31521. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31522. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31523. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31524. }
  31525. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31526. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31527. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31528. }
  31529. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31530. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31531. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31532. }
  31533. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31534. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31535. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31536. }
  31537. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31538. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31539. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31540. }
  31541. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31542. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31543. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31544. }
  31545. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31546. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31547. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31548. }
  31549. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31550. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31552. }
  31553. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31554. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31555. mesh.setIndices(indicesData, null);
  31556. }
  31557. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31558. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31559. mesh.subMeshes = [];
  31560. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31561. var materialIndex = subMeshesData[(i * 5) + 0];
  31562. var verticesStart = subMeshesData[(i * 5) + 1];
  31563. var verticesCount = subMeshesData[(i * 5) + 2];
  31564. var indexStart = subMeshesData[(i * 5) + 3];
  31565. var indexCount = subMeshesData[(i * 5) + 4];
  31566. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31567. }
  31568. }
  31569. }
  31570. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31571. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31572. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31573. if (parsedGeometry.uvs) {
  31574. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31575. }
  31576. if (parsedGeometry.uvs2) {
  31577. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31578. }
  31579. if (parsedGeometry.uvs3) {
  31580. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31581. }
  31582. if (parsedGeometry.uvs4) {
  31583. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31584. }
  31585. if (parsedGeometry.uvs5) {
  31586. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31587. }
  31588. if (parsedGeometry.uvs6) {
  31589. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31590. }
  31591. if (parsedGeometry.colors) {
  31592. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31593. }
  31594. if (parsedGeometry.matricesIndices) {
  31595. if (!parsedGeometry.matricesIndices._isExpanded) {
  31596. var floatIndices = [];
  31597. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31598. var matricesIndex = parsedGeometry.matricesIndices[i];
  31599. floatIndices.push(matricesIndex & 0x000000FF);
  31600. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31601. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31602. floatIndices.push(matricesIndex >> 24);
  31603. }
  31604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31605. }
  31606. else {
  31607. delete parsedGeometry.matricesIndices._isExpanded;
  31608. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31609. }
  31610. }
  31611. if (parsedGeometry.matricesIndicesExtra) {
  31612. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31613. var floatIndices = [];
  31614. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31615. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31616. floatIndices.push(matricesIndex & 0x000000FF);
  31617. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31618. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31619. floatIndices.push(matricesIndex >> 24);
  31620. }
  31621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31622. }
  31623. else {
  31624. delete parsedGeometry.matricesIndices._isExpanded;
  31625. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31626. }
  31627. }
  31628. if (parsedGeometry.matricesWeights) {
  31629. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31630. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31631. }
  31632. if (parsedGeometry.matricesWeightsExtra) {
  31633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31634. }
  31635. mesh.setIndices(parsedGeometry.indices, null);
  31636. }
  31637. // SubMeshes
  31638. if (parsedGeometry.subMeshes) {
  31639. mesh.subMeshes = [];
  31640. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31641. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31642. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31643. }
  31644. }
  31645. // Flat shading
  31646. if (mesh._shouldGenerateFlatShading) {
  31647. mesh.convertToFlatShadedMesh();
  31648. delete mesh._shouldGenerateFlatShading;
  31649. }
  31650. // Update
  31651. mesh.computeWorldMatrix(true);
  31652. // Octree
  31653. if (scene['_selectionOctree']) {
  31654. scene['_selectionOctree'].addMesh(mesh);
  31655. }
  31656. };
  31657. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31658. var epsilon = 1e-3;
  31659. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31660. return;
  31661. }
  31662. var noInfluenceBoneIndex = 0.0;
  31663. if (parsedGeometry.skeletonId > -1) {
  31664. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31665. if (!skeleton) {
  31666. return;
  31667. }
  31668. noInfluenceBoneIndex = skeleton.bones.length;
  31669. }
  31670. else {
  31671. return;
  31672. }
  31673. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31674. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31675. var matricesWeights = parsedGeometry.matricesWeights;
  31676. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31677. var influencers = parsedGeometry.numBoneInfluencer;
  31678. var size = matricesWeights.length;
  31679. for (var i = 0; i < size; i += 4) {
  31680. var weight = 0.0;
  31681. var firstZeroWeight = -1;
  31682. for (var j = 0; j < 4; j++) {
  31683. var w = matricesWeights[i + j];
  31684. weight += w;
  31685. if (w < epsilon && firstZeroWeight < 0) {
  31686. firstZeroWeight = j;
  31687. }
  31688. }
  31689. if (matricesWeightsExtra) {
  31690. for (var j = 0; j < 4; j++) {
  31691. var w = matricesWeightsExtra[i + j];
  31692. weight += w;
  31693. if (w < epsilon && firstZeroWeight < 0) {
  31694. firstZeroWeight = j + 4;
  31695. }
  31696. }
  31697. }
  31698. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31699. firstZeroWeight = influencers - 1;
  31700. }
  31701. if (weight > epsilon) {
  31702. var mweight = 1.0 / weight;
  31703. for (var j = 0; j < 4; j++) {
  31704. matricesWeights[i + j] *= mweight;
  31705. }
  31706. if (matricesWeightsExtra) {
  31707. for (var j = 0; j < 4; j++) {
  31708. matricesWeightsExtra[i + j] *= mweight;
  31709. }
  31710. }
  31711. }
  31712. else {
  31713. if (firstZeroWeight >= 4) {
  31714. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31715. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31716. }
  31717. else {
  31718. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31719. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31720. }
  31721. }
  31722. }
  31723. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31724. if (parsedGeometry.matricesWeightsExtra) {
  31725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31726. }
  31727. };
  31728. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31729. if (scene.getGeometryByID(parsedVertexData.id)) {
  31730. return null; // null since geometry could be something else than a box...
  31731. }
  31732. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31733. if (BABYLON.Tags) {
  31734. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31735. }
  31736. if (parsedVertexData.delayLoadingFile) {
  31737. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31738. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31739. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31740. geometry._delayInfo = [];
  31741. if (parsedVertexData.hasUVs) {
  31742. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31743. }
  31744. if (parsedVertexData.hasUVs2) {
  31745. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31746. }
  31747. if (parsedVertexData.hasUVs3) {
  31748. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31749. }
  31750. if (parsedVertexData.hasUVs4) {
  31751. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31752. }
  31753. if (parsedVertexData.hasUVs5) {
  31754. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31755. }
  31756. if (parsedVertexData.hasUVs6) {
  31757. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31758. }
  31759. if (parsedVertexData.hasColors) {
  31760. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31761. }
  31762. if (parsedVertexData.hasMatricesIndices) {
  31763. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31764. }
  31765. if (parsedVertexData.hasMatricesWeights) {
  31766. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31767. }
  31768. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31769. }
  31770. else {
  31771. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31772. }
  31773. scene.pushGeometry(geometry, true);
  31774. return geometry;
  31775. };
  31776. return Geometry;
  31777. }());
  31778. BABYLON.Geometry = Geometry;
  31779. /////// Primitives //////////////////////////////////////////////
  31780. (function (Geometry) {
  31781. var Primitives;
  31782. (function (Primitives) {
  31783. /// Abstract class
  31784. var _Primitive = /** @class */ (function (_super) {
  31785. __extends(_Primitive, _super);
  31786. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31787. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31788. if (mesh === void 0) { mesh = null; }
  31789. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31790. _this._canBeRegenerated = _canBeRegenerated;
  31791. _this._beingRegenerated = true;
  31792. _this.regenerate();
  31793. _this._beingRegenerated = false;
  31794. return _this;
  31795. }
  31796. _Primitive.prototype.canBeRegenerated = function () {
  31797. return this._canBeRegenerated;
  31798. };
  31799. _Primitive.prototype.regenerate = function () {
  31800. if (!this._canBeRegenerated) {
  31801. return;
  31802. }
  31803. this._beingRegenerated = true;
  31804. this.setAllVerticesData(this._regenerateVertexData(), false);
  31805. this._beingRegenerated = false;
  31806. };
  31807. _Primitive.prototype.asNewGeometry = function (id) {
  31808. return _super.prototype.copy.call(this, id);
  31809. };
  31810. // overrides
  31811. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31812. if (!this._beingRegenerated) {
  31813. return;
  31814. }
  31815. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31816. };
  31817. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31818. if (!this._beingRegenerated) {
  31819. return;
  31820. }
  31821. _super.prototype.setVerticesData.call(this, kind, data, false);
  31822. };
  31823. // to override
  31824. // protected
  31825. _Primitive.prototype._regenerateVertexData = function () {
  31826. throw new Error("Abstract method");
  31827. };
  31828. _Primitive.prototype.copy = function (id) {
  31829. throw new Error("Must be overriden in sub-classes.");
  31830. };
  31831. _Primitive.prototype.serialize = function () {
  31832. var serializationObject = _super.prototype.serialize.call(this);
  31833. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31834. return serializationObject;
  31835. };
  31836. return _Primitive;
  31837. }(Geometry));
  31838. Primitives._Primitive = _Primitive;
  31839. var Ribbon = /** @class */ (function (_super) {
  31840. __extends(Ribbon, _super);
  31841. // Members
  31842. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31843. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31844. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31845. _this.pathArray = pathArray;
  31846. _this.closeArray = closeArray;
  31847. _this.closePath = closePath;
  31848. _this.offset = offset;
  31849. _this.side = side;
  31850. return _this;
  31851. }
  31852. Ribbon.prototype._regenerateVertexData = function () {
  31853. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31854. };
  31855. Ribbon.prototype.copy = function (id) {
  31856. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31857. };
  31858. return Ribbon;
  31859. }(_Primitive));
  31860. Primitives.Ribbon = Ribbon;
  31861. var Box = /** @class */ (function (_super) {
  31862. __extends(Box, _super);
  31863. // Members
  31864. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31865. if (mesh === void 0) { mesh = null; }
  31866. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31867. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31868. _this.size = size;
  31869. _this.side = side;
  31870. return _this;
  31871. }
  31872. Box.prototype._regenerateVertexData = function () {
  31873. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31874. };
  31875. Box.prototype.copy = function (id) {
  31876. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31877. };
  31878. Box.prototype.serialize = function () {
  31879. var serializationObject = _super.prototype.serialize.call(this);
  31880. serializationObject.size = this.size;
  31881. return serializationObject;
  31882. };
  31883. Box.Parse = function (parsedBox, scene) {
  31884. if (scene.getGeometryByID(parsedBox.id)) {
  31885. return null; // null since geometry could be something else than a box...
  31886. }
  31887. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31888. if (BABYLON.Tags) {
  31889. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31890. }
  31891. scene.pushGeometry(box, true);
  31892. return box;
  31893. };
  31894. return Box;
  31895. }(_Primitive));
  31896. Primitives.Box = Box;
  31897. var Sphere = /** @class */ (function (_super) {
  31898. __extends(Sphere, _super);
  31899. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31900. if (mesh === void 0) { mesh = null; }
  31901. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31902. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31903. _this.segments = segments;
  31904. _this.diameter = diameter;
  31905. _this.side = side;
  31906. return _this;
  31907. }
  31908. Sphere.prototype._regenerateVertexData = function () {
  31909. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31910. };
  31911. Sphere.prototype.copy = function (id) {
  31912. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31913. };
  31914. Sphere.prototype.serialize = function () {
  31915. var serializationObject = _super.prototype.serialize.call(this);
  31916. serializationObject.segments = this.segments;
  31917. serializationObject.diameter = this.diameter;
  31918. return serializationObject;
  31919. };
  31920. Sphere.Parse = function (parsedSphere, scene) {
  31921. if (scene.getGeometryByID(parsedSphere.id)) {
  31922. return null; // null since geometry could be something else than a sphere...
  31923. }
  31924. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31925. if (BABYLON.Tags) {
  31926. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31927. }
  31928. scene.pushGeometry(sphere, true);
  31929. return sphere;
  31930. };
  31931. return Sphere;
  31932. }(_Primitive));
  31933. Primitives.Sphere = Sphere;
  31934. var Disc = /** @class */ (function (_super) {
  31935. __extends(Disc, _super);
  31936. // Members
  31937. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31938. if (mesh === void 0) { mesh = null; }
  31939. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31940. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31941. _this.radius = radius;
  31942. _this.tessellation = tessellation;
  31943. _this.side = side;
  31944. return _this;
  31945. }
  31946. Disc.prototype._regenerateVertexData = function () {
  31947. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31948. };
  31949. Disc.prototype.copy = function (id) {
  31950. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31951. };
  31952. return Disc;
  31953. }(_Primitive));
  31954. Primitives.Disc = Disc;
  31955. var Cylinder = /** @class */ (function (_super) {
  31956. __extends(Cylinder, _super);
  31957. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31958. if (subdivisions === void 0) { subdivisions = 1; }
  31959. if (mesh === void 0) { mesh = null; }
  31960. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31961. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31962. _this.height = height;
  31963. _this.diameterTop = diameterTop;
  31964. _this.diameterBottom = diameterBottom;
  31965. _this.tessellation = tessellation;
  31966. _this.subdivisions = subdivisions;
  31967. _this.side = side;
  31968. return _this;
  31969. }
  31970. Cylinder.prototype._regenerateVertexData = function () {
  31971. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31972. };
  31973. Cylinder.prototype.copy = function (id) {
  31974. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31975. };
  31976. Cylinder.prototype.serialize = function () {
  31977. var serializationObject = _super.prototype.serialize.call(this);
  31978. serializationObject.height = this.height;
  31979. serializationObject.diameterTop = this.diameterTop;
  31980. serializationObject.diameterBottom = this.diameterBottom;
  31981. serializationObject.tessellation = this.tessellation;
  31982. return serializationObject;
  31983. };
  31984. Cylinder.Parse = function (parsedCylinder, scene) {
  31985. if (scene.getGeometryByID(parsedCylinder.id)) {
  31986. return null; // null since geometry could be something else than a cylinder...
  31987. }
  31988. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31989. if (BABYLON.Tags) {
  31990. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31991. }
  31992. scene.pushGeometry(cylinder, true);
  31993. return cylinder;
  31994. };
  31995. return Cylinder;
  31996. }(_Primitive));
  31997. Primitives.Cylinder = Cylinder;
  31998. var Torus = /** @class */ (function (_super) {
  31999. __extends(Torus, _super);
  32000. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32001. if (mesh === void 0) { mesh = null; }
  32002. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32003. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32004. _this.diameter = diameter;
  32005. _this.thickness = thickness;
  32006. _this.tessellation = tessellation;
  32007. _this.side = side;
  32008. return _this;
  32009. }
  32010. Torus.prototype._regenerateVertexData = function () {
  32011. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32012. };
  32013. Torus.prototype.copy = function (id) {
  32014. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32015. };
  32016. Torus.prototype.serialize = function () {
  32017. var serializationObject = _super.prototype.serialize.call(this);
  32018. serializationObject.diameter = this.diameter;
  32019. serializationObject.thickness = this.thickness;
  32020. serializationObject.tessellation = this.tessellation;
  32021. return serializationObject;
  32022. };
  32023. Torus.Parse = function (parsedTorus, scene) {
  32024. if (scene.getGeometryByID(parsedTorus.id)) {
  32025. return null; // null since geometry could be something else than a torus...
  32026. }
  32027. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32028. if (BABYLON.Tags) {
  32029. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32030. }
  32031. scene.pushGeometry(torus, true);
  32032. return torus;
  32033. };
  32034. return Torus;
  32035. }(_Primitive));
  32036. Primitives.Torus = Torus;
  32037. var Ground = /** @class */ (function (_super) {
  32038. __extends(Ground, _super);
  32039. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32040. if (mesh === void 0) { mesh = null; }
  32041. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32042. _this.width = width;
  32043. _this.height = height;
  32044. _this.subdivisions = subdivisions;
  32045. return _this;
  32046. }
  32047. Ground.prototype._regenerateVertexData = function () {
  32048. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32049. };
  32050. Ground.prototype.copy = function (id) {
  32051. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32052. };
  32053. Ground.prototype.serialize = function () {
  32054. var serializationObject = _super.prototype.serialize.call(this);
  32055. serializationObject.width = this.width;
  32056. serializationObject.height = this.height;
  32057. serializationObject.subdivisions = this.subdivisions;
  32058. return serializationObject;
  32059. };
  32060. Ground.Parse = function (parsedGround, scene) {
  32061. if (scene.getGeometryByID(parsedGround.id)) {
  32062. return null; // null since geometry could be something else than a ground...
  32063. }
  32064. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32065. if (BABYLON.Tags) {
  32066. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32067. }
  32068. scene.pushGeometry(ground, true);
  32069. return ground;
  32070. };
  32071. return Ground;
  32072. }(_Primitive));
  32073. Primitives.Ground = Ground;
  32074. var TiledGround = /** @class */ (function (_super) {
  32075. __extends(TiledGround, _super);
  32076. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32077. if (mesh === void 0) { mesh = null; }
  32078. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32079. _this.xmin = xmin;
  32080. _this.zmin = zmin;
  32081. _this.xmax = xmax;
  32082. _this.zmax = zmax;
  32083. _this.subdivisions = subdivisions;
  32084. _this.precision = precision;
  32085. return _this;
  32086. }
  32087. TiledGround.prototype._regenerateVertexData = function () {
  32088. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32089. };
  32090. TiledGround.prototype.copy = function (id) {
  32091. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32092. };
  32093. return TiledGround;
  32094. }(_Primitive));
  32095. Primitives.TiledGround = TiledGround;
  32096. var Plane = /** @class */ (function (_super) {
  32097. __extends(Plane, _super);
  32098. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32099. if (mesh === void 0) { mesh = null; }
  32100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32101. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32102. _this.size = size;
  32103. _this.side = side;
  32104. return _this;
  32105. }
  32106. Plane.prototype._regenerateVertexData = function () {
  32107. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32108. };
  32109. Plane.prototype.copy = function (id) {
  32110. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32111. };
  32112. Plane.prototype.serialize = function () {
  32113. var serializationObject = _super.prototype.serialize.call(this);
  32114. serializationObject.size = this.size;
  32115. return serializationObject;
  32116. };
  32117. Plane.Parse = function (parsedPlane, scene) {
  32118. if (scene.getGeometryByID(parsedPlane.id)) {
  32119. return null; // null since geometry could be something else than a ground...
  32120. }
  32121. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32122. if (BABYLON.Tags) {
  32123. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32124. }
  32125. scene.pushGeometry(plane, true);
  32126. return plane;
  32127. };
  32128. return Plane;
  32129. }(_Primitive));
  32130. Primitives.Plane = Plane;
  32131. var TorusKnot = /** @class */ (function (_super) {
  32132. __extends(TorusKnot, _super);
  32133. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32134. if (mesh === void 0) { mesh = null; }
  32135. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32136. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32137. _this.radius = radius;
  32138. _this.tube = tube;
  32139. _this.radialSegments = radialSegments;
  32140. _this.tubularSegments = tubularSegments;
  32141. _this.p = p;
  32142. _this.q = q;
  32143. _this.side = side;
  32144. return _this;
  32145. }
  32146. TorusKnot.prototype._regenerateVertexData = function () {
  32147. 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 });
  32148. };
  32149. TorusKnot.prototype.copy = function (id) {
  32150. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32151. };
  32152. TorusKnot.prototype.serialize = function () {
  32153. var serializationObject = _super.prototype.serialize.call(this);
  32154. serializationObject.radius = this.radius;
  32155. serializationObject.tube = this.tube;
  32156. serializationObject.radialSegments = this.radialSegments;
  32157. serializationObject.tubularSegments = this.tubularSegments;
  32158. serializationObject.p = this.p;
  32159. serializationObject.q = this.q;
  32160. return serializationObject;
  32161. };
  32162. ;
  32163. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32164. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32165. return null; // null since geometry could be something else than a ground...
  32166. }
  32167. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32168. if (BABYLON.Tags) {
  32169. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32170. }
  32171. scene.pushGeometry(torusKnot, true);
  32172. return torusKnot;
  32173. };
  32174. return TorusKnot;
  32175. }(_Primitive));
  32176. Primitives.TorusKnot = TorusKnot;
  32177. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32178. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32179. })(BABYLON || (BABYLON = {}));
  32180. //# sourceMappingURL=babylon.geometry.js.map
  32181. var BABYLON;
  32182. (function (BABYLON) {
  32183. var PostProcessManager = /** @class */ (function () {
  32184. function PostProcessManager(scene) {
  32185. this._vertexBuffers = {};
  32186. this._scene = scene;
  32187. }
  32188. PostProcessManager.prototype._prepareBuffers = function () {
  32189. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32190. return;
  32191. }
  32192. // VBO
  32193. var vertices = [];
  32194. vertices.push(1, 1);
  32195. vertices.push(-1, 1);
  32196. vertices.push(-1, -1);
  32197. vertices.push(1, -1);
  32198. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32199. this._buildIndexBuffer();
  32200. };
  32201. PostProcessManager.prototype._buildIndexBuffer = function () {
  32202. // Indices
  32203. var indices = [];
  32204. indices.push(0);
  32205. indices.push(1);
  32206. indices.push(2);
  32207. indices.push(0);
  32208. indices.push(2);
  32209. indices.push(3);
  32210. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32211. };
  32212. PostProcessManager.prototype._rebuild = function () {
  32213. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32214. if (!vb) {
  32215. return;
  32216. }
  32217. vb._rebuild();
  32218. this._buildIndexBuffer();
  32219. };
  32220. // Methods
  32221. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32222. if (sourceTexture === void 0) { sourceTexture = null; }
  32223. if (postProcesses === void 0) { postProcesses = null; }
  32224. var camera = this._scene.activeCamera;
  32225. if (!camera) {
  32226. return false;
  32227. }
  32228. var postProcesses = postProcesses || camera._postProcesses;
  32229. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32230. return false;
  32231. }
  32232. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32233. return true;
  32234. };
  32235. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32236. if (targetTexture === void 0) { targetTexture = null; }
  32237. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32238. var engine = this._scene.getEngine();
  32239. for (var index = 0; index < postProcesses.length; index++) {
  32240. if (index < postProcesses.length - 1) {
  32241. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32242. }
  32243. else {
  32244. if (targetTexture) {
  32245. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32246. }
  32247. else {
  32248. engine.restoreDefaultFramebuffer();
  32249. }
  32250. }
  32251. var pp = postProcesses[index];
  32252. var effect = pp.apply();
  32253. if (effect) {
  32254. pp.onBeforeRenderObservable.notifyObservers(effect);
  32255. // VBOs
  32256. this._prepareBuffers();
  32257. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32258. // Draw order
  32259. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32260. pp.onAfterRenderObservable.notifyObservers(effect);
  32261. }
  32262. }
  32263. // Restore depth buffer
  32264. engine.setDepthBuffer(true);
  32265. engine.setDepthWrite(true);
  32266. };
  32267. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32268. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32269. var camera = this._scene.activeCamera;
  32270. if (!camera) {
  32271. return;
  32272. }
  32273. postProcesses = postProcesses || camera._postProcesses;
  32274. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32275. return;
  32276. }
  32277. var engine = this._scene.getEngine();
  32278. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32279. if (index < len - 1) {
  32280. postProcesses[index + 1].activate(camera, targetTexture);
  32281. }
  32282. else {
  32283. if (targetTexture) {
  32284. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32285. }
  32286. else {
  32287. engine.restoreDefaultFramebuffer();
  32288. }
  32289. }
  32290. if (doNotPresent) {
  32291. break;
  32292. }
  32293. var pp = postProcesses[index];
  32294. var effect = pp.apply();
  32295. if (effect) {
  32296. pp.onBeforeRenderObservable.notifyObservers(effect);
  32297. // VBOs
  32298. this._prepareBuffers();
  32299. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32300. // Draw order
  32301. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32302. pp.onAfterRenderObservable.notifyObservers(effect);
  32303. }
  32304. }
  32305. // Restore states
  32306. engine.setDepthBuffer(true);
  32307. engine.setDepthWrite(true);
  32308. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32309. };
  32310. PostProcessManager.prototype.dispose = function () {
  32311. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32312. if (buffer) {
  32313. buffer.dispose();
  32314. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32315. }
  32316. if (this._indexBuffer) {
  32317. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32318. this._indexBuffer = null;
  32319. }
  32320. };
  32321. return PostProcessManager;
  32322. }());
  32323. BABYLON.PostProcessManager = PostProcessManager;
  32324. })(BABYLON || (BABYLON = {}));
  32325. //# sourceMappingURL=babylon.postProcessManager.js.map
  32326. var BABYLON;
  32327. (function (BABYLON) {
  32328. /**
  32329. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32330. */
  32331. var PerformanceMonitor = /** @class */ (function () {
  32332. /**
  32333. * constructor
  32334. * @param frameSampleSize The number of samples required to saturate the sliding window
  32335. */
  32336. function PerformanceMonitor(frameSampleSize) {
  32337. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32338. this._enabled = true;
  32339. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32340. }
  32341. /**
  32342. * Samples current frame
  32343. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32344. */
  32345. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32346. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32347. if (!this._enabled)
  32348. return;
  32349. if (this._lastFrameTimeMs != null) {
  32350. var dt = timeMs - this._lastFrameTimeMs;
  32351. this._rollingFrameTime.add(dt);
  32352. }
  32353. this._lastFrameTimeMs = timeMs;
  32354. };
  32355. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32356. /**
  32357. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32358. * @return Average frame time in milliseconds
  32359. */
  32360. get: function () {
  32361. return this._rollingFrameTime.average;
  32362. },
  32363. enumerable: true,
  32364. configurable: true
  32365. });
  32366. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32367. /**
  32368. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32369. * @return Frame time variance in milliseconds squared
  32370. */
  32371. get: function () {
  32372. return this._rollingFrameTime.variance;
  32373. },
  32374. enumerable: true,
  32375. configurable: true
  32376. });
  32377. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32378. /**
  32379. * Returns the frame time of the most recent frame
  32380. * @return Frame time in milliseconds
  32381. */
  32382. get: function () {
  32383. return this._rollingFrameTime.history(0);
  32384. },
  32385. enumerable: true,
  32386. configurable: true
  32387. });
  32388. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32389. /**
  32390. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32391. * @return Framerate in frames per second
  32392. */
  32393. get: function () {
  32394. return 1000.0 / this._rollingFrameTime.average;
  32395. },
  32396. enumerable: true,
  32397. configurable: true
  32398. });
  32399. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32400. /**
  32401. * Returns the average framerate in frames per second using the most recent frame time
  32402. * @return Framerate in frames per second
  32403. */
  32404. get: function () {
  32405. var history = this._rollingFrameTime.history(0);
  32406. if (history === 0) {
  32407. return 0;
  32408. }
  32409. return 1000.0 / history;
  32410. },
  32411. enumerable: true,
  32412. configurable: true
  32413. });
  32414. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32415. /**
  32416. * Returns true if enough samples have been taken to completely fill the sliding window
  32417. * @return true if saturated
  32418. */
  32419. get: function () {
  32420. return this._rollingFrameTime.isSaturated();
  32421. },
  32422. enumerable: true,
  32423. configurable: true
  32424. });
  32425. /**
  32426. * Enables contributions to the sliding window sample set
  32427. */
  32428. PerformanceMonitor.prototype.enable = function () {
  32429. this._enabled = true;
  32430. };
  32431. /**
  32432. * Disables contributions to the sliding window sample set
  32433. * Samples will not be interpolated over the disabled period
  32434. */
  32435. PerformanceMonitor.prototype.disable = function () {
  32436. this._enabled = false;
  32437. //clear last sample to avoid interpolating over the disabled period when next enabled
  32438. this._lastFrameTimeMs = null;
  32439. };
  32440. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32441. /**
  32442. * Returns true if sampling is enabled
  32443. * @return true if enabled
  32444. */
  32445. get: function () {
  32446. return this._enabled;
  32447. },
  32448. enumerable: true,
  32449. configurable: true
  32450. });
  32451. /**
  32452. * Resets performance monitor
  32453. */
  32454. PerformanceMonitor.prototype.reset = function () {
  32455. //clear last sample to avoid interpolating over the disabled period when next enabled
  32456. this._lastFrameTimeMs = null;
  32457. //wipe record
  32458. this._rollingFrameTime.reset();
  32459. };
  32460. return PerformanceMonitor;
  32461. }());
  32462. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32463. /**
  32464. * RollingAverage
  32465. *
  32466. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32467. */
  32468. var RollingAverage = /** @class */ (function () {
  32469. /**
  32470. * constructor
  32471. * @param length The number of samples required to saturate the sliding window
  32472. */
  32473. function RollingAverage(length) {
  32474. this._samples = new Array(length);
  32475. this.reset();
  32476. }
  32477. /**
  32478. * Adds a sample to the sample set
  32479. * @param v The sample value
  32480. */
  32481. RollingAverage.prototype.add = function (v) {
  32482. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32483. var delta;
  32484. //we need to check if we've already wrapped round
  32485. if (this.isSaturated()) {
  32486. //remove bottom of stack from mean
  32487. var bottomValue = this._samples[this._pos];
  32488. delta = bottomValue - this.average;
  32489. this.average -= delta / (this._sampleCount - 1);
  32490. this._m2 -= delta * (bottomValue - this.average);
  32491. }
  32492. else {
  32493. this._sampleCount++;
  32494. }
  32495. //add new value to mean
  32496. delta = v - this.average;
  32497. this.average += delta / (this._sampleCount);
  32498. this._m2 += delta * (v - this.average);
  32499. //set the new variance
  32500. this.variance = this._m2 / (this._sampleCount - 1);
  32501. this._samples[this._pos] = v;
  32502. this._pos++;
  32503. this._pos %= this._samples.length; //positive wrap around
  32504. };
  32505. /**
  32506. * Returns previously added values or null if outside of history or outside the sliding window domain
  32507. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32508. * @return Value previously recorded with add() or null if outside of range
  32509. */
  32510. RollingAverage.prototype.history = function (i) {
  32511. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32512. return 0;
  32513. }
  32514. var i0 = this._wrapPosition(this._pos - 1.0);
  32515. return this._samples[this._wrapPosition(i0 - i)];
  32516. };
  32517. /**
  32518. * Returns true if enough samples have been taken to completely fill the sliding window
  32519. * @return true if sample-set saturated
  32520. */
  32521. RollingAverage.prototype.isSaturated = function () {
  32522. return this._sampleCount >= this._samples.length;
  32523. };
  32524. /**
  32525. * Resets the rolling average (equivalent to 0 samples taken so far)
  32526. */
  32527. RollingAverage.prototype.reset = function () {
  32528. this.average = 0;
  32529. this.variance = 0;
  32530. this._sampleCount = 0;
  32531. this._pos = 0;
  32532. this._m2 = 0;
  32533. };
  32534. /**
  32535. * Wraps a value around the sample range boundaries
  32536. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32537. * @return Wrapped position in sample range
  32538. */
  32539. RollingAverage.prototype._wrapPosition = function (i) {
  32540. var max = this._samples.length;
  32541. return ((i % max) + max) % max;
  32542. };
  32543. return RollingAverage;
  32544. }());
  32545. BABYLON.RollingAverage = RollingAverage;
  32546. })(BABYLON || (BABYLON = {}));
  32547. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32548. var BABYLON;
  32549. (function (BABYLON) {
  32550. /**
  32551. * This groups together the common properties used for image processing either in direct forward pass
  32552. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32553. * or not.
  32554. */
  32555. var ImageProcessingConfiguration = /** @class */ (function () {
  32556. function ImageProcessingConfiguration() {
  32557. /**
  32558. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32559. */
  32560. this.colorCurves = new BABYLON.ColorCurves();
  32561. this._colorCurvesEnabled = false;
  32562. this._colorGradingEnabled = false;
  32563. this._colorGradingWithGreenDepth = true;
  32564. this._colorGradingBGR = true;
  32565. this._exposure = 1.0;
  32566. this._toneMappingEnabled = false;
  32567. this._contrast = 1.0;
  32568. /**
  32569. * Vignette stretch size.
  32570. */
  32571. this.vignetteStretch = 0;
  32572. /**
  32573. * Vignette centre X Offset.
  32574. */
  32575. this.vignetteCentreX = 0;
  32576. /**
  32577. * Vignette centre Y Offset.
  32578. */
  32579. this.vignetteCentreY = 0;
  32580. /**
  32581. * Vignette weight or intensity of the vignette effect.
  32582. */
  32583. this.vignetteWeight = 1.5;
  32584. /**
  32585. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32586. * if vignetteEnabled is set to true.
  32587. */
  32588. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32589. /**
  32590. * Camera field of view used by the Vignette effect.
  32591. */
  32592. this.vignetteCameraFov = 0.5;
  32593. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32594. this._vignetteEnabled = false;
  32595. this._applyByPostProcess = false;
  32596. this._isEnabled = true;
  32597. /**
  32598. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32599. * @type {BABYLON.Observable}
  32600. */
  32601. this.onUpdateParameters = new BABYLON.Observable();
  32602. }
  32603. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32604. /**
  32605. * Gets wether the color curves effect is enabled.
  32606. */
  32607. get: function () {
  32608. return this._colorCurvesEnabled;
  32609. },
  32610. /**
  32611. * Sets wether the color curves effect is enabled.
  32612. */
  32613. set: function (value) {
  32614. if (this._colorCurvesEnabled === value) {
  32615. return;
  32616. }
  32617. this._colorCurvesEnabled = value;
  32618. this._updateParameters();
  32619. },
  32620. enumerable: true,
  32621. configurable: true
  32622. });
  32623. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32624. /**
  32625. * Gets wether the color grading effect is enabled.
  32626. */
  32627. get: function () {
  32628. return this._colorGradingEnabled;
  32629. },
  32630. /**
  32631. * Sets wether the color grading effect is enabled.
  32632. */
  32633. set: function (value) {
  32634. if (this._colorGradingEnabled === value) {
  32635. return;
  32636. }
  32637. this._colorGradingEnabled = value;
  32638. this._updateParameters();
  32639. },
  32640. enumerable: true,
  32641. configurable: true
  32642. });
  32643. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32644. /**
  32645. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32646. */
  32647. get: function () {
  32648. return this._colorGradingWithGreenDepth;
  32649. },
  32650. /**
  32651. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32652. */
  32653. set: function (value) {
  32654. if (this._colorGradingWithGreenDepth === value) {
  32655. return;
  32656. }
  32657. this._colorGradingWithGreenDepth = value;
  32658. this._updateParameters();
  32659. },
  32660. enumerable: true,
  32661. configurable: true
  32662. });
  32663. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32664. /**
  32665. * Gets wether the color grading texture contains BGR values.
  32666. */
  32667. get: function () {
  32668. return this._colorGradingBGR;
  32669. },
  32670. /**
  32671. * Sets wether the color grading texture contains BGR values.
  32672. */
  32673. set: function (value) {
  32674. if (this._colorGradingBGR === value) {
  32675. return;
  32676. }
  32677. this._colorGradingBGR = value;
  32678. this._updateParameters();
  32679. },
  32680. enumerable: true,
  32681. configurable: true
  32682. });
  32683. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32684. /**
  32685. * Gets the Exposure used in the effect.
  32686. */
  32687. get: function () {
  32688. return this._exposure;
  32689. },
  32690. /**
  32691. * Sets the Exposure used in the effect.
  32692. */
  32693. set: function (value) {
  32694. if (this._exposure === value) {
  32695. return;
  32696. }
  32697. this._exposure = value;
  32698. this._updateParameters();
  32699. },
  32700. enumerable: true,
  32701. configurable: true
  32702. });
  32703. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32704. /**
  32705. * Gets wether the tone mapping effect is enabled.
  32706. */
  32707. get: function () {
  32708. return this._toneMappingEnabled;
  32709. },
  32710. /**
  32711. * Sets wether the tone mapping effect is enabled.
  32712. */
  32713. set: function (value) {
  32714. if (this._toneMappingEnabled === value) {
  32715. return;
  32716. }
  32717. this._toneMappingEnabled = value;
  32718. this._updateParameters();
  32719. },
  32720. enumerable: true,
  32721. configurable: true
  32722. });
  32723. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32724. /**
  32725. * Gets the contrast used in the effect.
  32726. */
  32727. get: function () {
  32728. return this._contrast;
  32729. },
  32730. /**
  32731. * Sets the contrast used in the effect.
  32732. */
  32733. set: function (value) {
  32734. if (this._contrast === value) {
  32735. return;
  32736. }
  32737. this._contrast = value;
  32738. this._updateParameters();
  32739. },
  32740. enumerable: true,
  32741. configurable: true
  32742. });
  32743. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32744. /**
  32745. * Gets the vignette blend mode allowing different kind of effect.
  32746. */
  32747. get: function () {
  32748. return this._vignetteBlendMode;
  32749. },
  32750. /**
  32751. * Sets the vignette blend mode allowing different kind of effect.
  32752. */
  32753. set: function (value) {
  32754. if (this._vignetteBlendMode === value) {
  32755. return;
  32756. }
  32757. this._vignetteBlendMode = value;
  32758. this._updateParameters();
  32759. },
  32760. enumerable: true,
  32761. configurable: true
  32762. });
  32763. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32764. /**
  32765. * Gets wether the vignette effect is enabled.
  32766. */
  32767. get: function () {
  32768. return this._vignetteEnabled;
  32769. },
  32770. /**
  32771. * Sets wether the vignette effect is enabled.
  32772. */
  32773. set: function (value) {
  32774. if (this._vignetteEnabled === value) {
  32775. return;
  32776. }
  32777. this._vignetteEnabled = value;
  32778. this._updateParameters();
  32779. },
  32780. enumerable: true,
  32781. configurable: true
  32782. });
  32783. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32784. /**
  32785. * Gets wether the image processing is applied through a post process or not.
  32786. */
  32787. get: function () {
  32788. return this._applyByPostProcess;
  32789. },
  32790. /**
  32791. * Sets wether the image processing is applied through a post process or not.
  32792. */
  32793. set: function (value) {
  32794. if (this._applyByPostProcess === value) {
  32795. return;
  32796. }
  32797. this._applyByPostProcess = value;
  32798. this._updateParameters();
  32799. },
  32800. enumerable: true,
  32801. configurable: true
  32802. });
  32803. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  32804. /**
  32805. * Gets wether the image processing is enabled or not.
  32806. */
  32807. get: function () {
  32808. return this._isEnabled;
  32809. },
  32810. /**
  32811. * Sets wether the image processing is enabled or not.
  32812. */
  32813. set: function (value) {
  32814. if (this._isEnabled === value) {
  32815. return;
  32816. }
  32817. this._isEnabled = value;
  32818. this._updateParameters();
  32819. },
  32820. enumerable: true,
  32821. configurable: true
  32822. });
  32823. /**
  32824. * Method called each time the image processing information changes requires to recompile the effect.
  32825. */
  32826. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32827. this.onUpdateParameters.notifyObservers(this);
  32828. };
  32829. ImageProcessingConfiguration.prototype.getClassName = function () {
  32830. return "ImageProcessingConfiguration";
  32831. };
  32832. /**
  32833. * Prepare the list of uniforms associated with the Image Processing effects.
  32834. * @param uniformsList The list of uniforms used in the effect
  32835. * @param defines the list of defines currently in use
  32836. */
  32837. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32838. if (defines.EXPOSURE) {
  32839. uniforms.push("exposureLinear");
  32840. }
  32841. if (defines.CONTRAST) {
  32842. uniforms.push("contrast");
  32843. }
  32844. if (defines.COLORGRADING) {
  32845. uniforms.push("colorTransformSettings");
  32846. }
  32847. if (defines.VIGNETTE) {
  32848. uniforms.push("vInverseScreenSize");
  32849. uniforms.push("vignetteSettings1");
  32850. uniforms.push("vignetteSettings2");
  32851. }
  32852. if (defines.COLORCURVES) {
  32853. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32854. }
  32855. };
  32856. /**
  32857. * Prepare the list of samplers associated with the Image Processing effects.
  32858. * @param uniformsList The list of uniforms used in the effect
  32859. * @param defines the list of defines currently in use
  32860. */
  32861. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32862. if (defines.COLORGRADING) {
  32863. samplersList.push("txColorTransform");
  32864. }
  32865. };
  32866. /**
  32867. * Prepare the list of defines associated to the shader.
  32868. * @param defines the list of defines to complete
  32869. */
  32870. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32871. if (forPostProcess === void 0) { forPostProcess = false; }
  32872. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  32873. defines.VIGNETTE = false;
  32874. defines.TONEMAPPING = false;
  32875. defines.CONTRAST = false;
  32876. defines.EXPOSURE = false;
  32877. defines.COLORCURVES = false;
  32878. defines.COLORGRADING = false;
  32879. defines.COLORGRADING3D = false;
  32880. defines.IMAGEPROCESSING = false;
  32881. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  32882. return;
  32883. }
  32884. defines.VIGNETTE = this.vignetteEnabled;
  32885. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32886. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32887. defines.TONEMAPPING = this.toneMappingEnabled;
  32888. defines.CONTRAST = (this.contrast !== 1.0);
  32889. defines.EXPOSURE = (this.exposure !== 1.0);
  32890. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32891. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32892. if (defines.COLORGRADING) {
  32893. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32894. }
  32895. else {
  32896. defines.COLORGRADING3D = false;
  32897. }
  32898. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32899. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32900. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32901. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32902. };
  32903. /**
  32904. * Returns true if all the image processing information are ready.
  32905. */
  32906. ImageProcessingConfiguration.prototype.isReady = function () {
  32907. // Color Grading texure can not be none blocking.
  32908. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32909. };
  32910. /**
  32911. * Binds the image processing to the shader.
  32912. * @param effect The effect to bind to
  32913. */
  32914. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32915. if (aspectRatio === void 0) { aspectRatio = 1; }
  32916. // Color Curves
  32917. if (this._colorCurvesEnabled && this.colorCurves) {
  32918. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32919. }
  32920. // Vignette
  32921. if (this._vignetteEnabled) {
  32922. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32923. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32924. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32925. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32926. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32927. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32928. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32929. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32930. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32931. var vignettePower = -2.0 * this.vignetteWeight;
  32932. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32933. }
  32934. // Exposure
  32935. effect.setFloat("exposureLinear", this.exposure);
  32936. // Contrast
  32937. effect.setFloat("contrast", this.contrast);
  32938. // Color transform settings
  32939. if (this.colorGradingTexture) {
  32940. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32941. var textureSize = this.colorGradingTexture.getSize().height;
  32942. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32943. 0.5 / textureSize, // textureOffset
  32944. textureSize, // textureSize
  32945. this.colorGradingTexture.level // weight
  32946. );
  32947. }
  32948. };
  32949. /**
  32950. * Clones the current image processing instance.
  32951. * @return The cloned image processing
  32952. */
  32953. ImageProcessingConfiguration.prototype.clone = function () {
  32954. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32955. };
  32956. /**
  32957. * Serializes the current image processing instance to a json representation.
  32958. * @return a JSON representation
  32959. */
  32960. ImageProcessingConfiguration.prototype.serialize = function () {
  32961. return BABYLON.SerializationHelper.Serialize(this);
  32962. };
  32963. /**
  32964. * Parses the image processing from a json representation.
  32965. * @param source the JSON source to parse
  32966. * @return The parsed image processing
  32967. */
  32968. ImageProcessingConfiguration.Parse = function (source) {
  32969. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32970. };
  32971. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32972. /**
  32973. * Used to apply the vignette as a mix with the pixel color.
  32974. */
  32975. get: function () {
  32976. return this._VIGNETTEMODE_MULTIPLY;
  32977. },
  32978. enumerable: true,
  32979. configurable: true
  32980. });
  32981. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32982. /**
  32983. * Used to apply the vignette as a replacement of the pixel color.
  32984. */
  32985. get: function () {
  32986. return this._VIGNETTEMODE_OPAQUE;
  32987. },
  32988. enumerable: true,
  32989. configurable: true
  32990. });
  32991. // Static constants associated to the image processing.
  32992. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32993. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32994. __decorate([
  32995. BABYLON.serializeAsColorCurves()
  32996. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32997. __decorate([
  32998. BABYLON.serialize()
  32999. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33000. __decorate([
  33001. BABYLON.serializeAsTexture()
  33002. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33003. __decorate([
  33004. BABYLON.serialize()
  33005. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33006. __decorate([
  33007. BABYLON.serialize()
  33008. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33009. __decorate([
  33010. BABYLON.serialize()
  33011. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33012. __decorate([
  33013. BABYLON.serialize()
  33014. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33015. __decorate([
  33016. BABYLON.serialize()
  33017. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33018. __decorate([
  33019. BABYLON.serialize()
  33020. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33021. __decorate([
  33022. BABYLON.serialize()
  33023. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33024. __decorate([
  33025. BABYLON.serialize()
  33026. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33027. __decorate([
  33028. BABYLON.serialize()
  33029. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33030. __decorate([
  33031. BABYLON.serialize()
  33032. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33033. __decorate([
  33034. BABYLON.serializeAsColor4()
  33035. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33036. __decorate([
  33037. BABYLON.serialize()
  33038. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33039. __decorate([
  33040. BABYLON.serialize()
  33041. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33042. __decorate([
  33043. BABYLON.serialize()
  33044. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33045. __decorate([
  33046. BABYLON.serialize()
  33047. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33048. __decorate([
  33049. BABYLON.serialize()
  33050. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33051. return ImageProcessingConfiguration;
  33052. }());
  33053. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33054. })(BABYLON || (BABYLON = {}));
  33055. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33056. var BABYLON;
  33057. (function (BABYLON) {
  33058. /**
  33059. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33060. * It can help converting any input color in a desired output one. This can then be used to create effects
  33061. * from sepia, black and white to sixties or futuristic rendering...
  33062. *
  33063. * The only supported format is currently 3dl.
  33064. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33065. */
  33066. var ColorGradingTexture = /** @class */ (function (_super) {
  33067. __extends(ColorGradingTexture, _super);
  33068. /**
  33069. * Instantiates a ColorGradingTexture from the following parameters.
  33070. *
  33071. * @param url The location of the color gradind data (currently only supporting 3dl)
  33072. * @param scene The scene the texture will be used in
  33073. */
  33074. function ColorGradingTexture(url, scene) {
  33075. var _this = _super.call(this, scene) || this;
  33076. if (!url) {
  33077. return _this;
  33078. }
  33079. _this._engine = scene.getEngine();
  33080. _this._textureMatrix = BABYLON.Matrix.Identity();
  33081. _this.name = url;
  33082. _this.url = url;
  33083. _this.hasAlpha = false;
  33084. _this.isCube = false;
  33085. _this.is3D = _this._engine.webGLVersion > 1;
  33086. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33087. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33088. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33089. _this.anisotropicFilteringLevel = 1;
  33090. _this._texture = _this._getFromCache(url, true);
  33091. if (!_this._texture) {
  33092. if (!scene.useDelayedTextureLoading) {
  33093. _this.loadTexture();
  33094. }
  33095. else {
  33096. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33097. }
  33098. }
  33099. return _this;
  33100. }
  33101. /**
  33102. * Returns the texture matrix used in most of the material.
  33103. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33104. */
  33105. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33106. return this._textureMatrix;
  33107. };
  33108. /**
  33109. * Occurs when the file being loaded is a .3dl LUT file.
  33110. */
  33111. ColorGradingTexture.prototype.load3dlTexture = function () {
  33112. var engine = this._engine;
  33113. var texture;
  33114. if (engine.webGLVersion === 1) {
  33115. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33116. }
  33117. else {
  33118. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33119. }
  33120. this._texture = texture;
  33121. var callback = function (text) {
  33122. if (typeof text !== "string") {
  33123. return;
  33124. }
  33125. var data = null;
  33126. var tempData = null;
  33127. var line;
  33128. var lines = text.split('\n');
  33129. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33130. var maxColor = 0;
  33131. for (var i = 0; i < lines.length; i++) {
  33132. line = lines[i];
  33133. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33134. continue;
  33135. if (line.indexOf('#') === 0)
  33136. continue;
  33137. var words = line.split(" ");
  33138. if (size === 0) {
  33139. // Number of space + one
  33140. size = words.length;
  33141. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33142. tempData = new Float32Array(size * size * size * 4);
  33143. continue;
  33144. }
  33145. if (size != 0) {
  33146. var r = Math.max(parseInt(words[0]), 0);
  33147. var g = Math.max(parseInt(words[1]), 0);
  33148. var b = Math.max(parseInt(words[2]), 0);
  33149. maxColor = Math.max(r, maxColor);
  33150. maxColor = Math.max(g, maxColor);
  33151. maxColor = Math.max(b, maxColor);
  33152. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33153. if (tempData) {
  33154. tempData[pixelStorageIndex + 0] = r;
  33155. tempData[pixelStorageIndex + 1] = g;
  33156. tempData[pixelStorageIndex + 2] = b;
  33157. }
  33158. pixelIndexSlice++;
  33159. if (pixelIndexSlice % size == 0) {
  33160. pixelIndexH++;
  33161. pixelIndexSlice = 0;
  33162. if (pixelIndexH % size == 0) {
  33163. pixelIndexW++;
  33164. pixelIndexH = 0;
  33165. }
  33166. }
  33167. }
  33168. }
  33169. if (tempData && data) {
  33170. for (var i = 0; i < tempData.length; i++) {
  33171. if (i > 0 && (i + 1) % 4 === 0) {
  33172. data[i] = 255;
  33173. }
  33174. else {
  33175. var value = tempData[i];
  33176. data[i] = (value / maxColor * 255);
  33177. }
  33178. }
  33179. }
  33180. if (texture.is3D) {
  33181. texture.updateSize(size, size, size);
  33182. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33183. }
  33184. else {
  33185. texture.updateSize(size * size, size);
  33186. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33187. }
  33188. };
  33189. BABYLON.Tools.LoadFile(this.url, callback);
  33190. return this._texture;
  33191. };
  33192. /**
  33193. * Starts the loading process of the texture.
  33194. */
  33195. ColorGradingTexture.prototype.loadTexture = function () {
  33196. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33197. this.load3dlTexture();
  33198. }
  33199. };
  33200. /**
  33201. * Clones the color gradind texture.
  33202. */
  33203. ColorGradingTexture.prototype.clone = function () {
  33204. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33205. // Base texture
  33206. newTexture.level = this.level;
  33207. return newTexture;
  33208. };
  33209. /**
  33210. * Called during delayed load for textures.
  33211. */
  33212. ColorGradingTexture.prototype.delayLoad = function () {
  33213. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33214. return;
  33215. }
  33216. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33217. this._texture = this._getFromCache(this.url, true);
  33218. if (!this._texture) {
  33219. this.loadTexture();
  33220. }
  33221. };
  33222. /**
  33223. * Parses a color grading texture serialized by Babylon.
  33224. * @param parsedTexture The texture information being parsedTexture
  33225. * @param scene The scene to load the texture in
  33226. * @param rootUrl The root url of the data assets to load
  33227. * @return A color gradind texture
  33228. */
  33229. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33230. var texture = null;
  33231. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33232. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33233. texture.name = parsedTexture.name;
  33234. texture.level = parsedTexture.level;
  33235. }
  33236. return texture;
  33237. };
  33238. /**
  33239. * Serializes the LUT texture to json format.
  33240. */
  33241. ColorGradingTexture.prototype.serialize = function () {
  33242. if (!this.name) {
  33243. return null;
  33244. }
  33245. var serializationObject = {};
  33246. serializationObject.name = this.name;
  33247. serializationObject.level = this.level;
  33248. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33249. return serializationObject;
  33250. };
  33251. /**
  33252. * Empty line regex stored for GC.
  33253. */
  33254. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33255. return ColorGradingTexture;
  33256. }(BABYLON.BaseTexture));
  33257. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33258. })(BABYLON || (BABYLON = {}));
  33259. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33260. var BABYLON;
  33261. (function (BABYLON) {
  33262. /**
  33263. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33264. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33265. * 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;
  33266. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33267. */
  33268. var ColorCurves = /** @class */ (function () {
  33269. function ColorCurves() {
  33270. this._dirty = true;
  33271. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33272. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33273. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33274. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33275. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33276. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33277. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33278. this._globalHue = 30;
  33279. this._globalDensity = 0;
  33280. this._globalSaturation = 0;
  33281. this._globalExposure = 0;
  33282. this._highlightsHue = 30;
  33283. this._highlightsDensity = 0;
  33284. this._highlightsSaturation = 0;
  33285. this._highlightsExposure = 0;
  33286. this._midtonesHue = 30;
  33287. this._midtonesDensity = 0;
  33288. this._midtonesSaturation = 0;
  33289. this._midtonesExposure = 0;
  33290. this._shadowsHue = 30;
  33291. this._shadowsDensity = 0;
  33292. this._shadowsSaturation = 0;
  33293. this._shadowsExposure = 0;
  33294. }
  33295. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33296. /**
  33297. * Gets the global Hue value.
  33298. * 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).
  33299. */
  33300. get: function () {
  33301. return this._globalHue;
  33302. },
  33303. /**
  33304. * Sets the global Hue value.
  33305. * 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).
  33306. */
  33307. set: function (value) {
  33308. this._globalHue = value;
  33309. this._dirty = true;
  33310. },
  33311. enumerable: true,
  33312. configurable: true
  33313. });
  33314. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33315. /**
  33316. * Gets the global Density value.
  33317. * 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.
  33318. * Values less than zero provide a filter of opposite hue.
  33319. */
  33320. get: function () {
  33321. return this._globalDensity;
  33322. },
  33323. /**
  33324. * Sets the global Density value.
  33325. * 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.
  33326. * Values less than zero provide a filter of opposite hue.
  33327. */
  33328. set: function (value) {
  33329. this._globalDensity = value;
  33330. this._dirty = true;
  33331. },
  33332. enumerable: true,
  33333. configurable: true
  33334. });
  33335. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33336. /**
  33337. * Gets the global Saturation value.
  33338. * 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.
  33339. */
  33340. get: function () {
  33341. return this._globalSaturation;
  33342. },
  33343. /**
  33344. * Sets the global Saturation value.
  33345. * 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.
  33346. */
  33347. set: function (value) {
  33348. this._globalSaturation = value;
  33349. this._dirty = true;
  33350. },
  33351. enumerable: true,
  33352. configurable: true
  33353. });
  33354. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33355. /**
  33356. * Gets the highlights Hue value.
  33357. * 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).
  33358. */
  33359. get: function () {
  33360. return this._highlightsHue;
  33361. },
  33362. /**
  33363. * Sets the highlights Hue value.
  33364. * 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).
  33365. */
  33366. set: function (value) {
  33367. this._highlightsHue = value;
  33368. this._dirty = true;
  33369. },
  33370. enumerable: true,
  33371. configurable: true
  33372. });
  33373. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33374. /**
  33375. * Gets the highlights Density value.
  33376. * 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.
  33377. * Values less than zero provide a filter of opposite hue.
  33378. */
  33379. get: function () {
  33380. return this._highlightsDensity;
  33381. },
  33382. /**
  33383. * Sets the highlights Density value.
  33384. * 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.
  33385. * Values less than zero provide a filter of opposite hue.
  33386. */
  33387. set: function (value) {
  33388. this._highlightsDensity = value;
  33389. this._dirty = true;
  33390. },
  33391. enumerable: true,
  33392. configurable: true
  33393. });
  33394. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33395. /**
  33396. * Gets the highlights Saturation value.
  33397. * 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.
  33398. */
  33399. get: function () {
  33400. return this._highlightsSaturation;
  33401. },
  33402. /**
  33403. * Sets the highlights Saturation value.
  33404. * 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.
  33405. */
  33406. set: function (value) {
  33407. this._highlightsSaturation = value;
  33408. this._dirty = true;
  33409. },
  33410. enumerable: true,
  33411. configurable: true
  33412. });
  33413. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33414. /**
  33415. * Gets the highlights Exposure value.
  33416. * 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.
  33417. */
  33418. get: function () {
  33419. return this._highlightsExposure;
  33420. },
  33421. /**
  33422. * Sets the highlights Exposure value.
  33423. * 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.
  33424. */
  33425. set: function (value) {
  33426. this._highlightsExposure = value;
  33427. this._dirty = true;
  33428. },
  33429. enumerable: true,
  33430. configurable: true
  33431. });
  33432. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33433. /**
  33434. * Gets the midtones Hue value.
  33435. * 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).
  33436. */
  33437. get: function () {
  33438. return this._midtonesHue;
  33439. },
  33440. /**
  33441. * Sets the midtones Hue value.
  33442. * 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).
  33443. */
  33444. set: function (value) {
  33445. this._midtonesHue = value;
  33446. this._dirty = true;
  33447. },
  33448. enumerable: true,
  33449. configurable: true
  33450. });
  33451. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33452. /**
  33453. * Gets the midtones Density value.
  33454. * 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.
  33455. * Values less than zero provide a filter of opposite hue.
  33456. */
  33457. get: function () {
  33458. return this._midtonesDensity;
  33459. },
  33460. /**
  33461. * Sets the midtones Density value.
  33462. * 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.
  33463. * Values less than zero provide a filter of opposite hue.
  33464. */
  33465. set: function (value) {
  33466. this._midtonesDensity = value;
  33467. this._dirty = true;
  33468. },
  33469. enumerable: true,
  33470. configurable: true
  33471. });
  33472. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33473. /**
  33474. * Gets the midtones Saturation value.
  33475. * 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.
  33476. */
  33477. get: function () {
  33478. return this._midtonesSaturation;
  33479. },
  33480. /**
  33481. * Sets the midtones Saturation value.
  33482. * 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.
  33483. */
  33484. set: function (value) {
  33485. this._midtonesSaturation = value;
  33486. this._dirty = true;
  33487. },
  33488. enumerable: true,
  33489. configurable: true
  33490. });
  33491. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33492. /**
  33493. * Gets the midtones Exposure value.
  33494. * 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.
  33495. */
  33496. get: function () {
  33497. return this._midtonesExposure;
  33498. },
  33499. /**
  33500. * Sets the midtones Exposure value.
  33501. * 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.
  33502. */
  33503. set: function (value) {
  33504. this._midtonesExposure = value;
  33505. this._dirty = true;
  33506. },
  33507. enumerable: true,
  33508. configurable: true
  33509. });
  33510. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33511. /**
  33512. * Gets the shadows Hue value.
  33513. * 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).
  33514. */
  33515. get: function () {
  33516. return this._shadowsHue;
  33517. },
  33518. /**
  33519. * Sets the shadows Hue value.
  33520. * 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).
  33521. */
  33522. set: function (value) {
  33523. this._shadowsHue = value;
  33524. this._dirty = true;
  33525. },
  33526. enumerable: true,
  33527. configurable: true
  33528. });
  33529. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33530. /**
  33531. * Gets the shadows Density value.
  33532. * 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.
  33533. * Values less than zero provide a filter of opposite hue.
  33534. */
  33535. get: function () {
  33536. return this._shadowsDensity;
  33537. },
  33538. /**
  33539. * Sets the shadows Density value.
  33540. * 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.
  33541. * Values less than zero provide a filter of opposite hue.
  33542. */
  33543. set: function (value) {
  33544. this._shadowsDensity = value;
  33545. this._dirty = true;
  33546. },
  33547. enumerable: true,
  33548. configurable: true
  33549. });
  33550. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33551. /**
  33552. * Gets the shadows Saturation value.
  33553. * 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.
  33554. */
  33555. get: function () {
  33556. return this._shadowsSaturation;
  33557. },
  33558. /**
  33559. * Sets the shadows Saturation value.
  33560. * 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.
  33561. */
  33562. set: function (value) {
  33563. this._shadowsSaturation = value;
  33564. this._dirty = true;
  33565. },
  33566. enumerable: true,
  33567. configurable: true
  33568. });
  33569. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33570. /**
  33571. * Gets the shadows Exposure value.
  33572. * 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.
  33573. */
  33574. get: function () {
  33575. return this._shadowsExposure;
  33576. },
  33577. /**
  33578. * Sets the shadows Exposure value.
  33579. * 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.
  33580. */
  33581. set: function (value) {
  33582. this._shadowsExposure = value;
  33583. this._dirty = true;
  33584. },
  33585. enumerable: true,
  33586. configurable: true
  33587. });
  33588. ColorCurves.prototype.getClassName = function () {
  33589. return "ColorCurves";
  33590. };
  33591. /**
  33592. * Binds the color curves to the shader.
  33593. * @param colorCurves The color curve to bind
  33594. * @param effect The effect to bind to
  33595. */
  33596. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33597. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33598. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33599. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33600. if (colorCurves._dirty) {
  33601. colorCurves._dirty = false;
  33602. // Fill in global info.
  33603. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33604. // Compute highlights info.
  33605. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33606. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33607. // Compute midtones info.
  33608. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33609. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33610. // Compute shadows info.
  33611. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33612. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33613. // Compute deltas (neutral is midtones).
  33614. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33615. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33616. }
  33617. if (effect) {
  33618. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33619. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33620. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33621. }
  33622. };
  33623. /**
  33624. * Prepare the list of uniforms associated with the ColorCurves effects.
  33625. * @param uniformsList The list of uniforms used in the effect
  33626. */
  33627. ColorCurves.PrepareUniforms = function (uniformsList) {
  33628. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33629. };
  33630. /**
  33631. * Returns color grading data based on a hue, density, saturation and exposure value.
  33632. * @param filterHue The hue of the color filter.
  33633. * @param filterDensity The density of the color filter.
  33634. * @param saturation The saturation.
  33635. * @param exposure The exposure.
  33636. * @param result The result data container.
  33637. */
  33638. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33639. if (hue == null) {
  33640. return;
  33641. }
  33642. hue = ColorCurves.clamp(hue, 0, 360);
  33643. density = ColorCurves.clamp(density, -100, 100);
  33644. saturation = ColorCurves.clamp(saturation, -100, 100);
  33645. exposure = ColorCurves.clamp(exposure, -100, 100);
  33646. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33647. // so that the maximum filter density is only 50% control. This provides fine control
  33648. // for small values and reasonable range.
  33649. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33650. density *= 0.5;
  33651. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33652. if (density < 0) {
  33653. density *= -1;
  33654. hue = (hue + 180) % 360;
  33655. }
  33656. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33657. result.scaleToRef(2, result);
  33658. result.a = 1 + 0.01 * saturation;
  33659. };
  33660. /**
  33661. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33662. * @param value The input slider value in range [-100,100].
  33663. * @returns Adjusted value.
  33664. */
  33665. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33666. value /= 100;
  33667. var x = Math.abs(value);
  33668. x = Math.pow(x, 2);
  33669. if (value < 0) {
  33670. x *= -1;
  33671. }
  33672. x *= 100;
  33673. return x;
  33674. };
  33675. /**
  33676. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33677. * @param hue The hue (H) input.
  33678. * @param saturation The saturation (S) input.
  33679. * @param brightness The brightness (B) input.
  33680. * @result An RGBA color represented as Vector4.
  33681. */
  33682. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33683. var h = ColorCurves.clamp(hue, 0, 360);
  33684. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33685. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33686. if (s === 0) {
  33687. result.r = v;
  33688. result.g = v;
  33689. result.b = v;
  33690. }
  33691. else {
  33692. // sector 0 to 5
  33693. h /= 60;
  33694. var i = Math.floor(h);
  33695. // fractional part of h
  33696. var f = h - i;
  33697. var p = v * (1 - s);
  33698. var q = v * (1 - s * f);
  33699. var t = v * (1 - s * (1 - f));
  33700. switch (i) {
  33701. case 0:
  33702. result.r = v;
  33703. result.g = t;
  33704. result.b = p;
  33705. break;
  33706. case 1:
  33707. result.r = q;
  33708. result.g = v;
  33709. result.b = p;
  33710. break;
  33711. case 2:
  33712. result.r = p;
  33713. result.g = v;
  33714. result.b = t;
  33715. break;
  33716. case 3:
  33717. result.r = p;
  33718. result.g = q;
  33719. result.b = v;
  33720. break;
  33721. case 4:
  33722. result.r = t;
  33723. result.g = p;
  33724. result.b = v;
  33725. break;
  33726. default:// case 5:
  33727. result.r = v;
  33728. result.g = p;
  33729. result.b = q;
  33730. break;
  33731. }
  33732. }
  33733. result.a = 1;
  33734. };
  33735. /**
  33736. * Returns a value clamped between min and max
  33737. * @param value The value to clamp
  33738. * @param min The minimum of value
  33739. * @param max The maximum of value
  33740. * @returns The clamped value.
  33741. */
  33742. ColorCurves.clamp = function (value, min, max) {
  33743. return Math.min(Math.max(value, min), max);
  33744. };
  33745. /**
  33746. * Clones the current color curve instance.
  33747. * @return The cloned curves
  33748. */
  33749. ColorCurves.prototype.clone = function () {
  33750. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33751. };
  33752. /**
  33753. * Serializes the current color curve instance to a json representation.
  33754. * @return a JSON representation
  33755. */
  33756. ColorCurves.prototype.serialize = function () {
  33757. return BABYLON.SerializationHelper.Serialize(this);
  33758. };
  33759. /**
  33760. * Parses the color curve from a json representation.
  33761. * @param source the JSON source to parse
  33762. * @return The parsed curves
  33763. */
  33764. ColorCurves.Parse = function (source) {
  33765. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33766. };
  33767. __decorate([
  33768. BABYLON.serialize()
  33769. ], ColorCurves.prototype, "_globalHue", void 0);
  33770. __decorate([
  33771. BABYLON.serialize()
  33772. ], ColorCurves.prototype, "_globalDensity", void 0);
  33773. __decorate([
  33774. BABYLON.serialize()
  33775. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33776. __decorate([
  33777. BABYLON.serialize()
  33778. ], ColorCurves.prototype, "_globalExposure", void 0);
  33779. __decorate([
  33780. BABYLON.serialize()
  33781. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33782. __decorate([
  33783. BABYLON.serialize()
  33784. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33785. __decorate([
  33786. BABYLON.serialize()
  33787. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33788. __decorate([
  33789. BABYLON.serialize()
  33790. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33791. __decorate([
  33792. BABYLON.serialize()
  33793. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33794. __decorate([
  33795. BABYLON.serialize()
  33796. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33797. __decorate([
  33798. BABYLON.serialize()
  33799. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33800. __decorate([
  33801. BABYLON.serialize()
  33802. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33803. return ColorCurves;
  33804. }());
  33805. BABYLON.ColorCurves = ColorCurves;
  33806. })(BABYLON || (BABYLON = {}));
  33807. //# sourceMappingURL=babylon.colorCurves.js.map
  33808. var BABYLON;
  33809. (function (BABYLON) {
  33810. var MaterialHelper = /** @class */ (function () {
  33811. function MaterialHelper() {
  33812. }
  33813. MaterialHelper.BindEyePosition = function (effect, scene) {
  33814. if (scene._forcedViewPosition) {
  33815. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  33816. return;
  33817. }
  33818. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  33819. };
  33820. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  33821. defines._needUVs = true;
  33822. defines[key] = true;
  33823. if (texture.getTextureMatrix().isIdentity(true)) {
  33824. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  33825. if (texture.coordinatesIndex === 0) {
  33826. defines["MAINUV1"] = true;
  33827. }
  33828. else {
  33829. defines["MAINUV2"] = true;
  33830. }
  33831. }
  33832. else {
  33833. defines[key + "DIRECTUV"] = 0;
  33834. }
  33835. };
  33836. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  33837. var matrix = texture.getTextureMatrix();
  33838. if (!matrix.isIdentity(true)) {
  33839. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  33840. }
  33841. };
  33842. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  33843. if (defines._areMiscDirty) {
  33844. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  33845. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  33846. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  33847. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  33848. }
  33849. };
  33850. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  33851. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  33852. var changed = false;
  33853. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  33854. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  33855. changed = true;
  33856. }
  33857. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  33858. defines["ALPHATEST"] = !defines["ALPHATEST"];
  33859. changed = true;
  33860. }
  33861. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  33862. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  33863. changed = true;
  33864. }
  33865. if (defines["INSTANCES"] !== useInstances) {
  33866. defines["INSTANCES"] = useInstances;
  33867. changed = true;
  33868. }
  33869. if (changed) {
  33870. defines.markAsUnprocessed();
  33871. }
  33872. };
  33873. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  33874. if (useMorphTargets === void 0) { useMorphTargets = false; }
  33875. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  33876. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  33877. return false;
  33878. }
  33879. defines._normals = defines._needNormals;
  33880. defines._uvs = defines._needUVs;
  33881. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  33882. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33883. defines["TANGENT"] = true;
  33884. }
  33885. if (defines._needUVs) {
  33886. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  33887. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  33888. }
  33889. else {
  33890. defines["UV1"] = false;
  33891. defines["UV2"] = false;
  33892. }
  33893. if (useVertexColor) {
  33894. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  33895. defines["VERTEXCOLOR"] = hasVertexColors;
  33896. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  33897. }
  33898. if (useBones) {
  33899. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  33900. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  33901. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  33902. }
  33903. else {
  33904. defines["NUM_BONE_INFLUENCERS"] = 0;
  33905. defines["BonesPerMesh"] = 0;
  33906. }
  33907. }
  33908. if (useMorphTargets) {
  33909. var manager = mesh.morphTargetManager;
  33910. if (manager) {
  33911. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  33912. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  33913. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  33914. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  33915. }
  33916. else {
  33917. defines["MORPHTARGETS_TANGENT"] = false;
  33918. defines["MORPHTARGETS_NORMAL"] = false;
  33919. defines["MORPHTARGETS"] = false;
  33920. defines["NUM_MORPH_INFLUENCERS"] = 0;
  33921. }
  33922. }
  33923. return true;
  33924. };
  33925. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  33926. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  33927. if (disableLighting === void 0) { disableLighting = false; }
  33928. if (!defines._areLightsDirty) {
  33929. return defines._needNormals;
  33930. }
  33931. var lightIndex = 0;
  33932. var needNormals = false;
  33933. var needRebuild = false;
  33934. var lightmapMode = false;
  33935. var shadowEnabled = false;
  33936. var specularEnabled = false;
  33937. if (scene.lightsEnabled && !disableLighting) {
  33938. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  33939. var light = _a[_i];
  33940. needNormals = true;
  33941. if (defines["LIGHT" + lightIndex] === undefined) {
  33942. needRebuild = true;
  33943. }
  33944. defines["LIGHT" + lightIndex] = true;
  33945. defines["SPOTLIGHT" + lightIndex] = false;
  33946. defines["HEMILIGHT" + lightIndex] = false;
  33947. defines["POINTLIGHT" + lightIndex] = false;
  33948. defines["DIRLIGHT" + lightIndex] = false;
  33949. var type;
  33950. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  33951. type = "SPOTLIGHT" + lightIndex;
  33952. }
  33953. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  33954. type = "HEMILIGHT" + lightIndex;
  33955. }
  33956. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  33957. type = "POINTLIGHT" + lightIndex;
  33958. }
  33959. else {
  33960. type = "DIRLIGHT" + lightIndex;
  33961. }
  33962. defines[type] = true;
  33963. // Specular
  33964. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  33965. specularEnabled = true;
  33966. }
  33967. // Shadows
  33968. defines["SHADOW" + lightIndex] = false;
  33969. defines["SHADOWPCF" + lightIndex] = false;
  33970. defines["SHADOWESM" + lightIndex] = false;
  33971. defines["SHADOWCUBE" + lightIndex] = false;
  33972. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  33973. var shadowGenerator = light.getShadowGenerator();
  33974. if (shadowGenerator) {
  33975. shadowEnabled = true;
  33976. shadowGenerator.prepareDefines(defines, lightIndex);
  33977. }
  33978. }
  33979. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  33980. lightmapMode = true;
  33981. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  33982. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  33983. }
  33984. else {
  33985. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  33986. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  33987. }
  33988. lightIndex++;
  33989. if (lightIndex === maxSimultaneousLights)
  33990. break;
  33991. }
  33992. }
  33993. defines["SPECULARTERM"] = specularEnabled;
  33994. defines["SHADOWS"] = shadowEnabled;
  33995. // Resetting all other lights if any
  33996. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  33997. if (defines["LIGHT" + index] !== undefined) {
  33998. defines["LIGHT" + index] = false;
  33999. defines["HEMILIGHT" + lightIndex] = false;
  34000. defines["POINTLIGHT" + lightIndex] = false;
  34001. defines["DIRLIGHT" + lightIndex] = false;
  34002. defines["SPOTLIGHT" + lightIndex] = false;
  34003. defines["SHADOW" + lightIndex] = false;
  34004. }
  34005. }
  34006. var caps = scene.getEngine().getCaps();
  34007. if (defines["SHADOWFLOAT"] === undefined) {
  34008. needRebuild = true;
  34009. }
  34010. defines["SHADOWFLOAT"] = shadowEnabled &&
  34011. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34012. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34013. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34014. if (needRebuild) {
  34015. defines.rebuild();
  34016. }
  34017. return needNormals;
  34018. };
  34019. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34020. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34021. var uniformsList;
  34022. var uniformBuffersList = null;
  34023. if (uniformsListOrOptions.uniformsNames) {
  34024. var options = uniformsListOrOptions;
  34025. uniformsList = options.uniformsNames;
  34026. uniformBuffersList = options.uniformBuffersNames;
  34027. samplersList = options.samplers;
  34028. defines = options.defines;
  34029. maxSimultaneousLights = options.maxSimultaneousLights;
  34030. }
  34031. else {
  34032. uniformsList = uniformsListOrOptions;
  34033. if (!samplersList) {
  34034. samplersList = [];
  34035. }
  34036. }
  34037. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34038. if (!defines["LIGHT" + lightIndex]) {
  34039. break;
  34040. }
  34041. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34042. if (uniformBuffersList) {
  34043. uniformBuffersList.push("Light" + lightIndex);
  34044. }
  34045. samplersList.push("shadowSampler" + lightIndex);
  34046. }
  34047. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34048. uniformsList.push("morphTargetInfluences");
  34049. }
  34050. };
  34051. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34052. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34053. if (rank === void 0) { rank = 0; }
  34054. var lightFallbackRank = 0;
  34055. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34056. if (!defines["LIGHT" + lightIndex]) {
  34057. break;
  34058. }
  34059. if (lightIndex > 0) {
  34060. lightFallbackRank = rank + lightIndex;
  34061. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34062. }
  34063. if (!defines["SHADOWS"]) {
  34064. if (defines["SHADOW" + lightIndex]) {
  34065. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34066. }
  34067. if (defines["SHADOWPCF" + lightIndex]) {
  34068. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34069. }
  34070. if (defines["SHADOWESM" + lightIndex]) {
  34071. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34072. }
  34073. }
  34074. }
  34075. return lightFallbackRank++;
  34076. };
  34077. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34078. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34079. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34080. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34081. var manager = mesh.morphTargetManager;
  34082. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34083. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34084. for (var index = 0; index < influencers; index++) {
  34085. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34086. if (normal) {
  34087. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34088. }
  34089. if (tangent) {
  34090. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34091. }
  34092. if (attribs.length > maxAttributesCount) {
  34093. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34094. }
  34095. }
  34096. }
  34097. };
  34098. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34099. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34100. fallbacks.addCPUSkinningFallback(0, mesh);
  34101. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34102. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34103. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34104. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34105. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34106. }
  34107. }
  34108. };
  34109. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34110. if (defines["INSTANCES"]) {
  34111. attribs.push("world0");
  34112. attribs.push("world1");
  34113. attribs.push("world2");
  34114. attribs.push("world3");
  34115. }
  34116. };
  34117. // Bindings
  34118. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34119. if (light.shadowEnabled && mesh.receiveShadows) {
  34120. var shadowGenerator = light.getShadowGenerator();
  34121. if (shadowGenerator) {
  34122. shadowGenerator.bindShadowLight(lightIndex, effect);
  34123. }
  34124. }
  34125. };
  34126. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34127. light.transferToEffect(effect, lightIndex + "");
  34128. };
  34129. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34130. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34131. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34132. var lightIndex = 0;
  34133. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34134. var light = _a[_i];
  34135. var scaledIntensity = light.getScaledIntensity();
  34136. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  34137. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  34138. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34139. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  34140. if (defines["SPECULARTERM"]) {
  34141. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34142. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  34143. }
  34144. // Shadows
  34145. if (scene.shadowsEnabled) {
  34146. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  34147. }
  34148. light._uniformBuffer.update();
  34149. lightIndex++;
  34150. if (lightIndex === maxSimultaneousLights)
  34151. break;
  34152. }
  34153. };
  34154. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34155. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34156. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34157. effect.setColor3("vFogColor", scene.fogColor);
  34158. }
  34159. };
  34160. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34161. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34162. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34163. if (matrices && effect) {
  34164. effect.setMatrices("mBones", matrices);
  34165. }
  34166. }
  34167. };
  34168. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34169. var manager = abstractMesh.morphTargetManager;
  34170. if (!abstractMesh || !manager) {
  34171. return;
  34172. }
  34173. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34174. };
  34175. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34176. if (defines["LOGARITHMICDEPTH"]) {
  34177. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34178. }
  34179. };
  34180. MaterialHelper.BindClipPlane = function (effect, scene) {
  34181. if (scene.clipPlane) {
  34182. var clipPlane = scene.clipPlane;
  34183. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34184. }
  34185. };
  34186. return MaterialHelper;
  34187. }());
  34188. BABYLON.MaterialHelper = MaterialHelper;
  34189. })(BABYLON || (BABYLON = {}));
  34190. //# sourceMappingURL=babylon.materialHelper.js.map
  34191. var BABYLON;
  34192. (function (BABYLON) {
  34193. var PushMaterial = /** @class */ (function (_super) {
  34194. __extends(PushMaterial, _super);
  34195. function PushMaterial(name, scene) {
  34196. var _this = _super.call(this, name, scene) || this;
  34197. _this.storeEffectOnSubMeshes = true;
  34198. return _this;
  34199. }
  34200. PushMaterial.prototype.getEffect = function () {
  34201. return this._activeEffect;
  34202. };
  34203. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34204. if (!mesh) {
  34205. return false;
  34206. }
  34207. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34208. return true;
  34209. }
  34210. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34211. };
  34212. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34213. this._activeEffect.setMatrix("world", world);
  34214. };
  34215. PushMaterial.prototype.bind = function (world, mesh) {
  34216. if (!mesh) {
  34217. return;
  34218. }
  34219. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34220. };
  34221. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34222. if (effect === void 0) { effect = null; }
  34223. _super.prototype._afterBind.call(this, mesh);
  34224. this.getScene()._cachedEffect = effect;
  34225. };
  34226. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34227. if (visibility === void 0) { visibility = 1; }
  34228. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34229. };
  34230. return PushMaterial;
  34231. }(BABYLON.Material));
  34232. BABYLON.PushMaterial = PushMaterial;
  34233. })(BABYLON || (BABYLON = {}));
  34234. //# sourceMappingURL=babylon.pushMaterial.js.map
  34235. var BABYLON;
  34236. (function (BABYLON) {
  34237. var StandardMaterialDefines = /** @class */ (function (_super) {
  34238. __extends(StandardMaterialDefines, _super);
  34239. function StandardMaterialDefines() {
  34240. var _this = _super.call(this) || this;
  34241. _this.MAINUV1 = false;
  34242. _this.MAINUV2 = false;
  34243. _this.DIFFUSE = false;
  34244. _this.DIFFUSEDIRECTUV = 0;
  34245. _this.AMBIENT = false;
  34246. _this.AMBIENTDIRECTUV = 0;
  34247. _this.OPACITY = false;
  34248. _this.OPACITYDIRECTUV = 0;
  34249. _this.OPACITYRGB = false;
  34250. _this.REFLECTION = false;
  34251. _this.EMISSIVE = false;
  34252. _this.EMISSIVEDIRECTUV = 0;
  34253. _this.SPECULAR = false;
  34254. _this.SPECULARDIRECTUV = 0;
  34255. _this.BUMP = false;
  34256. _this.BUMPDIRECTUV = 0;
  34257. _this.PARALLAX = false;
  34258. _this.PARALLAXOCCLUSION = false;
  34259. _this.SPECULAROVERALPHA = false;
  34260. _this.CLIPPLANE = false;
  34261. _this.ALPHATEST = false;
  34262. _this.DEPTHPREPASS = false;
  34263. _this.ALPHAFROMDIFFUSE = false;
  34264. _this.POINTSIZE = false;
  34265. _this.FOG = false;
  34266. _this.SPECULARTERM = false;
  34267. _this.DIFFUSEFRESNEL = false;
  34268. _this.OPACITYFRESNEL = false;
  34269. _this.REFLECTIONFRESNEL = false;
  34270. _this.REFRACTIONFRESNEL = false;
  34271. _this.EMISSIVEFRESNEL = false;
  34272. _this.FRESNEL = false;
  34273. _this.NORMAL = false;
  34274. _this.UV1 = false;
  34275. _this.UV2 = false;
  34276. _this.VERTEXCOLOR = false;
  34277. _this.VERTEXALPHA = false;
  34278. _this.NUM_BONE_INFLUENCERS = 0;
  34279. _this.BonesPerMesh = 0;
  34280. _this.INSTANCES = false;
  34281. _this.GLOSSINESS = false;
  34282. _this.ROUGHNESS = false;
  34283. _this.EMISSIVEASILLUMINATION = false;
  34284. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34285. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34286. _this.LIGHTMAP = false;
  34287. _this.LIGHTMAPDIRECTUV = 0;
  34288. _this.USELIGHTMAPASSHADOWMAP = false;
  34289. _this.REFLECTIONMAP_3D = false;
  34290. _this.REFLECTIONMAP_SPHERICAL = false;
  34291. _this.REFLECTIONMAP_PLANAR = false;
  34292. _this.REFLECTIONMAP_CUBIC = false;
  34293. _this.REFLECTIONMAP_PROJECTION = false;
  34294. _this.REFLECTIONMAP_SKYBOX = false;
  34295. _this.REFLECTIONMAP_EXPLICIT = false;
  34296. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34297. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34298. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34299. _this.INVERTCUBICMAP = false;
  34300. _this.LOGARITHMICDEPTH = false;
  34301. _this.REFRACTION = false;
  34302. _this.REFRACTIONMAP_3D = false;
  34303. _this.REFLECTIONOVERALPHA = false;
  34304. _this.TWOSIDEDLIGHTING = false;
  34305. _this.SHADOWFLOAT = false;
  34306. _this.MORPHTARGETS = false;
  34307. _this.MORPHTARGETS_NORMAL = false;
  34308. _this.MORPHTARGETS_TANGENT = false;
  34309. _this.NUM_MORPH_INFLUENCERS = 0;
  34310. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34311. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34312. _this.IMAGEPROCESSING = false;
  34313. _this.VIGNETTE = false;
  34314. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34315. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34316. _this.TONEMAPPING = false;
  34317. _this.CONTRAST = false;
  34318. _this.COLORCURVES = false;
  34319. _this.COLORGRADING = false;
  34320. _this.COLORGRADING3D = false;
  34321. _this.SAMPLER3DGREENDEPTH = false;
  34322. _this.SAMPLER3DBGRMAP = false;
  34323. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34324. _this.EXPOSURE = false;
  34325. _this.rebuild();
  34326. return _this;
  34327. }
  34328. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34329. var modes = [
  34330. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34331. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34332. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34333. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34334. ];
  34335. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34336. var mode = modes_1[_i];
  34337. this[mode] = (mode === modeToEnable);
  34338. }
  34339. };
  34340. return StandardMaterialDefines;
  34341. }(BABYLON.MaterialDefines));
  34342. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34343. var StandardMaterial = /** @class */ (function (_super) {
  34344. __extends(StandardMaterial, _super);
  34345. function StandardMaterial(name, scene) {
  34346. var _this = _super.call(this, name, scene) || this;
  34347. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34348. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34349. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34350. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34351. _this.specularPower = 64;
  34352. _this._useAlphaFromDiffuseTexture = false;
  34353. _this._useEmissiveAsIllumination = false;
  34354. _this._linkEmissiveWithDiffuse = false;
  34355. _this._useSpecularOverAlpha = false;
  34356. _this._useReflectionOverAlpha = false;
  34357. _this._disableLighting = false;
  34358. _this._useParallax = false;
  34359. _this._useParallaxOcclusion = false;
  34360. _this.parallaxScaleBias = 0.05;
  34361. _this._roughness = 0;
  34362. _this.indexOfRefraction = 0.98;
  34363. _this.invertRefractionY = true;
  34364. _this._useLightmapAsShadowmap = false;
  34365. _this._useReflectionFresnelFromSpecular = false;
  34366. _this._useGlossinessFromSpecularMapAlpha = false;
  34367. _this._maxSimultaneousLights = 4;
  34368. /**
  34369. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34370. */
  34371. _this._invertNormalMapX = false;
  34372. /**
  34373. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34374. */
  34375. _this._invertNormalMapY = false;
  34376. /**
  34377. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34378. */
  34379. _this._twoSidedLighting = false;
  34380. _this._renderTargets = new BABYLON.SmartArray(16);
  34381. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34382. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34383. // Setup the default processing configuration to the scene.
  34384. _this._attachImageProcessingConfiguration(null);
  34385. _this.getRenderTargetTextures = function () {
  34386. _this._renderTargets.reset();
  34387. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34388. _this._renderTargets.push(_this._reflectionTexture);
  34389. }
  34390. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34391. _this._renderTargets.push(_this._refractionTexture);
  34392. }
  34393. return _this._renderTargets;
  34394. };
  34395. return _this;
  34396. }
  34397. ;
  34398. ;
  34399. ;
  34400. ;
  34401. ;
  34402. ;
  34403. ;
  34404. ;
  34405. ;
  34406. ;
  34407. ;
  34408. ;
  34409. ;
  34410. ;
  34411. ;
  34412. ;
  34413. ;
  34414. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34415. /**
  34416. * Gets the image processing configuration used either in this material.
  34417. */
  34418. get: function () {
  34419. return this._imageProcessingConfiguration;
  34420. },
  34421. /**
  34422. * Sets the Default image processing configuration used either in the this material.
  34423. *
  34424. * If sets to null, the scene one is in use.
  34425. */
  34426. set: function (value) {
  34427. this._attachImageProcessingConfiguration(value);
  34428. // Ensure the effect will be rebuilt.
  34429. this._markAllSubMeshesAsTexturesDirty();
  34430. },
  34431. enumerable: true,
  34432. configurable: true
  34433. });
  34434. /**
  34435. * Attaches a new image processing configuration to the Standard Material.
  34436. * @param configuration
  34437. */
  34438. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34439. var _this = this;
  34440. if (configuration === this._imageProcessingConfiguration) {
  34441. return;
  34442. }
  34443. // Detaches observer.
  34444. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34445. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34446. }
  34447. // Pick the scene configuration if needed.
  34448. if (!configuration) {
  34449. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34450. }
  34451. else {
  34452. this._imageProcessingConfiguration = configuration;
  34453. }
  34454. // Attaches observer.
  34455. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34456. _this._markAllSubMeshesAsImageProcessingDirty();
  34457. });
  34458. };
  34459. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34460. /**
  34461. * Gets wether the color curves effect is enabled.
  34462. */
  34463. get: function () {
  34464. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34465. },
  34466. /**
  34467. * Sets wether the color curves effect is enabled.
  34468. */
  34469. set: function (value) {
  34470. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34471. },
  34472. enumerable: true,
  34473. configurable: true
  34474. });
  34475. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34476. /**
  34477. * Gets wether the color grading effect is enabled.
  34478. */
  34479. get: function () {
  34480. return this.imageProcessingConfiguration.colorGradingEnabled;
  34481. },
  34482. /**
  34483. * Gets wether the color grading effect is enabled.
  34484. */
  34485. set: function (value) {
  34486. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34487. },
  34488. enumerable: true,
  34489. configurable: true
  34490. });
  34491. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34492. /**
  34493. * Gets wether tonemapping is enabled or not.
  34494. */
  34495. get: function () {
  34496. return this._imageProcessingConfiguration.toneMappingEnabled;
  34497. },
  34498. /**
  34499. * Sets wether tonemapping is enabled or not
  34500. */
  34501. set: function (value) {
  34502. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34503. },
  34504. enumerable: true,
  34505. configurable: true
  34506. });
  34507. ;
  34508. ;
  34509. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34510. /**
  34511. * The camera exposure used on this material.
  34512. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34513. * This corresponds to a photographic exposure.
  34514. */
  34515. get: function () {
  34516. return this._imageProcessingConfiguration.exposure;
  34517. },
  34518. /**
  34519. * The camera exposure used on this material.
  34520. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34521. * This corresponds to a photographic exposure.
  34522. */
  34523. set: function (value) {
  34524. this._imageProcessingConfiguration.exposure = value;
  34525. },
  34526. enumerable: true,
  34527. configurable: true
  34528. });
  34529. ;
  34530. ;
  34531. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34532. /**
  34533. * Gets The camera contrast used on this material.
  34534. */
  34535. get: function () {
  34536. return this._imageProcessingConfiguration.contrast;
  34537. },
  34538. /**
  34539. * Sets The camera contrast used on this material.
  34540. */
  34541. set: function (value) {
  34542. this._imageProcessingConfiguration.contrast = value;
  34543. },
  34544. enumerable: true,
  34545. configurable: true
  34546. });
  34547. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34548. /**
  34549. * Gets the Color Grading 2D Lookup Texture.
  34550. */
  34551. get: function () {
  34552. return this._imageProcessingConfiguration.colorGradingTexture;
  34553. },
  34554. /**
  34555. * Sets the Color Grading 2D Lookup Texture.
  34556. */
  34557. set: function (value) {
  34558. this._imageProcessingConfiguration.colorGradingTexture = value;
  34559. },
  34560. enumerable: true,
  34561. configurable: true
  34562. });
  34563. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34564. /**
  34565. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34566. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34567. * 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;
  34568. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34569. */
  34570. get: function () {
  34571. return this._imageProcessingConfiguration.colorCurves;
  34572. },
  34573. /**
  34574. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34575. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34576. * 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;
  34577. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34578. */
  34579. set: function (value) {
  34580. this._imageProcessingConfiguration.colorCurves = value;
  34581. },
  34582. enumerable: true,
  34583. configurable: true
  34584. });
  34585. StandardMaterial.prototype.getClassName = function () {
  34586. return "StandardMaterial";
  34587. };
  34588. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34589. get: function () {
  34590. return this._useLogarithmicDepth;
  34591. },
  34592. set: function (value) {
  34593. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34594. this._markAllSubMeshesAsMiscDirty();
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. StandardMaterial.prototype.needAlphaBlending = function () {
  34600. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34601. };
  34602. StandardMaterial.prototype.needAlphaTesting = function () {
  34603. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34604. };
  34605. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34606. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34607. };
  34608. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34609. return this._diffuseTexture;
  34610. };
  34611. /**
  34612. * Child classes can use it to update shaders
  34613. */
  34614. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34615. if (useInstances === void 0) { useInstances = false; }
  34616. if (subMesh.effect && this.isFrozen) {
  34617. if (this._wasPreviouslyReady && subMesh.effect) {
  34618. return true;
  34619. }
  34620. }
  34621. if (!subMesh._materialDefines) {
  34622. subMesh._materialDefines = new StandardMaterialDefines();
  34623. }
  34624. var scene = this.getScene();
  34625. var defines = subMesh._materialDefines;
  34626. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34627. if (defines._renderId === scene.getRenderId()) {
  34628. return true;
  34629. }
  34630. }
  34631. var engine = scene.getEngine();
  34632. // Lights
  34633. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34634. // Textures
  34635. if (defines._areTexturesDirty) {
  34636. defines._needUVs = false;
  34637. defines.MAINUV1 = false;
  34638. defines.MAINUV2 = false;
  34639. if (scene.texturesEnabled) {
  34640. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34641. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34642. return false;
  34643. }
  34644. else {
  34645. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34646. }
  34647. }
  34648. else {
  34649. defines.DIFFUSE = false;
  34650. }
  34651. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34652. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34653. return false;
  34654. }
  34655. else {
  34656. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34657. }
  34658. }
  34659. else {
  34660. defines.AMBIENT = false;
  34661. }
  34662. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34663. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34664. return false;
  34665. }
  34666. else {
  34667. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34668. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34669. }
  34670. }
  34671. else {
  34672. defines.OPACITY = false;
  34673. }
  34674. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34675. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34676. return false;
  34677. }
  34678. else {
  34679. defines._needNormals = true;
  34680. defines.REFLECTION = true;
  34681. defines.ROUGHNESS = (this._roughness > 0);
  34682. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34683. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34684. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34685. switch (this._reflectionTexture.coordinatesMode) {
  34686. case BABYLON.Texture.CUBIC_MODE:
  34687. case BABYLON.Texture.INVCUBIC_MODE:
  34688. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34689. break;
  34690. case BABYLON.Texture.EXPLICIT_MODE:
  34691. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34692. break;
  34693. case BABYLON.Texture.PLANAR_MODE:
  34694. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34695. break;
  34696. case BABYLON.Texture.PROJECTION_MODE:
  34697. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34698. break;
  34699. case BABYLON.Texture.SKYBOX_MODE:
  34700. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34701. break;
  34702. case BABYLON.Texture.SPHERICAL_MODE:
  34703. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34704. break;
  34705. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34706. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34707. break;
  34708. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34709. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34710. break;
  34711. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34712. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34713. break;
  34714. }
  34715. }
  34716. }
  34717. else {
  34718. defines.REFLECTION = false;
  34719. }
  34720. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34721. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34722. return false;
  34723. }
  34724. else {
  34725. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34726. }
  34727. }
  34728. else {
  34729. defines.EMISSIVE = false;
  34730. }
  34731. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34732. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34733. return false;
  34734. }
  34735. else {
  34736. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34737. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34738. }
  34739. }
  34740. else {
  34741. defines.LIGHTMAP = false;
  34742. }
  34743. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34744. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34745. return false;
  34746. }
  34747. else {
  34748. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34749. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34750. }
  34751. }
  34752. else {
  34753. defines.SPECULAR = false;
  34754. }
  34755. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34756. // Bump texure can not be not blocking.
  34757. if (!this._bumpTexture.isReady()) {
  34758. return false;
  34759. }
  34760. else {
  34761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34762. defines.PARALLAX = this._useParallax;
  34763. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34764. }
  34765. }
  34766. else {
  34767. defines.BUMP = false;
  34768. }
  34769. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34770. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34771. return false;
  34772. }
  34773. else {
  34774. defines._needUVs = true;
  34775. defines.REFRACTION = true;
  34776. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34777. }
  34778. }
  34779. else {
  34780. defines.REFRACTION = false;
  34781. }
  34782. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34783. }
  34784. else {
  34785. defines.DIFFUSE = false;
  34786. defines.AMBIENT = false;
  34787. defines.OPACITY = false;
  34788. defines.REFLECTION = false;
  34789. defines.EMISSIVE = false;
  34790. defines.LIGHTMAP = false;
  34791. defines.BUMP = false;
  34792. defines.REFRACTION = false;
  34793. }
  34794. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34795. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34796. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34797. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34798. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34799. }
  34800. if (defines._areImageProcessingDirty) {
  34801. if (!this._imageProcessingConfiguration.isReady()) {
  34802. return false;
  34803. }
  34804. this._imageProcessingConfiguration.prepareDefines(defines);
  34805. }
  34806. if (defines._areFresnelDirty) {
  34807. if (StandardMaterial.FresnelEnabled) {
  34808. // Fresnel
  34809. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34810. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34811. this._reflectionFresnelParameters) {
  34812. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34813. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34814. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34815. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34816. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34817. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34818. defines._needNormals = true;
  34819. defines.FRESNEL = true;
  34820. }
  34821. }
  34822. else {
  34823. defines.FRESNEL = false;
  34824. }
  34825. }
  34826. // Misc.
  34827. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34828. // Attribs
  34829. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34830. // Values that need to be evaluated on every frame
  34831. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34832. // Get correct effect
  34833. if (defines.isDirty) {
  34834. defines.markAsProcessed();
  34835. scene.resetCachedMaterial();
  34836. // Fallbacks
  34837. var fallbacks = new BABYLON.EffectFallbacks();
  34838. if (defines.REFLECTION) {
  34839. fallbacks.addFallback(0, "REFLECTION");
  34840. }
  34841. if (defines.SPECULAR) {
  34842. fallbacks.addFallback(0, "SPECULAR");
  34843. }
  34844. if (defines.BUMP) {
  34845. fallbacks.addFallback(0, "BUMP");
  34846. }
  34847. if (defines.PARALLAX) {
  34848. fallbacks.addFallback(1, "PARALLAX");
  34849. }
  34850. if (defines.PARALLAXOCCLUSION) {
  34851. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34852. }
  34853. if (defines.SPECULAROVERALPHA) {
  34854. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34855. }
  34856. if (defines.FOG) {
  34857. fallbacks.addFallback(1, "FOG");
  34858. }
  34859. if (defines.POINTSIZE) {
  34860. fallbacks.addFallback(0, "POINTSIZE");
  34861. }
  34862. if (defines.LOGARITHMICDEPTH) {
  34863. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34864. }
  34865. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34866. if (defines.SPECULARTERM) {
  34867. fallbacks.addFallback(0, "SPECULARTERM");
  34868. }
  34869. if (defines.DIFFUSEFRESNEL) {
  34870. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34871. }
  34872. if (defines.OPACITYFRESNEL) {
  34873. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34874. }
  34875. if (defines.REFLECTIONFRESNEL) {
  34876. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34877. }
  34878. if (defines.EMISSIVEFRESNEL) {
  34879. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34880. }
  34881. if (defines.FRESNEL) {
  34882. fallbacks.addFallback(4, "FRESNEL");
  34883. }
  34884. //Attributes
  34885. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34886. if (defines.NORMAL) {
  34887. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34888. }
  34889. if (defines.UV1) {
  34890. attribs.push(BABYLON.VertexBuffer.UVKind);
  34891. }
  34892. if (defines.UV2) {
  34893. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34894. }
  34895. if (defines.VERTEXCOLOR) {
  34896. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34897. }
  34898. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34899. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34900. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34901. var shaderName = "default";
  34902. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34903. "vFogInfos", "vFogColor", "pointSize",
  34904. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34905. "mBones",
  34906. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34907. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34908. "logarithmicDepthConstant", "vTangentSpaceParams"
  34909. ];
  34910. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34911. var uniformBuffers = ["Material", "Scene"];
  34912. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34913. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34914. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34915. uniformsNames: uniforms,
  34916. uniformBuffersNames: uniformBuffers,
  34917. samplers: samplers,
  34918. defines: defines,
  34919. maxSimultaneousLights: this._maxSimultaneousLights
  34920. });
  34921. if (this.customShaderNameResolve) {
  34922. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34923. }
  34924. var join = defines.toString();
  34925. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34926. attributes: attribs,
  34927. uniformsNames: uniforms,
  34928. uniformBuffersNames: uniformBuffers,
  34929. samplers: samplers,
  34930. defines: join,
  34931. fallbacks: fallbacks,
  34932. onCompiled: this.onCompiled,
  34933. onError: this.onError,
  34934. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34935. }, engine), defines);
  34936. this.buildUniformLayout();
  34937. }
  34938. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34939. return false;
  34940. }
  34941. defines._renderId = scene.getRenderId();
  34942. this._wasPreviouslyReady = true;
  34943. return true;
  34944. };
  34945. StandardMaterial.prototype.buildUniformLayout = function () {
  34946. // Order is important !
  34947. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34948. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34949. this._uniformBuffer.addUniform("opacityParts", 4);
  34950. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34951. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34952. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34953. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34954. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34955. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34956. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34957. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34958. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34959. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34960. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34961. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34962. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34963. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34964. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34965. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34966. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34967. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34968. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34969. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34970. this._uniformBuffer.addUniform("specularMatrix", 16);
  34971. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34972. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34973. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34974. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34975. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34976. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34977. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34978. this._uniformBuffer.addUniform("pointSize", 1);
  34979. this._uniformBuffer.create();
  34980. };
  34981. StandardMaterial.prototype.unbind = function () {
  34982. if (this._activeEffect) {
  34983. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34984. this._activeEffect.setTexture("reflection2DSampler", null);
  34985. }
  34986. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34987. this._activeEffect.setTexture("refraction2DSampler", null);
  34988. }
  34989. }
  34990. _super.prototype.unbind.call(this);
  34991. };
  34992. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34993. var scene = this.getScene();
  34994. var defines = subMesh._materialDefines;
  34995. if (!defines) {
  34996. return;
  34997. }
  34998. var effect = subMesh.effect;
  34999. if (!effect) {
  35000. return;
  35001. }
  35002. this._activeEffect = effect;
  35003. // Matrices
  35004. this.bindOnlyWorldMatrix(world);
  35005. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35006. // Bones
  35007. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35008. if (mustRebind) {
  35009. this._uniformBuffer.bindToEffect(effect, "Material");
  35010. this.bindViewProjection(effect);
  35011. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35012. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35013. // Fresnel
  35014. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35015. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35016. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35017. }
  35018. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35019. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35020. }
  35021. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35022. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35023. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35024. }
  35025. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35026. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35027. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35028. }
  35029. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35030. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35031. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35032. }
  35033. }
  35034. // Textures
  35035. if (scene.texturesEnabled) {
  35036. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35037. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35038. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35039. }
  35040. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35041. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35042. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35043. }
  35044. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35045. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35046. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35047. }
  35048. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35049. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35050. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35051. }
  35052. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35053. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35054. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35055. }
  35056. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35057. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35058. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35059. }
  35060. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35061. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35062. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35063. }
  35064. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35065. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35066. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35067. if (scene._mirroredCameraPosition) {
  35068. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35069. }
  35070. else {
  35071. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35072. }
  35073. }
  35074. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35075. var depth = 1.0;
  35076. if (!this._refractionTexture.isCube) {
  35077. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35078. if (this._refractionTexture.depth) {
  35079. depth = this._refractionTexture.depth;
  35080. }
  35081. }
  35082. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35083. }
  35084. }
  35085. // Point size
  35086. if (this.pointsCloud) {
  35087. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35088. }
  35089. if (defines.SPECULARTERM) {
  35090. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35091. }
  35092. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35093. // Diffuse
  35094. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35095. }
  35096. // Textures
  35097. if (scene.texturesEnabled) {
  35098. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35099. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35100. }
  35101. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35102. effect.setTexture("ambientSampler", this._ambientTexture);
  35103. }
  35104. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35105. effect.setTexture("opacitySampler", this._opacityTexture);
  35106. }
  35107. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35108. if (this._reflectionTexture.isCube) {
  35109. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35110. }
  35111. else {
  35112. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35113. }
  35114. }
  35115. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35116. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35117. }
  35118. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35119. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35120. }
  35121. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35122. effect.setTexture("specularSampler", this._specularTexture);
  35123. }
  35124. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35125. effect.setTexture("bumpSampler", this._bumpTexture);
  35126. }
  35127. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35128. var depth = 1.0;
  35129. if (this._refractionTexture.isCube) {
  35130. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35131. }
  35132. else {
  35133. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35134. }
  35135. }
  35136. }
  35137. // Clip plane
  35138. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35139. // Colors
  35140. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35141. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35142. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35143. }
  35144. if (mustRebind || !this.isFrozen) {
  35145. // Lights
  35146. if (scene.lightsEnabled && !this._disableLighting) {
  35147. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35148. }
  35149. // View
  35150. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35151. this.bindView(effect);
  35152. }
  35153. // Fog
  35154. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35155. // Morph targets
  35156. if (defines.NUM_MORPH_INFLUENCERS) {
  35157. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35158. }
  35159. // Log. depth
  35160. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35161. // image processing
  35162. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35163. this._imageProcessingConfiguration.bind(this._activeEffect);
  35164. }
  35165. }
  35166. this._uniformBuffer.update();
  35167. this._afterBind(mesh, this._activeEffect);
  35168. };
  35169. StandardMaterial.prototype.getAnimatables = function () {
  35170. var results = [];
  35171. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35172. results.push(this._diffuseTexture);
  35173. }
  35174. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35175. results.push(this._ambientTexture);
  35176. }
  35177. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35178. results.push(this._opacityTexture);
  35179. }
  35180. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35181. results.push(this._reflectionTexture);
  35182. }
  35183. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35184. results.push(this._emissiveTexture);
  35185. }
  35186. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35187. results.push(this._specularTexture);
  35188. }
  35189. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35190. results.push(this._bumpTexture);
  35191. }
  35192. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35193. results.push(this._lightmapTexture);
  35194. }
  35195. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35196. results.push(this._refractionTexture);
  35197. }
  35198. return results;
  35199. };
  35200. StandardMaterial.prototype.getActiveTextures = function () {
  35201. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35202. if (this._diffuseTexture) {
  35203. activeTextures.push(this._diffuseTexture);
  35204. }
  35205. if (this._ambientTexture) {
  35206. activeTextures.push(this._ambientTexture);
  35207. }
  35208. if (this._opacityTexture) {
  35209. activeTextures.push(this._opacityTexture);
  35210. }
  35211. if (this._reflectionTexture) {
  35212. activeTextures.push(this._reflectionTexture);
  35213. }
  35214. if (this._emissiveTexture) {
  35215. activeTextures.push(this._emissiveTexture);
  35216. }
  35217. if (this._specularTexture) {
  35218. activeTextures.push(this._specularTexture);
  35219. }
  35220. if (this._bumpTexture) {
  35221. activeTextures.push(this._bumpTexture);
  35222. }
  35223. if (this._lightmapTexture) {
  35224. activeTextures.push(this._lightmapTexture);
  35225. }
  35226. if (this._refractionTexture) {
  35227. activeTextures.push(this._refractionTexture);
  35228. }
  35229. return activeTextures;
  35230. };
  35231. StandardMaterial.prototype.hasTexture = function (texture) {
  35232. if (_super.prototype.hasTexture.call(this, texture)) {
  35233. return true;
  35234. }
  35235. if (this._diffuseTexture === texture) {
  35236. return true;
  35237. }
  35238. if (this._ambientTexture === texture) {
  35239. return true;
  35240. }
  35241. if (this._opacityTexture === texture) {
  35242. return true;
  35243. }
  35244. if (this._reflectionTexture === texture) {
  35245. return true;
  35246. }
  35247. if (this._emissiveTexture === texture) {
  35248. return true;
  35249. }
  35250. if (this._specularTexture === texture) {
  35251. return true;
  35252. }
  35253. if (this._bumpTexture === texture) {
  35254. return true;
  35255. }
  35256. if (this._lightmapTexture === texture) {
  35257. return true;
  35258. }
  35259. if (this._refractionTexture === texture) {
  35260. return true;
  35261. }
  35262. return false;
  35263. };
  35264. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35265. if (forceDisposeTextures) {
  35266. if (this._diffuseTexture) {
  35267. this._diffuseTexture.dispose();
  35268. }
  35269. if (this._ambientTexture) {
  35270. this._ambientTexture.dispose();
  35271. }
  35272. if (this._opacityTexture) {
  35273. this._opacityTexture.dispose();
  35274. }
  35275. if (this._reflectionTexture) {
  35276. this._reflectionTexture.dispose();
  35277. }
  35278. if (this._emissiveTexture) {
  35279. this._emissiveTexture.dispose();
  35280. }
  35281. if (this._specularTexture) {
  35282. this._specularTexture.dispose();
  35283. }
  35284. if (this._bumpTexture) {
  35285. this._bumpTexture.dispose();
  35286. }
  35287. if (this._lightmapTexture) {
  35288. this._lightmapTexture.dispose();
  35289. }
  35290. if (this._refractionTexture) {
  35291. this._refractionTexture.dispose();
  35292. }
  35293. }
  35294. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35295. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35296. }
  35297. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35298. };
  35299. StandardMaterial.prototype.clone = function (name) {
  35300. var _this = this;
  35301. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35302. result.name = name;
  35303. result.id = name;
  35304. return result;
  35305. };
  35306. StandardMaterial.prototype.serialize = function () {
  35307. return BABYLON.SerializationHelper.Serialize(this);
  35308. };
  35309. // Statics
  35310. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35311. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35312. };
  35313. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35314. get: function () {
  35315. return StandardMaterial._DiffuseTextureEnabled;
  35316. },
  35317. set: function (value) {
  35318. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35319. return;
  35320. }
  35321. StandardMaterial._DiffuseTextureEnabled = value;
  35322. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35323. },
  35324. enumerable: true,
  35325. configurable: true
  35326. });
  35327. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35328. get: function () {
  35329. return StandardMaterial._AmbientTextureEnabled;
  35330. },
  35331. set: function (value) {
  35332. if (StandardMaterial._AmbientTextureEnabled === value) {
  35333. return;
  35334. }
  35335. StandardMaterial._AmbientTextureEnabled = value;
  35336. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35337. },
  35338. enumerable: true,
  35339. configurable: true
  35340. });
  35341. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35342. get: function () {
  35343. return StandardMaterial._OpacityTextureEnabled;
  35344. },
  35345. set: function (value) {
  35346. if (StandardMaterial._OpacityTextureEnabled === value) {
  35347. return;
  35348. }
  35349. StandardMaterial._OpacityTextureEnabled = value;
  35350. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35351. },
  35352. enumerable: true,
  35353. configurable: true
  35354. });
  35355. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35356. get: function () {
  35357. return StandardMaterial._ReflectionTextureEnabled;
  35358. },
  35359. set: function (value) {
  35360. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35361. return;
  35362. }
  35363. StandardMaterial._ReflectionTextureEnabled = value;
  35364. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35365. },
  35366. enumerable: true,
  35367. configurable: true
  35368. });
  35369. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35370. get: function () {
  35371. return StandardMaterial._EmissiveTextureEnabled;
  35372. },
  35373. set: function (value) {
  35374. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35375. return;
  35376. }
  35377. StandardMaterial._EmissiveTextureEnabled = value;
  35378. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35379. },
  35380. enumerable: true,
  35381. configurable: true
  35382. });
  35383. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35384. get: function () {
  35385. return StandardMaterial._SpecularTextureEnabled;
  35386. },
  35387. set: function (value) {
  35388. if (StandardMaterial._SpecularTextureEnabled === value) {
  35389. return;
  35390. }
  35391. StandardMaterial._SpecularTextureEnabled = value;
  35392. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35393. },
  35394. enumerable: true,
  35395. configurable: true
  35396. });
  35397. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35398. get: function () {
  35399. return StandardMaterial._BumpTextureEnabled;
  35400. },
  35401. set: function (value) {
  35402. if (StandardMaterial._BumpTextureEnabled === value) {
  35403. return;
  35404. }
  35405. StandardMaterial._BumpTextureEnabled = value;
  35406. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35407. },
  35408. enumerable: true,
  35409. configurable: true
  35410. });
  35411. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35412. get: function () {
  35413. return StandardMaterial._LightmapTextureEnabled;
  35414. },
  35415. set: function (value) {
  35416. if (StandardMaterial._LightmapTextureEnabled === value) {
  35417. return;
  35418. }
  35419. StandardMaterial._LightmapTextureEnabled = value;
  35420. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35421. },
  35422. enumerable: true,
  35423. configurable: true
  35424. });
  35425. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35426. get: function () {
  35427. return StandardMaterial._RefractionTextureEnabled;
  35428. },
  35429. set: function (value) {
  35430. if (StandardMaterial._RefractionTextureEnabled === value) {
  35431. return;
  35432. }
  35433. StandardMaterial._RefractionTextureEnabled = value;
  35434. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35435. },
  35436. enumerable: true,
  35437. configurable: true
  35438. });
  35439. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35440. get: function () {
  35441. return StandardMaterial._ColorGradingTextureEnabled;
  35442. },
  35443. set: function (value) {
  35444. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35445. return;
  35446. }
  35447. StandardMaterial._ColorGradingTextureEnabled = value;
  35448. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35449. },
  35450. enumerable: true,
  35451. configurable: true
  35452. });
  35453. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35454. get: function () {
  35455. return StandardMaterial._FresnelEnabled;
  35456. },
  35457. set: function (value) {
  35458. if (StandardMaterial._FresnelEnabled === value) {
  35459. return;
  35460. }
  35461. StandardMaterial._FresnelEnabled = value;
  35462. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35463. },
  35464. enumerable: true,
  35465. configurable: true
  35466. });
  35467. // Flags used to enable or disable a type of texture for all Standard Materials
  35468. StandardMaterial._DiffuseTextureEnabled = true;
  35469. StandardMaterial._AmbientTextureEnabled = true;
  35470. StandardMaterial._OpacityTextureEnabled = true;
  35471. StandardMaterial._ReflectionTextureEnabled = true;
  35472. StandardMaterial._EmissiveTextureEnabled = true;
  35473. StandardMaterial._SpecularTextureEnabled = true;
  35474. StandardMaterial._BumpTextureEnabled = true;
  35475. StandardMaterial._LightmapTextureEnabled = true;
  35476. StandardMaterial._RefractionTextureEnabled = true;
  35477. StandardMaterial._ColorGradingTextureEnabled = true;
  35478. StandardMaterial._FresnelEnabled = true;
  35479. __decorate([
  35480. BABYLON.serializeAsTexture("diffuseTexture")
  35481. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35482. __decorate([
  35483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35484. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35485. __decorate([
  35486. BABYLON.serializeAsTexture("ambientTexture")
  35487. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35488. __decorate([
  35489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35490. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35491. __decorate([
  35492. BABYLON.serializeAsTexture("opacityTexture")
  35493. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35494. __decorate([
  35495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35496. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35497. __decorate([
  35498. BABYLON.serializeAsTexture("reflectionTexture")
  35499. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35500. __decorate([
  35501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35502. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35503. __decorate([
  35504. BABYLON.serializeAsTexture("emissiveTexture")
  35505. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35506. __decorate([
  35507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35508. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35509. __decorate([
  35510. BABYLON.serializeAsTexture("specularTexture")
  35511. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35512. __decorate([
  35513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35514. ], StandardMaterial.prototype, "specularTexture", void 0);
  35515. __decorate([
  35516. BABYLON.serializeAsTexture("bumpTexture")
  35517. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35518. __decorate([
  35519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35520. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35521. __decorate([
  35522. BABYLON.serializeAsTexture("lightmapTexture")
  35523. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35524. __decorate([
  35525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35526. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35527. __decorate([
  35528. BABYLON.serializeAsTexture("refractionTexture")
  35529. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35530. __decorate([
  35531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35532. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35533. __decorate([
  35534. BABYLON.serializeAsColor3("ambient")
  35535. ], StandardMaterial.prototype, "ambientColor", void 0);
  35536. __decorate([
  35537. BABYLON.serializeAsColor3("diffuse")
  35538. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35539. __decorate([
  35540. BABYLON.serializeAsColor3("specular")
  35541. ], StandardMaterial.prototype, "specularColor", void 0);
  35542. __decorate([
  35543. BABYLON.serializeAsColor3("emissive")
  35544. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35545. __decorate([
  35546. BABYLON.serialize()
  35547. ], StandardMaterial.prototype, "specularPower", void 0);
  35548. __decorate([
  35549. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35550. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35551. __decorate([
  35552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35553. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35554. __decorate([
  35555. BABYLON.serialize("useEmissiveAsIllumination")
  35556. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35557. __decorate([
  35558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35559. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35560. __decorate([
  35561. BABYLON.serialize("linkEmissiveWithDiffuse")
  35562. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35563. __decorate([
  35564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35565. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35566. __decorate([
  35567. BABYLON.serialize("useSpecularOverAlpha")
  35568. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35569. __decorate([
  35570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35571. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35572. __decorate([
  35573. BABYLON.serialize("useReflectionOverAlpha")
  35574. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35575. __decorate([
  35576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35577. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35578. __decorate([
  35579. BABYLON.serialize("disableLighting")
  35580. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35581. __decorate([
  35582. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35583. ], StandardMaterial.prototype, "disableLighting", void 0);
  35584. __decorate([
  35585. BABYLON.serialize("useParallax")
  35586. ], StandardMaterial.prototype, "_useParallax", void 0);
  35587. __decorate([
  35588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35589. ], StandardMaterial.prototype, "useParallax", void 0);
  35590. __decorate([
  35591. BABYLON.serialize("useParallaxOcclusion")
  35592. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35593. __decorate([
  35594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35595. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35596. __decorate([
  35597. BABYLON.serialize()
  35598. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35599. __decorate([
  35600. BABYLON.serialize("roughness")
  35601. ], StandardMaterial.prototype, "_roughness", void 0);
  35602. __decorate([
  35603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35604. ], StandardMaterial.prototype, "roughness", void 0);
  35605. __decorate([
  35606. BABYLON.serialize()
  35607. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35608. __decorate([
  35609. BABYLON.serialize()
  35610. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35611. __decorate([
  35612. BABYLON.serialize("useLightmapAsShadowmap")
  35613. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35614. __decorate([
  35615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35616. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35617. __decorate([
  35618. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35619. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35620. __decorate([
  35621. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35622. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35623. __decorate([
  35624. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35625. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35626. __decorate([
  35627. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35628. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35629. __decorate([
  35630. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35631. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35632. __decorate([
  35633. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35634. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35635. __decorate([
  35636. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35637. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35638. __decorate([
  35639. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35640. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35641. __decorate([
  35642. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35643. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35644. __decorate([
  35645. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35646. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35647. __decorate([
  35648. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35649. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35650. __decorate([
  35651. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35652. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35653. __decorate([
  35654. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35655. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35656. __decorate([
  35657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35658. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35659. __decorate([
  35660. BABYLON.serialize("maxSimultaneousLights")
  35661. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35662. __decorate([
  35663. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35664. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35665. __decorate([
  35666. BABYLON.serialize("invertNormalMapX")
  35667. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35668. __decorate([
  35669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35670. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35671. __decorate([
  35672. BABYLON.serialize("invertNormalMapY")
  35673. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35674. __decorate([
  35675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35676. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35677. __decorate([
  35678. BABYLON.serialize("twoSidedLighting")
  35679. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35680. __decorate([
  35681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35682. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35683. __decorate([
  35684. BABYLON.serialize()
  35685. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35686. return StandardMaterial;
  35687. }(BABYLON.PushMaterial));
  35688. BABYLON.StandardMaterial = StandardMaterial;
  35689. })(BABYLON || (BABYLON = {}));
  35690. //# sourceMappingURL=babylon.standardMaterial.js.map
  35691. var BABYLON;
  35692. (function (BABYLON) {
  35693. var PBRMaterialDefines = /** @class */ (function (_super) {
  35694. __extends(PBRMaterialDefines, _super);
  35695. function PBRMaterialDefines() {
  35696. var _this = _super.call(this) || this;
  35697. _this.PBR = true;
  35698. _this.MAINUV1 = false;
  35699. _this.MAINUV2 = false;
  35700. _this.UV1 = false;
  35701. _this.UV2 = false;
  35702. _this.ALBEDO = false;
  35703. _this.ALBEDODIRECTUV = 0;
  35704. _this.VERTEXCOLOR = false;
  35705. _this.AMBIENT = false;
  35706. _this.AMBIENTDIRECTUV = 0;
  35707. _this.AMBIENTINGRAYSCALE = false;
  35708. _this.OPACITY = false;
  35709. _this.VERTEXALPHA = false;
  35710. _this.OPACITYDIRECTUV = 0;
  35711. _this.OPACITYRGB = false;
  35712. _this.ALPHATEST = false;
  35713. _this.DEPTHPREPASS = false;
  35714. _this.ALPHABLEND = false;
  35715. _this.ALPHAFROMALBEDO = false;
  35716. _this.ALPHATESTVALUE = 0.5;
  35717. _this.SPECULAROVERALPHA = false;
  35718. _this.RADIANCEOVERALPHA = false;
  35719. _this.ALPHAFRESNEL = false;
  35720. _this.LINEARALPHAFRESNEL = false;
  35721. _this.PREMULTIPLYALPHA = false;
  35722. _this.EMISSIVE = false;
  35723. _this.EMISSIVEDIRECTUV = 0;
  35724. _this.REFLECTIVITY = false;
  35725. _this.REFLECTIVITYDIRECTUV = 0;
  35726. _this.SPECULARTERM = false;
  35727. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35728. _this.MICROSURFACEAUTOMATIC = false;
  35729. _this.LODBASEDMICROSFURACE = false;
  35730. _this.MICROSURFACEMAP = false;
  35731. _this.MICROSURFACEMAPDIRECTUV = 0;
  35732. _this.METALLICWORKFLOW = false;
  35733. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35734. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35735. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35736. _this.AOSTOREINMETALMAPRED = false;
  35737. _this.ENVIRONMENTBRDF = false;
  35738. _this.NORMAL = false;
  35739. _this.TANGENT = false;
  35740. _this.BUMP = false;
  35741. _this.BUMPDIRECTUV = 0;
  35742. _this.PARALLAX = false;
  35743. _this.PARALLAXOCCLUSION = false;
  35744. _this.NORMALXYSCALE = true;
  35745. _this.LIGHTMAP = false;
  35746. _this.LIGHTMAPDIRECTUV = 0;
  35747. _this.USELIGHTMAPASSHADOWMAP = false;
  35748. _this.REFLECTION = false;
  35749. _this.REFLECTIONMAP_3D = false;
  35750. _this.REFLECTIONMAP_SPHERICAL = false;
  35751. _this.REFLECTIONMAP_PLANAR = false;
  35752. _this.REFLECTIONMAP_CUBIC = false;
  35753. _this.REFLECTIONMAP_PROJECTION = false;
  35754. _this.REFLECTIONMAP_SKYBOX = false;
  35755. _this.REFLECTIONMAP_EXPLICIT = false;
  35756. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35757. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35758. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35759. _this.INVERTCUBICMAP = false;
  35760. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35761. _this.USESPHERICALINVERTEX = false;
  35762. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35763. _this.LODINREFLECTIONALPHA = false;
  35764. _this.GAMMAREFLECTION = false;
  35765. _this.RADIANCEOCCLUSION = false;
  35766. _this.HORIZONOCCLUSION = false;
  35767. _this.REFRACTION = false;
  35768. _this.REFRACTIONMAP_3D = false;
  35769. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35770. _this.LODINREFRACTIONALPHA = false;
  35771. _this.GAMMAREFRACTION = false;
  35772. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35773. _this.INSTANCES = false;
  35774. _this.NUM_BONE_INFLUENCERS = 0;
  35775. _this.BonesPerMesh = 0;
  35776. _this.NONUNIFORMSCALING = false;
  35777. _this.MORPHTARGETS = false;
  35778. _this.MORPHTARGETS_NORMAL = false;
  35779. _this.MORPHTARGETS_TANGENT = false;
  35780. _this.NUM_MORPH_INFLUENCERS = 0;
  35781. _this.IMAGEPROCESSING = false;
  35782. _this.VIGNETTE = false;
  35783. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35784. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35785. _this.TONEMAPPING = false;
  35786. _this.CONTRAST = false;
  35787. _this.COLORCURVES = false;
  35788. _this.COLORGRADING = false;
  35789. _this.COLORGRADING3D = false;
  35790. _this.SAMPLER3DGREENDEPTH = false;
  35791. _this.SAMPLER3DBGRMAP = false;
  35792. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35793. _this.EXPOSURE = false;
  35794. _this.USEPHYSICALLIGHTFALLOFF = false;
  35795. _this.TWOSIDEDLIGHTING = false;
  35796. _this.SHADOWFLOAT = false;
  35797. _this.CLIPPLANE = false;
  35798. _this.POINTSIZE = false;
  35799. _this.FOG = false;
  35800. _this.LOGARITHMICDEPTH = false;
  35801. _this.FORCENORMALFORWARD = false;
  35802. _this.rebuild();
  35803. return _this;
  35804. }
  35805. PBRMaterialDefines.prototype.reset = function () {
  35806. _super.prototype.reset.call(this);
  35807. this.ALPHATESTVALUE = 0.5;
  35808. this.PBR = true;
  35809. };
  35810. return PBRMaterialDefines;
  35811. }(BABYLON.MaterialDefines));
  35812. /**
  35813. * The Physically based material base class of BJS.
  35814. *
  35815. * This offers the main features of a standard PBR material.
  35816. * For more information, please refer to the documentation :
  35817. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35818. */
  35819. var PBRBaseMaterial = /** @class */ (function (_super) {
  35820. __extends(PBRBaseMaterial, _super);
  35821. /**
  35822. * Instantiates a new PBRMaterial instance.
  35823. *
  35824. * @param name The material name
  35825. * @param scene The scene the material will be use in.
  35826. */
  35827. function PBRBaseMaterial(name, scene) {
  35828. var _this = _super.call(this, name, scene) || this;
  35829. /**
  35830. * Intensity of the direct lights e.g. the four lights available in your scene.
  35831. * This impacts both the direct diffuse and specular highlights.
  35832. */
  35833. _this._directIntensity = 1.0;
  35834. /**
  35835. * Intensity of the emissive part of the material.
  35836. * This helps controlling the emissive effect without modifying the emissive color.
  35837. */
  35838. _this._emissiveIntensity = 1.0;
  35839. /**
  35840. * Intensity of the environment e.g. how much the environment will light the object
  35841. * either through harmonics for rough material or through the refelction for shiny ones.
  35842. */
  35843. _this._environmentIntensity = 1.0;
  35844. /**
  35845. * This is a special control allowing the reduction of the specular highlights coming from the
  35846. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35847. */
  35848. _this._specularIntensity = 1.0;
  35849. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35850. /**
  35851. * Debug Control allowing disabling the bump map on this material.
  35852. */
  35853. _this._disableBumpMap = false;
  35854. /**
  35855. * AKA Occlusion Texture Intensity in other nomenclature.
  35856. */
  35857. _this._ambientTextureStrength = 1.0;
  35858. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35859. /**
  35860. * AKA Diffuse Color in other nomenclature.
  35861. */
  35862. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35863. /**
  35864. * AKA Specular Color in other nomenclature.
  35865. */
  35866. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35867. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35868. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35869. /**
  35870. * AKA Glossiness in other nomenclature.
  35871. */
  35872. _this._microSurface = 0.9;
  35873. /**
  35874. * source material index of refraction (IOR)' / 'destination material IOR.
  35875. */
  35876. _this._indexOfRefraction = 0.66;
  35877. /**
  35878. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35879. */
  35880. _this._invertRefractionY = false;
  35881. /**
  35882. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35883. * Materials half opaque for instance using refraction could benefit from this control.
  35884. */
  35885. _this._linkRefractionWithTransparency = false;
  35886. _this._useLightmapAsShadowmap = false;
  35887. /**
  35888. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  35889. * makes the reflect vector face the model (under horizon).
  35890. */
  35891. _this._useHorizonOcclusion = true;
  35892. /**
  35893. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  35894. * too much the area relying on ambient texture to define their ambient occlusion.
  35895. */
  35896. _this._useRadianceOcclusion = true;
  35897. /**
  35898. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35899. */
  35900. _this._useAlphaFromAlbedoTexture = false;
  35901. /**
  35902. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35903. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35904. */
  35905. _this._useSpecularOverAlpha = true;
  35906. /**
  35907. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35908. */
  35909. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35910. /**
  35911. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35912. */
  35913. _this._useRoughnessFromMetallicTextureAlpha = true;
  35914. /**
  35915. * Specifies if the metallic texture contains the roughness information in its green channel.
  35916. */
  35917. _this._useRoughnessFromMetallicTextureGreen = false;
  35918. /**
  35919. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35920. */
  35921. _this._useMetallnessFromMetallicTextureBlue = false;
  35922. /**
  35923. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35924. */
  35925. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35926. /**
  35927. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35928. */
  35929. _this._useAmbientInGrayScale = false;
  35930. /**
  35931. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35932. * The material will try to infer what glossiness each pixel should be.
  35933. */
  35934. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35935. /**
  35936. * BJS is using an harcoded light falloff based on a manually sets up range.
  35937. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35938. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35939. */
  35940. _this._usePhysicalLightFalloff = true;
  35941. /**
  35942. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35943. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35944. */
  35945. _this._useRadianceOverAlpha = true;
  35946. /**
  35947. * Allows using the bump map in parallax mode.
  35948. */
  35949. _this._useParallax = false;
  35950. /**
  35951. * Allows using the bump map in parallax occlusion mode.
  35952. */
  35953. _this._useParallaxOcclusion = false;
  35954. /**
  35955. * Controls the scale bias of the parallax mode.
  35956. */
  35957. _this._parallaxScaleBias = 0.05;
  35958. /**
  35959. * If sets to true, disables all the lights affecting the material.
  35960. */
  35961. _this._disableLighting = false;
  35962. /**
  35963. * Number of Simultaneous lights allowed on the material.
  35964. */
  35965. _this._maxSimultaneousLights = 4;
  35966. /**
  35967. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35968. */
  35969. _this._invertNormalMapX = false;
  35970. /**
  35971. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35972. */
  35973. _this._invertNormalMapY = false;
  35974. /**
  35975. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35976. */
  35977. _this._twoSidedLighting = false;
  35978. /**
  35979. * Defines the alpha limits in alpha test mode.
  35980. */
  35981. _this._alphaCutOff = 0.4;
  35982. /**
  35983. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35984. */
  35985. _this._forceAlphaTest = false;
  35986. /**
  35987. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35988. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  35989. */
  35990. _this._useAlphaFresnel = false;
  35991. /**
  35992. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35993. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  35994. */
  35995. _this._useLinearAlphaFresnel = false;
  35996. /**
  35997. * The transparency mode of the material.
  35998. */
  35999. _this._transparencyMode = null;
  36000. /**
  36001. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36002. * from cos thetav and roughness:
  36003. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36004. */
  36005. _this._environmentBRDFTexture = null;
  36006. /**
  36007. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36008. */
  36009. _this._forceIrradianceInFragment = false;
  36010. /**
  36011. * Force normal to face away from face.
  36012. */
  36013. _this._forceNormalForward = false;
  36014. _this._renderTargets = new BABYLON.SmartArray(16);
  36015. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36016. // Setup the default processing configuration to the scene.
  36017. _this._attachImageProcessingConfiguration(null);
  36018. _this.getRenderTargetTextures = function () {
  36019. _this._renderTargets.reset();
  36020. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36021. _this._renderTargets.push(_this._reflectionTexture);
  36022. }
  36023. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36024. _this._renderTargets.push(_this._refractionTexture);
  36025. }
  36026. return _this._renderTargets;
  36027. };
  36028. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36029. return _this;
  36030. }
  36031. /**
  36032. * Attaches a new image processing configuration to the PBR Material.
  36033. * @param configuration
  36034. */
  36035. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36036. var _this = this;
  36037. if (configuration === this._imageProcessingConfiguration) {
  36038. return;
  36039. }
  36040. // Detaches observer.
  36041. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36042. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36043. }
  36044. // Pick the scene configuration if needed.
  36045. if (!configuration) {
  36046. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36047. }
  36048. else {
  36049. this._imageProcessingConfiguration = configuration;
  36050. }
  36051. // Attaches observer.
  36052. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36053. _this._markAllSubMeshesAsImageProcessingDirty();
  36054. });
  36055. };
  36056. PBRBaseMaterial.prototype.getClassName = function () {
  36057. return "PBRBaseMaterial";
  36058. };
  36059. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36060. get: function () {
  36061. return this._useLogarithmicDepth;
  36062. },
  36063. set: function (value) {
  36064. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36065. },
  36066. enumerable: true,
  36067. configurable: true
  36068. });
  36069. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36070. /**
  36071. * Gets the current transparency mode.
  36072. */
  36073. get: function () {
  36074. return this._transparencyMode;
  36075. },
  36076. /**
  36077. * Sets the transparency mode of the material.
  36078. */
  36079. set: function (value) {
  36080. if (this._transparencyMode === value) {
  36081. return;
  36082. }
  36083. this._transparencyMode = value;
  36084. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36085. this._markAllSubMeshesAsTexturesDirty();
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36091. /**
  36092. * Returns true if alpha blending should be disabled.
  36093. */
  36094. get: function () {
  36095. return (this._linkRefractionWithTransparency ||
  36096. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36097. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36098. },
  36099. enumerable: true,
  36100. configurable: true
  36101. });
  36102. /**
  36103. * Specifies whether or not this material should be rendered in alpha blend mode.
  36104. */
  36105. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36106. if (this._disableAlphaBlending) {
  36107. return false;
  36108. }
  36109. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36110. };
  36111. /**
  36112. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36113. */
  36114. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36115. if (this._disableAlphaBlending) {
  36116. return false;
  36117. }
  36118. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36119. };
  36120. /**
  36121. * Specifies whether or not this material should be rendered in alpha test mode.
  36122. */
  36123. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36124. if (this._forceAlphaTest) {
  36125. return true;
  36126. }
  36127. if (this._linkRefractionWithTransparency) {
  36128. return false;
  36129. }
  36130. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36131. };
  36132. /**
  36133. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36134. */
  36135. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36136. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36137. };
  36138. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36139. return this._albedoTexture;
  36140. };
  36141. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36142. var _this = this;
  36143. if (subMesh.effect && this.isFrozen) {
  36144. if (this._wasPreviouslyReady) {
  36145. return true;
  36146. }
  36147. }
  36148. if (!subMesh._materialDefines) {
  36149. subMesh._materialDefines = new PBRMaterialDefines();
  36150. }
  36151. var scene = this.getScene();
  36152. var defines = subMesh._materialDefines;
  36153. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36154. if (defines._renderId === scene.getRenderId()) {
  36155. return true;
  36156. }
  36157. }
  36158. var engine = scene.getEngine();
  36159. // Lights
  36160. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36161. defines._needNormals = true;
  36162. // Textures
  36163. if (defines._areTexturesDirty) {
  36164. defines._needUVs = false;
  36165. if (scene.texturesEnabled) {
  36166. if (scene.getEngine().getCaps().textureLOD) {
  36167. defines.LODBASEDMICROSFURACE = true;
  36168. }
  36169. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36170. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36171. return false;
  36172. }
  36173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36174. }
  36175. else {
  36176. defines.ALBEDO = false;
  36177. }
  36178. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36179. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36180. return false;
  36181. }
  36182. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36183. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36184. }
  36185. else {
  36186. defines.AMBIENT = false;
  36187. }
  36188. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36189. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36190. return false;
  36191. }
  36192. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36193. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36194. }
  36195. else {
  36196. defines.OPACITY = false;
  36197. }
  36198. var reflectionTexture = this._getReflectionTexture();
  36199. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36200. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36201. return false;
  36202. }
  36203. defines.REFLECTION = true;
  36204. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36205. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36206. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36207. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36208. defines.INVERTCUBICMAP = true;
  36209. }
  36210. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36211. switch (reflectionTexture.coordinatesMode) {
  36212. case BABYLON.Texture.CUBIC_MODE:
  36213. case BABYLON.Texture.INVCUBIC_MODE:
  36214. defines.REFLECTIONMAP_CUBIC = true;
  36215. break;
  36216. case BABYLON.Texture.EXPLICIT_MODE:
  36217. defines.REFLECTIONMAP_EXPLICIT = true;
  36218. break;
  36219. case BABYLON.Texture.PLANAR_MODE:
  36220. defines.REFLECTIONMAP_PLANAR = true;
  36221. break;
  36222. case BABYLON.Texture.PROJECTION_MODE:
  36223. defines.REFLECTIONMAP_PROJECTION = true;
  36224. break;
  36225. case BABYLON.Texture.SKYBOX_MODE:
  36226. defines.REFLECTIONMAP_SKYBOX = true;
  36227. break;
  36228. case BABYLON.Texture.SPHERICAL_MODE:
  36229. defines.REFLECTIONMAP_SPHERICAL = true;
  36230. break;
  36231. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36232. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36233. break;
  36234. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36235. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36236. break;
  36237. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36238. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36239. break;
  36240. }
  36241. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36242. if (reflectionTexture.sphericalPolynomial) {
  36243. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36244. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36245. defines.USESPHERICALINVERTEX = false;
  36246. }
  36247. else {
  36248. defines.USESPHERICALINVERTEX = true;
  36249. }
  36250. }
  36251. }
  36252. }
  36253. else {
  36254. defines.REFLECTION = false;
  36255. defines.REFLECTIONMAP_3D = false;
  36256. defines.REFLECTIONMAP_SPHERICAL = false;
  36257. defines.REFLECTIONMAP_PLANAR = false;
  36258. defines.REFLECTIONMAP_CUBIC = false;
  36259. defines.REFLECTIONMAP_PROJECTION = false;
  36260. defines.REFLECTIONMAP_SKYBOX = false;
  36261. defines.REFLECTIONMAP_EXPLICIT = false;
  36262. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36263. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36264. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36265. defines.INVERTCUBICMAP = false;
  36266. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36267. defines.USESPHERICALINVERTEX = false;
  36268. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36269. defines.LODINREFLECTIONALPHA = false;
  36270. defines.GAMMAREFLECTION = false;
  36271. }
  36272. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36273. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36274. return false;
  36275. }
  36276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36277. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36278. }
  36279. else {
  36280. defines.LIGHTMAP = false;
  36281. }
  36282. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36283. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36284. return false;
  36285. }
  36286. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36287. }
  36288. else {
  36289. defines.EMISSIVE = false;
  36290. }
  36291. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36292. if (this._metallicTexture) {
  36293. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36294. return false;
  36295. }
  36296. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36297. defines.METALLICWORKFLOW = true;
  36298. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36299. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36300. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36301. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36302. }
  36303. else if (this._reflectivityTexture) {
  36304. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36305. return false;
  36306. }
  36307. defines.METALLICWORKFLOW = false;
  36308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36309. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36310. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36311. }
  36312. else {
  36313. defines.METALLICWORKFLOW = false;
  36314. defines.REFLECTIVITY = false;
  36315. }
  36316. if (this._microSurfaceTexture) {
  36317. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36318. return false;
  36319. }
  36320. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36321. }
  36322. else {
  36323. defines.MICROSURFACEMAP = false;
  36324. }
  36325. }
  36326. else {
  36327. defines.REFLECTIVITY = false;
  36328. defines.MICROSURFACEMAP = false;
  36329. }
  36330. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36331. // Bump texure can not be none blocking.
  36332. if (!this._bumpTexture.isReady()) {
  36333. return false;
  36334. }
  36335. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36336. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36337. defines.PARALLAX = true;
  36338. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36339. }
  36340. else {
  36341. defines.PARALLAX = false;
  36342. }
  36343. }
  36344. else {
  36345. defines.BUMP = false;
  36346. }
  36347. var refractionTexture = this._getRefractionTexture();
  36348. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36349. if (!refractionTexture.isReadyOrNotBlocking()) {
  36350. return false;
  36351. }
  36352. defines.REFRACTION = true;
  36353. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36354. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36355. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36356. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36357. if (this._linkRefractionWithTransparency) {
  36358. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36359. }
  36360. }
  36361. else {
  36362. defines.REFRACTION = false;
  36363. }
  36364. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36365. // This is blocking.
  36366. if (!this._environmentBRDFTexture.isReady()) {
  36367. return false;
  36368. }
  36369. defines.ENVIRONMENTBRDF = true;
  36370. }
  36371. else {
  36372. defines.ENVIRONMENTBRDF = false;
  36373. }
  36374. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36375. defines.ALPHAFROMALBEDO = true;
  36376. }
  36377. else {
  36378. defines.ALPHAFROMALBEDO = false;
  36379. }
  36380. }
  36381. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36382. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36383. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36384. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36385. defines.METALLICWORKFLOW = true;
  36386. }
  36387. else {
  36388. defines.METALLICWORKFLOW = false;
  36389. }
  36390. if (!this.backFaceCulling && this._twoSidedLighting) {
  36391. defines.TWOSIDEDLIGHTING = true;
  36392. }
  36393. else {
  36394. defines.TWOSIDEDLIGHTING = false;
  36395. }
  36396. defines.ALPHATESTVALUE = this._alphaCutOff;
  36397. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36398. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36399. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36400. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36401. }
  36402. if (defines._areImageProcessingDirty) {
  36403. if (!this._imageProcessingConfiguration.isReady()) {
  36404. return false;
  36405. }
  36406. this._imageProcessingConfiguration.prepareDefines(defines);
  36407. }
  36408. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36409. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36410. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36411. // Misc.
  36412. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36413. // Values that need to be evaluated on every frame
  36414. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36415. // Attribs
  36416. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36417. var bufferMesh = null;
  36418. if (mesh instanceof BABYLON.InstancedMesh) {
  36419. bufferMesh = mesh.sourceMesh;
  36420. }
  36421. else if (mesh instanceof BABYLON.Mesh) {
  36422. bufferMesh = mesh;
  36423. }
  36424. if (bufferMesh) {
  36425. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36426. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36427. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36428. var normals = normalVertexBuffer.getData();
  36429. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36430. var strideSize = normalVertexBuffer.getStrideSize();
  36431. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36432. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36433. defines.NORMAL = false;
  36434. }
  36435. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36436. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36437. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36438. var tangents = tangentVertexBuffer.getData();
  36439. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36440. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36441. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36442. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36443. defines.TANGENT = false;
  36444. }
  36445. }
  36446. }
  36447. else {
  36448. if (!scene.getEngine().getCaps().standardDerivatives) {
  36449. bufferMesh.createNormals(true);
  36450. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36451. }
  36452. }
  36453. }
  36454. }
  36455. // Get correct effect
  36456. if (defines.isDirty) {
  36457. defines.markAsProcessed();
  36458. scene.resetCachedMaterial();
  36459. // Fallbacks
  36460. var fallbacks = new BABYLON.EffectFallbacks();
  36461. var fallbackRank = 0;
  36462. if (defines.USESPHERICALINVERTEX) {
  36463. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36464. }
  36465. if (defines.FOG) {
  36466. fallbacks.addFallback(fallbackRank, "FOG");
  36467. }
  36468. if (defines.POINTSIZE) {
  36469. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36470. }
  36471. if (defines.LOGARITHMICDEPTH) {
  36472. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36473. }
  36474. if (defines.PARALLAX) {
  36475. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36476. }
  36477. if (defines.PARALLAXOCCLUSION) {
  36478. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36479. }
  36480. if (defines.ENVIRONMENTBRDF) {
  36481. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36482. }
  36483. if (defines.TANGENT) {
  36484. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36485. }
  36486. if (defines.BUMP) {
  36487. fallbacks.addFallback(fallbackRank++, "BUMP");
  36488. }
  36489. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36490. if (defines.SPECULARTERM) {
  36491. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36492. }
  36493. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36494. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36495. }
  36496. if (defines.LIGHTMAP) {
  36497. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36498. }
  36499. if (defines.NORMAL) {
  36500. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36501. }
  36502. if (defines.AMBIENT) {
  36503. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36504. }
  36505. if (defines.EMISSIVE) {
  36506. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36507. }
  36508. if (defines.VERTEXCOLOR) {
  36509. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36510. }
  36511. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36512. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36513. }
  36514. if (defines.MORPHTARGETS) {
  36515. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36516. }
  36517. //Attributes
  36518. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36519. if (defines.NORMAL) {
  36520. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36521. }
  36522. if (defines.TANGENT) {
  36523. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36524. }
  36525. if (defines.UV1) {
  36526. attribs.push(BABYLON.VertexBuffer.UVKind);
  36527. }
  36528. if (defines.UV2) {
  36529. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36530. }
  36531. if (defines.VERTEXCOLOR) {
  36532. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36533. }
  36534. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36535. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36536. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36537. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36538. "vFogInfos", "vFogColor", "pointSize",
  36539. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36540. "mBones",
  36541. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36542. "vLightingIntensity",
  36543. "logarithmicDepthConstant",
  36544. "vSphericalX", "vSphericalY", "vSphericalZ",
  36545. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36546. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36547. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36548. "vTangentSpaceParams"
  36549. ];
  36550. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36551. "bumpSampler", "lightmapSampler", "opacitySampler",
  36552. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36553. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36554. "microSurfaceSampler", "environmentBrdfSampler"];
  36555. var uniformBuffers = ["Material", "Scene"];
  36556. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36557. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36558. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36559. uniformsNames: uniforms,
  36560. uniformBuffersNames: uniformBuffers,
  36561. samplers: samplers,
  36562. defines: defines,
  36563. maxSimultaneousLights: this._maxSimultaneousLights
  36564. });
  36565. var onCompiled = function (effect) {
  36566. if (_this.onCompiled) {
  36567. _this.onCompiled(effect);
  36568. }
  36569. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36570. };
  36571. var join = defines.toString();
  36572. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36573. attributes: attribs,
  36574. uniformsNames: uniforms,
  36575. uniformBuffersNames: uniformBuffers,
  36576. samplers: samplers,
  36577. defines: join,
  36578. fallbacks: fallbacks,
  36579. onCompiled: onCompiled,
  36580. onError: this.onError,
  36581. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36582. }, engine), defines);
  36583. this.buildUniformLayout();
  36584. }
  36585. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36586. return false;
  36587. }
  36588. defines._renderId = scene.getRenderId();
  36589. this._wasPreviouslyReady = true;
  36590. return true;
  36591. };
  36592. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36593. // Order is important !
  36594. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36595. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36596. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36597. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36598. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36599. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36600. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36601. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36602. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36603. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36604. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36605. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36606. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36607. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36608. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36609. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36610. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36611. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36612. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36613. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36614. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36615. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36616. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36617. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36618. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36619. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36620. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36621. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36622. this._uniformBuffer.addUniform("pointSize", 1);
  36623. this._uniformBuffer.create();
  36624. };
  36625. PBRBaseMaterial.prototype.unbind = function () {
  36626. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36627. this._uniformBuffer.setTexture("reflectionSampler", null);
  36628. }
  36629. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36630. this._uniformBuffer.setTexture("refractionSampler", null);
  36631. }
  36632. _super.prototype.unbind.call(this);
  36633. };
  36634. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36635. this._activeEffect.setMatrix("world", world);
  36636. };
  36637. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36638. var scene = this.getScene();
  36639. var defines = subMesh._materialDefines;
  36640. if (!defines) {
  36641. return;
  36642. }
  36643. var effect = subMesh.effect;
  36644. if (!effect) {
  36645. return;
  36646. }
  36647. this._activeEffect = effect;
  36648. // Matrices
  36649. this.bindOnlyWorldMatrix(world);
  36650. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36651. // Bones
  36652. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36653. var reflectionTexture = null;
  36654. if (mustRebind) {
  36655. this._uniformBuffer.bindToEffect(effect, "Material");
  36656. this.bindViewProjection(effect);
  36657. reflectionTexture = this._getReflectionTexture();
  36658. var refractionTexture = this._getRefractionTexture();
  36659. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36660. // Texture uniforms
  36661. if (scene.texturesEnabled) {
  36662. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36663. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36664. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36665. }
  36666. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36667. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36668. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36669. }
  36670. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36671. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36672. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36673. }
  36674. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36675. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36676. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36677. var polynomials = reflectionTexture.sphericalPolynomial;
  36678. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36679. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36680. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36681. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36682. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36683. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36684. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36685. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36686. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36687. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36688. }
  36689. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36690. }
  36691. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36692. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36693. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36694. }
  36695. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36696. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36697. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36698. }
  36699. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36700. if (this._metallicTexture) {
  36701. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36702. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36703. }
  36704. else if (this._reflectivityTexture) {
  36705. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36706. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36707. }
  36708. if (this._microSurfaceTexture) {
  36709. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36710. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36711. }
  36712. }
  36713. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36714. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36715. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36716. if (scene._mirroredCameraPosition) {
  36717. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36718. }
  36719. else {
  36720. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36721. }
  36722. }
  36723. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36724. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36725. var depth = 1.0;
  36726. if (!refractionTexture.isCube) {
  36727. if (refractionTexture.depth) {
  36728. depth = refractionTexture.depth;
  36729. }
  36730. }
  36731. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36732. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36733. }
  36734. }
  36735. // Point size
  36736. if (this.pointsCloud) {
  36737. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36738. }
  36739. // Colors
  36740. if (defines.METALLICWORKFLOW) {
  36741. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36742. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36743. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36744. }
  36745. else {
  36746. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36747. }
  36748. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36749. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36750. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36751. // Misc
  36752. this._lightingInfos.x = this._directIntensity;
  36753. this._lightingInfos.y = this._emissiveIntensity;
  36754. this._lightingInfos.z = this._environmentIntensity;
  36755. this._lightingInfos.w = this._specularIntensity;
  36756. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36757. }
  36758. // Textures
  36759. if (scene.texturesEnabled) {
  36760. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36761. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36762. }
  36763. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36764. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36765. }
  36766. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36767. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36768. }
  36769. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36770. if (defines.LODBASEDMICROSFURACE) {
  36771. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36772. }
  36773. else {
  36774. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36775. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36776. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36777. }
  36778. }
  36779. if (defines.ENVIRONMENTBRDF) {
  36780. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36781. }
  36782. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36783. if (defines.LODBASEDMICROSFURACE) {
  36784. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36785. }
  36786. else {
  36787. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36788. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36789. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36790. }
  36791. }
  36792. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36793. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36794. }
  36795. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36796. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36797. }
  36798. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36799. if (this._metallicTexture) {
  36800. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36801. }
  36802. else if (this._reflectivityTexture) {
  36803. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36804. }
  36805. if (this._microSurfaceTexture) {
  36806. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36807. }
  36808. }
  36809. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36810. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36811. }
  36812. }
  36813. // Clip plane
  36814. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36815. // Colors
  36816. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36817. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36818. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36819. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36820. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36821. }
  36822. if (mustRebind || !this.isFrozen) {
  36823. // Lights
  36824. if (scene.lightsEnabled && !this._disableLighting) {
  36825. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36826. }
  36827. // View
  36828. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36829. this.bindView(effect);
  36830. }
  36831. // Fog
  36832. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36833. // Morph targets
  36834. if (defines.NUM_MORPH_INFLUENCERS) {
  36835. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36836. }
  36837. // image processing
  36838. this._imageProcessingConfiguration.bind(this._activeEffect);
  36839. // Log. depth
  36840. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36841. }
  36842. this._uniformBuffer.update();
  36843. this._afterBind(mesh);
  36844. };
  36845. PBRBaseMaterial.prototype.getAnimatables = function () {
  36846. var results = [];
  36847. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36848. results.push(this._albedoTexture);
  36849. }
  36850. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36851. results.push(this._ambientTexture);
  36852. }
  36853. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36854. results.push(this._opacityTexture);
  36855. }
  36856. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36857. results.push(this._reflectionTexture);
  36858. }
  36859. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36860. results.push(this._emissiveTexture);
  36861. }
  36862. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36863. results.push(this._metallicTexture);
  36864. }
  36865. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36866. results.push(this._reflectivityTexture);
  36867. }
  36868. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36869. results.push(this._bumpTexture);
  36870. }
  36871. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36872. results.push(this._lightmapTexture);
  36873. }
  36874. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36875. results.push(this._refractionTexture);
  36876. }
  36877. return results;
  36878. };
  36879. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36880. if (this._reflectionTexture) {
  36881. return this._reflectionTexture;
  36882. }
  36883. return this.getScene().environmentTexture;
  36884. };
  36885. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36886. if (this._refractionTexture) {
  36887. return this._refractionTexture;
  36888. }
  36889. if (this._linkRefractionWithTransparency) {
  36890. return this.getScene().environmentTexture;
  36891. }
  36892. return null;
  36893. };
  36894. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36895. if (forceDisposeTextures) {
  36896. if (this._albedoTexture) {
  36897. this._albedoTexture.dispose();
  36898. }
  36899. if (this._ambientTexture) {
  36900. this._ambientTexture.dispose();
  36901. }
  36902. if (this._opacityTexture) {
  36903. this._opacityTexture.dispose();
  36904. }
  36905. if (this._reflectionTexture) {
  36906. this._reflectionTexture.dispose();
  36907. }
  36908. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36909. this._environmentBRDFTexture.dispose();
  36910. }
  36911. if (this._emissiveTexture) {
  36912. this._emissiveTexture.dispose();
  36913. }
  36914. if (this._metallicTexture) {
  36915. this._metallicTexture.dispose();
  36916. }
  36917. if (this._reflectivityTexture) {
  36918. this._reflectivityTexture.dispose();
  36919. }
  36920. if (this._bumpTexture) {
  36921. this._bumpTexture.dispose();
  36922. }
  36923. if (this._lightmapTexture) {
  36924. this._lightmapTexture.dispose();
  36925. }
  36926. if (this._refractionTexture) {
  36927. this._refractionTexture.dispose();
  36928. }
  36929. }
  36930. this._renderTargets.dispose();
  36931. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36932. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36933. }
  36934. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36935. };
  36936. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36937. __decorate([
  36938. BABYLON.serializeAsImageProcessingConfiguration()
  36939. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36940. __decorate([
  36941. BABYLON.serialize()
  36942. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36943. __decorate([
  36944. BABYLON.serialize()
  36945. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36946. return PBRBaseMaterial;
  36947. }(BABYLON.PushMaterial));
  36948. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36949. })(BABYLON || (BABYLON = {}));
  36950. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36951. var BABYLON;
  36952. (function (BABYLON) {
  36953. var Internals;
  36954. (function (Internals) {
  36955. /**
  36956. * The Physically based simple base material of BJS.
  36957. *
  36958. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36959. * It is used as the base class for both the specGloss and metalRough conventions.
  36960. */
  36961. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36962. __extends(PBRBaseSimpleMaterial, _super);
  36963. /**
  36964. * Instantiates a new PBRMaterial instance.
  36965. *
  36966. * @param name The material name
  36967. * @param scene The scene the material will be use in.
  36968. */
  36969. function PBRBaseSimpleMaterial(name, scene) {
  36970. var _this = _super.call(this, name, scene) || this;
  36971. /**
  36972. * Number of Simultaneous lights allowed on the material.
  36973. */
  36974. _this.maxSimultaneousLights = 4;
  36975. /**
  36976. * If sets to true, disables all the lights affecting the material.
  36977. */
  36978. _this.disableLighting = false;
  36979. /**
  36980. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36981. */
  36982. _this.invertNormalMapX = false;
  36983. /**
  36984. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36985. */
  36986. _this.invertNormalMapY = false;
  36987. /**
  36988. * Emissivie color used to self-illuminate the model.
  36989. */
  36990. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36991. /**
  36992. * Occlusion Channel Strenght.
  36993. */
  36994. _this.occlusionStrength = 1.0;
  36995. _this.useLightmapAsShadowmap = false;
  36996. _this._useAlphaFromAlbedoTexture = true;
  36997. _this._useAmbientInGrayScale = true;
  36998. return _this;
  36999. }
  37000. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37001. /**
  37002. * Gets the current double sided mode.
  37003. */
  37004. get: function () {
  37005. return this._twoSidedLighting;
  37006. },
  37007. /**
  37008. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37009. */
  37010. set: function (value) {
  37011. if (this._twoSidedLighting === value) {
  37012. return;
  37013. }
  37014. this._twoSidedLighting = value;
  37015. this.backFaceCulling = !value;
  37016. this._markAllSubMeshesAsTexturesDirty();
  37017. },
  37018. enumerable: true,
  37019. configurable: true
  37020. });
  37021. /**
  37022. * Return the active textures of the material.
  37023. */
  37024. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37025. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37026. if (this.environmentTexture) {
  37027. activeTextures.push(this.environmentTexture);
  37028. }
  37029. if (this.normalTexture) {
  37030. activeTextures.push(this.normalTexture);
  37031. }
  37032. if (this.emissiveTexture) {
  37033. activeTextures.push(this.emissiveTexture);
  37034. }
  37035. if (this.occlusionTexture) {
  37036. activeTextures.push(this.occlusionTexture);
  37037. }
  37038. if (this.lightmapTexture) {
  37039. activeTextures.push(this.lightmapTexture);
  37040. }
  37041. return activeTextures;
  37042. };
  37043. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37044. if (_super.prototype.hasTexture.call(this, texture)) {
  37045. return true;
  37046. }
  37047. if (this.lightmapTexture === texture) {
  37048. return true;
  37049. }
  37050. return false;
  37051. };
  37052. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37053. return "PBRBaseSimpleMaterial";
  37054. };
  37055. __decorate([
  37056. BABYLON.serialize(),
  37057. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37058. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37059. __decorate([
  37060. BABYLON.serialize(),
  37061. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37062. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37063. __decorate([
  37064. BABYLON.serializeAsTexture(),
  37065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37066. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37067. __decorate([
  37068. BABYLON.serialize(),
  37069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37070. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37071. __decorate([
  37072. BABYLON.serialize(),
  37073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37074. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37075. __decorate([
  37076. BABYLON.serializeAsTexture(),
  37077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37078. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37079. __decorate([
  37080. BABYLON.serializeAsColor3("emissive"),
  37081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37082. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37083. __decorate([
  37084. BABYLON.serializeAsTexture(),
  37085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37086. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37087. __decorate([
  37088. BABYLON.serialize(),
  37089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37090. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37091. __decorate([
  37092. BABYLON.serializeAsTexture(),
  37093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37094. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37095. __decorate([
  37096. BABYLON.serialize(),
  37097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37098. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37099. __decorate([
  37100. BABYLON.serialize()
  37101. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37102. __decorate([
  37103. BABYLON.serializeAsTexture(),
  37104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37105. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37106. __decorate([
  37107. BABYLON.serialize(),
  37108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37109. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37110. return PBRBaseSimpleMaterial;
  37111. }(BABYLON.PBRBaseMaterial));
  37112. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37113. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37114. })(BABYLON || (BABYLON = {}));
  37115. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37116. var BABYLON;
  37117. (function (BABYLON) {
  37118. /**
  37119. * The Physically based material of BJS.
  37120. *
  37121. * This offers the main features of a standard PBR material.
  37122. * For more information, please refer to the documentation :
  37123. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37124. */
  37125. var PBRMaterial = /** @class */ (function (_super) {
  37126. __extends(PBRMaterial, _super);
  37127. /**
  37128. * Instantiates a new PBRMaterial instance.
  37129. *
  37130. * @param name The material name
  37131. * @param scene The scene the material will be use in.
  37132. */
  37133. function PBRMaterial(name, scene) {
  37134. var _this = _super.call(this, name, scene) || this;
  37135. /**
  37136. * Intensity of the direct lights e.g. the four lights available in your scene.
  37137. * This impacts both the direct diffuse and specular highlights.
  37138. */
  37139. _this.directIntensity = 1.0;
  37140. /**
  37141. * Intensity of the emissive part of the material.
  37142. * This helps controlling the emissive effect without modifying the emissive color.
  37143. */
  37144. _this.emissiveIntensity = 1.0;
  37145. /**
  37146. * Intensity of the environment e.g. how much the environment will light the object
  37147. * either through harmonics for rough material or through the refelction for shiny ones.
  37148. */
  37149. _this.environmentIntensity = 1.0;
  37150. /**
  37151. * This is a special control allowing the reduction of the specular highlights coming from the
  37152. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37153. */
  37154. _this.specularIntensity = 1.0;
  37155. /**
  37156. * Debug Control allowing disabling the bump map on this material.
  37157. */
  37158. _this.disableBumpMap = false;
  37159. /**
  37160. * AKA Occlusion Texture Intensity in other nomenclature.
  37161. */
  37162. _this.ambientTextureStrength = 1.0;
  37163. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37164. /**
  37165. * AKA Diffuse Color in other nomenclature.
  37166. */
  37167. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37168. /**
  37169. * AKA Specular Color in other nomenclature.
  37170. */
  37171. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37172. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37173. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37174. /**
  37175. * AKA Glossiness in other nomenclature.
  37176. */
  37177. _this.microSurface = 1.0;
  37178. /**
  37179. * source material index of refraction (IOR)' / 'destination material IOR.
  37180. */
  37181. _this.indexOfRefraction = 0.66;
  37182. /**
  37183. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37184. */
  37185. _this.invertRefractionY = false;
  37186. /**
  37187. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37188. * Materials half opaque for instance using refraction could benefit from this control.
  37189. */
  37190. _this.linkRefractionWithTransparency = false;
  37191. _this.useLightmapAsShadowmap = false;
  37192. /**
  37193. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37194. */
  37195. _this.useAlphaFromAlbedoTexture = false;
  37196. /**
  37197. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37198. */
  37199. _this.forceAlphaTest = false;
  37200. /**
  37201. * Defines the alpha limits in alpha test mode.
  37202. */
  37203. _this.alphaCutOff = 0.4;
  37204. /**
  37205. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37206. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37207. */
  37208. _this.useSpecularOverAlpha = true;
  37209. /**
  37210. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37211. */
  37212. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37213. /**
  37214. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37215. */
  37216. _this.useRoughnessFromMetallicTextureAlpha = true;
  37217. /**
  37218. * Specifies if the metallic texture contains the roughness information in its green channel.
  37219. */
  37220. _this.useRoughnessFromMetallicTextureGreen = false;
  37221. /**
  37222. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37223. */
  37224. _this.useMetallnessFromMetallicTextureBlue = false;
  37225. /**
  37226. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37227. */
  37228. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37229. /**
  37230. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37231. */
  37232. _this.useAmbientInGrayScale = false;
  37233. /**
  37234. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37235. * The material will try to infer what glossiness each pixel should be.
  37236. */
  37237. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37238. /**
  37239. * BJS is using an harcoded light falloff based on a manually sets up range.
  37240. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37241. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37242. */
  37243. _this.usePhysicalLightFalloff = true;
  37244. /**
  37245. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37246. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37247. */
  37248. _this.useRadianceOverAlpha = true;
  37249. /**
  37250. * Allows using the bump map in parallax mode.
  37251. */
  37252. _this.useParallax = false;
  37253. /**
  37254. * Allows using the bump map in parallax occlusion mode.
  37255. */
  37256. _this.useParallaxOcclusion = false;
  37257. /**
  37258. * Controls the scale bias of the parallax mode.
  37259. */
  37260. _this.parallaxScaleBias = 0.05;
  37261. /**
  37262. * If sets to true, disables all the lights affecting the material.
  37263. */
  37264. _this.disableLighting = false;
  37265. /**
  37266. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37267. */
  37268. _this.forceIrradianceInFragment = false;
  37269. /**
  37270. * Number of Simultaneous lights allowed on the material.
  37271. */
  37272. _this.maxSimultaneousLights = 4;
  37273. /**
  37274. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37275. */
  37276. _this.invertNormalMapX = false;
  37277. /**
  37278. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37279. */
  37280. _this.invertNormalMapY = false;
  37281. /**
  37282. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37283. */
  37284. _this.twoSidedLighting = false;
  37285. /**
  37286. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37287. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37288. */
  37289. _this.useAlphaFresnel = false;
  37290. /**
  37291. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37292. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37293. */
  37294. _this.useLinearAlphaFresnel = false;
  37295. /**
  37296. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37297. * And/Or occlude the blended part.
  37298. */
  37299. _this.environmentBRDFTexture = null;
  37300. /**
  37301. * Force normal to face away from face.
  37302. */
  37303. _this.forceNormalForward = false;
  37304. /**
  37305. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37306. * makes the reflect vector face the model (under horizon).
  37307. */
  37308. _this.useHorizonOcclusion = true;
  37309. /**
  37310. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37311. * too much the area relying on ambient texture to define their ambient occlusion.
  37312. */
  37313. _this.useRadianceOcclusion = true;
  37314. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37315. return _this;
  37316. }
  37317. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37318. /**
  37319. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37320. */
  37321. get: function () {
  37322. return this._PBRMATERIAL_OPAQUE;
  37323. },
  37324. enumerable: true,
  37325. configurable: true
  37326. });
  37327. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37328. /**
  37329. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37330. */
  37331. get: function () {
  37332. return this._PBRMATERIAL_ALPHATEST;
  37333. },
  37334. enumerable: true,
  37335. configurable: true
  37336. });
  37337. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37338. /**
  37339. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37340. */
  37341. get: function () {
  37342. return this._PBRMATERIAL_ALPHABLEND;
  37343. },
  37344. enumerable: true,
  37345. configurable: true
  37346. });
  37347. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37348. /**
  37349. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37350. * They are also discarded below the alpha cutoff threshold to improve performances.
  37351. */
  37352. get: function () {
  37353. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37354. },
  37355. enumerable: true,
  37356. configurable: true
  37357. });
  37358. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37359. /**
  37360. * Gets the image processing configuration used either in this material.
  37361. */
  37362. get: function () {
  37363. return this._imageProcessingConfiguration;
  37364. },
  37365. /**
  37366. * Sets the Default image processing configuration used either in the this material.
  37367. *
  37368. * If sets to null, the scene one is in use.
  37369. */
  37370. set: function (value) {
  37371. this._attachImageProcessingConfiguration(value);
  37372. // Ensure the effect will be rebuilt.
  37373. this._markAllSubMeshesAsTexturesDirty();
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37379. /**
  37380. * Gets wether the color curves effect is enabled.
  37381. */
  37382. get: function () {
  37383. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37384. },
  37385. /**
  37386. * Sets wether the color curves effect is enabled.
  37387. */
  37388. set: function (value) {
  37389. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37390. },
  37391. enumerable: true,
  37392. configurable: true
  37393. });
  37394. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37395. /**
  37396. * Gets wether the color grading effect is enabled.
  37397. */
  37398. get: function () {
  37399. return this.imageProcessingConfiguration.colorGradingEnabled;
  37400. },
  37401. /**
  37402. * Gets wether the color grading effect is enabled.
  37403. */
  37404. set: function (value) {
  37405. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37406. },
  37407. enumerable: true,
  37408. configurable: true
  37409. });
  37410. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37411. /**
  37412. * Gets wether tonemapping is enabled or not.
  37413. */
  37414. get: function () {
  37415. return this._imageProcessingConfiguration.toneMappingEnabled;
  37416. },
  37417. /**
  37418. * Sets wether tonemapping is enabled or not
  37419. */
  37420. set: function (value) {
  37421. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37422. },
  37423. enumerable: true,
  37424. configurable: true
  37425. });
  37426. ;
  37427. ;
  37428. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37429. /**
  37430. * The camera exposure used on this material.
  37431. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37432. * This corresponds to a photographic exposure.
  37433. */
  37434. get: function () {
  37435. return this._imageProcessingConfiguration.exposure;
  37436. },
  37437. /**
  37438. * The camera exposure used on this material.
  37439. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37440. * This corresponds to a photographic exposure.
  37441. */
  37442. set: function (value) {
  37443. this._imageProcessingConfiguration.exposure = value;
  37444. },
  37445. enumerable: true,
  37446. configurable: true
  37447. });
  37448. ;
  37449. ;
  37450. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37451. /**
  37452. * Gets The camera contrast used on this material.
  37453. */
  37454. get: function () {
  37455. return this._imageProcessingConfiguration.contrast;
  37456. },
  37457. /**
  37458. * Sets The camera contrast used on this material.
  37459. */
  37460. set: function (value) {
  37461. this._imageProcessingConfiguration.contrast = value;
  37462. },
  37463. enumerable: true,
  37464. configurable: true
  37465. });
  37466. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37467. /**
  37468. * Gets the Color Grading 2D Lookup Texture.
  37469. */
  37470. get: function () {
  37471. return this._imageProcessingConfiguration.colorGradingTexture;
  37472. },
  37473. /**
  37474. * Sets the Color Grading 2D Lookup Texture.
  37475. */
  37476. set: function (value) {
  37477. this._imageProcessingConfiguration.colorGradingTexture = value;
  37478. },
  37479. enumerable: true,
  37480. configurable: true
  37481. });
  37482. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37483. /**
  37484. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37485. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37486. * 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;
  37487. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37488. */
  37489. get: function () {
  37490. return this._imageProcessingConfiguration.colorCurves;
  37491. },
  37492. /**
  37493. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37494. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37495. * 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;
  37496. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37497. */
  37498. set: function (value) {
  37499. this._imageProcessingConfiguration.colorCurves = value;
  37500. },
  37501. enumerable: true,
  37502. configurable: true
  37503. });
  37504. PBRMaterial.prototype.getClassName = function () {
  37505. return "PBRMaterial";
  37506. };
  37507. PBRMaterial.prototype.getActiveTextures = function () {
  37508. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37509. if (this._albedoTexture) {
  37510. activeTextures.push(this._albedoTexture);
  37511. }
  37512. if (this._ambientTexture) {
  37513. activeTextures.push(this._ambientTexture);
  37514. }
  37515. if (this._opacityTexture) {
  37516. activeTextures.push(this._opacityTexture);
  37517. }
  37518. if (this._reflectionTexture) {
  37519. activeTextures.push(this._reflectionTexture);
  37520. }
  37521. if (this._emissiveTexture) {
  37522. activeTextures.push(this._emissiveTexture);
  37523. }
  37524. if (this._reflectivityTexture) {
  37525. activeTextures.push(this._reflectivityTexture);
  37526. }
  37527. if (this._metallicTexture) {
  37528. activeTextures.push(this._metallicTexture);
  37529. }
  37530. if (this._microSurfaceTexture) {
  37531. activeTextures.push(this._microSurfaceTexture);
  37532. }
  37533. if (this._bumpTexture) {
  37534. activeTextures.push(this._bumpTexture);
  37535. }
  37536. if (this._lightmapTexture) {
  37537. activeTextures.push(this._lightmapTexture);
  37538. }
  37539. if (this._refractionTexture) {
  37540. activeTextures.push(this._refractionTexture);
  37541. }
  37542. return activeTextures;
  37543. };
  37544. PBRMaterial.prototype.hasTexture = function (texture) {
  37545. if (_super.prototype.hasTexture.call(this, texture)) {
  37546. return true;
  37547. }
  37548. if (this._albedoTexture === texture) {
  37549. return true;
  37550. }
  37551. if (this._ambientTexture === texture) {
  37552. return true;
  37553. }
  37554. if (this._opacityTexture === texture) {
  37555. return true;
  37556. }
  37557. if (this._reflectionTexture === texture) {
  37558. return true;
  37559. }
  37560. if (this._reflectivityTexture === texture) {
  37561. return true;
  37562. }
  37563. if (this._metallicTexture === texture) {
  37564. return true;
  37565. }
  37566. if (this._microSurfaceTexture === texture) {
  37567. return true;
  37568. }
  37569. if (this._bumpTexture === texture) {
  37570. return true;
  37571. }
  37572. if (this._lightmapTexture === texture) {
  37573. return true;
  37574. }
  37575. if (this._refractionTexture === texture) {
  37576. return true;
  37577. }
  37578. return false;
  37579. };
  37580. PBRMaterial.prototype.clone = function (name) {
  37581. var _this = this;
  37582. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37583. clone.id = name;
  37584. clone.name = name;
  37585. return clone;
  37586. };
  37587. PBRMaterial.prototype.serialize = function () {
  37588. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37589. serializationObject.customType = "BABYLON.PBRMaterial";
  37590. return serializationObject;
  37591. };
  37592. // Statics
  37593. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37594. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37595. };
  37596. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37597. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37598. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37599. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37600. __decorate([
  37601. BABYLON.serialize(),
  37602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37603. ], PBRMaterial.prototype, "directIntensity", void 0);
  37604. __decorate([
  37605. BABYLON.serialize(),
  37606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37607. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37608. __decorate([
  37609. BABYLON.serialize(),
  37610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37611. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37612. __decorate([
  37613. BABYLON.serialize(),
  37614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37615. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37616. __decorate([
  37617. BABYLON.serialize(),
  37618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37619. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37620. __decorate([
  37621. BABYLON.serializeAsTexture(),
  37622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37623. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37624. __decorate([
  37625. BABYLON.serializeAsTexture(),
  37626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37627. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37628. __decorate([
  37629. BABYLON.serialize(),
  37630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37631. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37632. __decorate([
  37633. BABYLON.serializeAsTexture(),
  37634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37635. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37636. __decorate([
  37637. BABYLON.serializeAsTexture(),
  37638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37639. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37640. __decorate([
  37641. BABYLON.serializeAsTexture(),
  37642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37643. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37644. __decorate([
  37645. BABYLON.serializeAsTexture(),
  37646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37647. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37648. __decorate([
  37649. BABYLON.serializeAsTexture(),
  37650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37651. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37652. __decorate([
  37653. BABYLON.serialize(),
  37654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37655. ], PBRMaterial.prototype, "metallic", void 0);
  37656. __decorate([
  37657. BABYLON.serialize(),
  37658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37659. ], PBRMaterial.prototype, "roughness", void 0);
  37660. __decorate([
  37661. BABYLON.serializeAsTexture(),
  37662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37663. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37664. __decorate([
  37665. BABYLON.serializeAsTexture(),
  37666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37667. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37668. __decorate([
  37669. BABYLON.serializeAsTexture(),
  37670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37671. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37672. __decorate([
  37673. BABYLON.serializeAsTexture(),
  37674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37675. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37676. __decorate([
  37677. BABYLON.serializeAsColor3("ambient"),
  37678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37679. ], PBRMaterial.prototype, "ambientColor", void 0);
  37680. __decorate([
  37681. BABYLON.serializeAsColor3("albedo"),
  37682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37683. ], PBRMaterial.prototype, "albedoColor", void 0);
  37684. __decorate([
  37685. BABYLON.serializeAsColor3("reflectivity"),
  37686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37687. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37688. __decorate([
  37689. BABYLON.serializeAsColor3("reflection"),
  37690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37691. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37692. __decorate([
  37693. BABYLON.serializeAsColor3("emissive"),
  37694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37695. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37696. __decorate([
  37697. BABYLON.serialize(),
  37698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37699. ], PBRMaterial.prototype, "microSurface", void 0);
  37700. __decorate([
  37701. BABYLON.serialize(),
  37702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37703. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37704. __decorate([
  37705. BABYLON.serialize(),
  37706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37707. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37708. __decorate([
  37709. BABYLON.serialize(),
  37710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37711. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37712. __decorate([
  37713. BABYLON.serialize(),
  37714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37715. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37716. __decorate([
  37717. BABYLON.serialize(),
  37718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37719. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37720. __decorate([
  37721. BABYLON.serialize(),
  37722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37723. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37724. __decorate([
  37725. BABYLON.serialize(),
  37726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37727. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37728. __decorate([
  37729. BABYLON.serialize(),
  37730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37731. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37732. __decorate([
  37733. BABYLON.serialize(),
  37734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37735. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37736. __decorate([
  37737. BABYLON.serialize(),
  37738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37739. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37740. __decorate([
  37741. BABYLON.serialize(),
  37742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37743. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37744. __decorate([
  37745. BABYLON.serialize(),
  37746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37747. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37748. __decorate([
  37749. BABYLON.serialize(),
  37750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37751. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37752. __decorate([
  37753. BABYLON.serialize(),
  37754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37755. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37756. __decorate([
  37757. BABYLON.serialize(),
  37758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37759. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37760. __decorate([
  37761. BABYLON.serialize(),
  37762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37763. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37764. __decorate([
  37765. BABYLON.serialize(),
  37766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37767. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37768. __decorate([
  37769. BABYLON.serialize(),
  37770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37771. ], PBRMaterial.prototype, "useParallax", void 0);
  37772. __decorate([
  37773. BABYLON.serialize(),
  37774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37775. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37776. __decorate([
  37777. BABYLON.serialize(),
  37778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37779. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37780. __decorate([
  37781. BABYLON.serialize(),
  37782. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37783. ], PBRMaterial.prototype, "disableLighting", void 0);
  37784. __decorate([
  37785. BABYLON.serialize(),
  37786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37787. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37788. __decorate([
  37789. BABYLON.serialize(),
  37790. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37791. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37792. __decorate([
  37793. BABYLON.serialize(),
  37794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37795. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37796. __decorate([
  37797. BABYLON.serialize(),
  37798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37799. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37800. __decorate([
  37801. BABYLON.serialize(),
  37802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37803. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37804. __decorate([
  37805. BABYLON.serialize(),
  37806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37807. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37808. __decorate([
  37809. BABYLON.serialize(),
  37810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37811. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  37812. __decorate([
  37813. BABYLON.serializeAsTexture(),
  37814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37815. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37816. __decorate([
  37817. BABYLON.serialize(),
  37818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37819. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37820. __decorate([
  37821. BABYLON.serialize(),
  37822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37823. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  37824. __decorate([
  37825. BABYLON.serialize(),
  37826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37827. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  37828. return PBRMaterial;
  37829. }(BABYLON.PBRBaseMaterial));
  37830. BABYLON.PBRMaterial = PBRMaterial;
  37831. })(BABYLON || (BABYLON = {}));
  37832. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37833. var BABYLON;
  37834. (function (BABYLON) {
  37835. /**
  37836. * The PBR material of BJS following the metal roughness convention.
  37837. *
  37838. * This fits to the PBR convention in the GLTF definition:
  37839. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37840. */
  37841. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37842. __extends(PBRMetallicRoughnessMaterial, _super);
  37843. /**
  37844. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37845. *
  37846. * @param name The material name
  37847. * @param scene The scene the material will be use in.
  37848. */
  37849. function PBRMetallicRoughnessMaterial(name, scene) {
  37850. var _this = _super.call(this, name, scene) || this;
  37851. _this._useRoughnessFromMetallicTextureAlpha = false;
  37852. _this._useRoughnessFromMetallicTextureGreen = true;
  37853. _this._useMetallnessFromMetallicTextureBlue = true;
  37854. return _this;
  37855. }
  37856. /**
  37857. * Return the currrent class name of the material.
  37858. */
  37859. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37860. return "PBRMetallicRoughnessMaterial";
  37861. };
  37862. /**
  37863. * Return the active textures of the material.
  37864. */
  37865. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37866. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37867. if (this.baseTexture) {
  37868. activeTextures.push(this.baseTexture);
  37869. }
  37870. if (this.metallicRoughnessTexture) {
  37871. activeTextures.push(this.metallicRoughnessTexture);
  37872. }
  37873. return activeTextures;
  37874. };
  37875. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37876. if (_super.prototype.hasTexture.call(this, texture)) {
  37877. return true;
  37878. }
  37879. if (this.baseTexture === texture) {
  37880. return true;
  37881. }
  37882. if (this.metallicRoughnessTexture === texture) {
  37883. return true;
  37884. }
  37885. return false;
  37886. };
  37887. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37888. var _this = this;
  37889. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37890. clone.id = name;
  37891. clone.name = name;
  37892. return clone;
  37893. };
  37894. /**
  37895. * Serialize the material to a parsable JSON object.
  37896. */
  37897. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37898. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37899. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37900. return serializationObject;
  37901. };
  37902. /**
  37903. * Parses a JSON object correponding to the serialize function.
  37904. */
  37905. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37906. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37907. };
  37908. __decorate([
  37909. BABYLON.serializeAsColor3(),
  37910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37911. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37912. __decorate([
  37913. BABYLON.serializeAsTexture(),
  37914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37915. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37916. __decorate([
  37917. BABYLON.serialize(),
  37918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37919. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37920. __decorate([
  37921. BABYLON.serialize(),
  37922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37923. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37924. __decorate([
  37925. BABYLON.serializeAsTexture(),
  37926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37927. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37928. return PBRMetallicRoughnessMaterial;
  37929. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37930. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37931. })(BABYLON || (BABYLON = {}));
  37932. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37933. var BABYLON;
  37934. (function (BABYLON) {
  37935. /**
  37936. * The PBR material of BJS following the specular glossiness convention.
  37937. *
  37938. * This fits to the PBR convention in the GLTF definition:
  37939. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37940. */
  37941. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37942. __extends(PBRSpecularGlossinessMaterial, _super);
  37943. /**
  37944. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37945. *
  37946. * @param name The material name
  37947. * @param scene The scene the material will be use in.
  37948. */
  37949. function PBRSpecularGlossinessMaterial(name, scene) {
  37950. var _this = _super.call(this, name, scene) || this;
  37951. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37952. return _this;
  37953. }
  37954. /**
  37955. * Return the currrent class name of the material.
  37956. */
  37957. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37958. return "PBRSpecularGlossinessMaterial";
  37959. };
  37960. /**
  37961. * Return the active textures of the material.
  37962. */
  37963. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37964. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37965. if (this.diffuseTexture) {
  37966. activeTextures.push(this.diffuseTexture);
  37967. }
  37968. if (this.specularGlossinessTexture) {
  37969. activeTextures.push(this.specularGlossinessTexture);
  37970. }
  37971. return activeTextures;
  37972. };
  37973. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37974. if (_super.prototype.hasTexture.call(this, texture)) {
  37975. return true;
  37976. }
  37977. if (this.diffuseTexture === texture) {
  37978. return true;
  37979. }
  37980. if (this.specularGlossinessTexture === texture) {
  37981. return true;
  37982. }
  37983. return false;
  37984. };
  37985. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37986. var _this = this;
  37987. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37988. clone.id = name;
  37989. clone.name = name;
  37990. return clone;
  37991. };
  37992. /**
  37993. * Serialize the material to a parsable JSON object.
  37994. */
  37995. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37996. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37997. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37998. return serializationObject;
  37999. };
  38000. /**
  38001. * Parses a JSON object correponding to the serialize function.
  38002. */
  38003. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38004. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38005. };
  38006. __decorate([
  38007. BABYLON.serializeAsColor3("diffuse"),
  38008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38009. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38010. __decorate([
  38011. BABYLON.serializeAsTexture(),
  38012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38013. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38014. __decorate([
  38015. BABYLON.serializeAsColor3("specular"),
  38016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38017. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38018. __decorate([
  38019. BABYLON.serialize(),
  38020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38021. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38022. __decorate([
  38023. BABYLON.serializeAsTexture(),
  38024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38025. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38026. return PBRSpecularGlossinessMaterial;
  38027. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38028. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38029. })(BABYLON || (BABYLON = {}));
  38030. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38031. var BABYLON;
  38032. (function (BABYLON) {
  38033. BABYLON.CameraInputTypes = {};
  38034. var CameraInputsManager = /** @class */ (function () {
  38035. function CameraInputsManager(camera) {
  38036. this.attached = {};
  38037. this.camera = camera;
  38038. this.checkInputs = function () { };
  38039. }
  38040. CameraInputsManager.prototype.add = function (input) {
  38041. var type = input.getSimpleName();
  38042. if (this.attached[type]) {
  38043. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38044. return;
  38045. }
  38046. this.attached[type] = input;
  38047. input.camera = this.camera;
  38048. //for checkInputs, we are dynamically creating a function
  38049. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38050. if (input.checkInputs) {
  38051. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38052. }
  38053. if (this.attachedElement) {
  38054. input.attachControl(this.attachedElement);
  38055. }
  38056. };
  38057. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38058. for (var cam in this.attached) {
  38059. var input = this.attached[cam];
  38060. if (input === inputToRemove) {
  38061. input.detachControl(this.attachedElement);
  38062. input.camera = null;
  38063. delete this.attached[cam];
  38064. this.rebuildInputCheck();
  38065. }
  38066. }
  38067. };
  38068. CameraInputsManager.prototype.removeByType = function (inputType) {
  38069. for (var cam in this.attached) {
  38070. var input = this.attached[cam];
  38071. if (input.getClassName() === inputType) {
  38072. input.detachControl(this.attachedElement);
  38073. input.camera = null;
  38074. delete this.attached[cam];
  38075. this.rebuildInputCheck();
  38076. }
  38077. }
  38078. };
  38079. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38080. var current = this.checkInputs;
  38081. return function () {
  38082. current();
  38083. fn();
  38084. };
  38085. };
  38086. CameraInputsManager.prototype.attachInput = function (input) {
  38087. if (this.attachedElement) {
  38088. input.attachControl(this.attachedElement, this.noPreventDefault);
  38089. }
  38090. };
  38091. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38092. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38093. if (this.attachedElement) {
  38094. return;
  38095. }
  38096. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38097. this.attachedElement = element;
  38098. this.noPreventDefault = noPreventDefault;
  38099. for (var cam in this.attached) {
  38100. this.attached[cam].attachControl(element, noPreventDefault);
  38101. }
  38102. };
  38103. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38104. if (disconnect === void 0) { disconnect = false; }
  38105. if (this.attachedElement !== element) {
  38106. return;
  38107. }
  38108. for (var cam in this.attached) {
  38109. this.attached[cam].detachControl(element);
  38110. if (disconnect) {
  38111. this.attached[cam].camera = null;
  38112. }
  38113. }
  38114. this.attachedElement = null;
  38115. };
  38116. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38117. this.checkInputs = function () { };
  38118. for (var cam in this.attached) {
  38119. var input = this.attached[cam];
  38120. if (input.checkInputs) {
  38121. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38122. }
  38123. }
  38124. };
  38125. CameraInputsManager.prototype.clear = function () {
  38126. if (this.attachedElement) {
  38127. this.detachElement(this.attachedElement, true);
  38128. }
  38129. this.attached = {};
  38130. this.attachedElement = null;
  38131. this.checkInputs = function () { };
  38132. };
  38133. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38134. var inputs = {};
  38135. for (var cam in this.attached) {
  38136. var input = this.attached[cam];
  38137. var res = BABYLON.SerializationHelper.Serialize(input);
  38138. inputs[input.getClassName()] = res;
  38139. }
  38140. serializedCamera.inputsmgr = inputs;
  38141. };
  38142. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38143. var parsedInputs = parsedCamera.inputsmgr;
  38144. if (parsedInputs) {
  38145. this.clear();
  38146. for (var n in parsedInputs) {
  38147. var construct = BABYLON.CameraInputTypes[n];
  38148. if (construct) {
  38149. var parsedinput = parsedInputs[n];
  38150. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38151. this.add(input);
  38152. }
  38153. }
  38154. }
  38155. else {
  38156. //2016-03-08 this part is for managing backward compatibility
  38157. for (var n in this.attached) {
  38158. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38159. if (construct) {
  38160. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38161. this.remove(this.attached[n]);
  38162. this.add(input);
  38163. }
  38164. }
  38165. }
  38166. };
  38167. return CameraInputsManager;
  38168. }());
  38169. BABYLON.CameraInputsManager = CameraInputsManager;
  38170. })(BABYLON || (BABYLON = {}));
  38171. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38172. var BABYLON;
  38173. (function (BABYLON) {
  38174. var FreeCameraMouseInput = /** @class */ (function () {
  38175. function FreeCameraMouseInput(touchEnabled) {
  38176. if (touchEnabled === void 0) { touchEnabled = true; }
  38177. this.touchEnabled = touchEnabled;
  38178. this.buttons = [0, 1, 2];
  38179. this.angularSensibility = 2000.0;
  38180. this.previousPosition = null;
  38181. }
  38182. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38183. var _this = this;
  38184. var engine = this.camera.getEngine();
  38185. if (!this._pointerInput) {
  38186. this._pointerInput = function (p, s) {
  38187. var evt = p.event;
  38188. if (engine.isInVRExclusivePointerMode) {
  38189. return;
  38190. }
  38191. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38192. return;
  38193. }
  38194. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38195. return;
  38196. }
  38197. var srcElement = (evt.srcElement || evt.target);
  38198. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38199. try {
  38200. srcElement.setPointerCapture(evt.pointerId);
  38201. }
  38202. catch (e) {
  38203. //Nothing to do with the error. Execution will continue.
  38204. }
  38205. _this.previousPosition = {
  38206. x: evt.clientX,
  38207. y: evt.clientY
  38208. };
  38209. if (!noPreventDefault) {
  38210. evt.preventDefault();
  38211. element.focus();
  38212. }
  38213. }
  38214. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38215. try {
  38216. srcElement.releasePointerCapture(evt.pointerId);
  38217. }
  38218. catch (e) {
  38219. //Nothing to do with the error.
  38220. }
  38221. _this.previousPosition = null;
  38222. if (!noPreventDefault) {
  38223. evt.preventDefault();
  38224. }
  38225. }
  38226. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38227. if (!_this.previousPosition || engine.isPointerLock) {
  38228. return;
  38229. }
  38230. var offsetX = evt.clientX - _this.previousPosition.x;
  38231. var offsetY = evt.clientY - _this.previousPosition.y;
  38232. if (_this.camera.getScene().useRightHandedSystem) {
  38233. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38234. }
  38235. else {
  38236. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38237. }
  38238. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38239. _this.previousPosition = {
  38240. x: evt.clientX,
  38241. y: evt.clientY
  38242. };
  38243. if (!noPreventDefault) {
  38244. evt.preventDefault();
  38245. }
  38246. }
  38247. };
  38248. }
  38249. this._onMouseMove = function (evt) {
  38250. if (!engine.isPointerLock) {
  38251. return;
  38252. }
  38253. if (engine.isInVRExclusivePointerMode) {
  38254. return;
  38255. }
  38256. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38257. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38258. if (_this.camera.getScene().useRightHandedSystem) {
  38259. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38260. }
  38261. else {
  38262. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38263. }
  38264. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38265. _this.previousPosition = null;
  38266. if (!noPreventDefault) {
  38267. evt.preventDefault();
  38268. }
  38269. };
  38270. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38271. element.addEventListener("mousemove", this._onMouseMove, false);
  38272. };
  38273. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38274. if (this._observer && element) {
  38275. this.camera.getScene().onPointerObservable.remove(this._observer);
  38276. if (this._onMouseMove) {
  38277. element.removeEventListener("mousemove", this._onMouseMove);
  38278. }
  38279. this._observer = null;
  38280. this._onMouseMove = null;
  38281. this.previousPosition = null;
  38282. }
  38283. };
  38284. FreeCameraMouseInput.prototype.getClassName = function () {
  38285. return "FreeCameraMouseInput";
  38286. };
  38287. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38288. return "mouse";
  38289. };
  38290. __decorate([
  38291. BABYLON.serialize()
  38292. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38293. __decorate([
  38294. BABYLON.serialize()
  38295. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38296. return FreeCameraMouseInput;
  38297. }());
  38298. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38299. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38300. })(BABYLON || (BABYLON = {}));
  38301. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38302. var BABYLON;
  38303. (function (BABYLON) {
  38304. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38305. function FreeCameraKeyboardMoveInput() {
  38306. this._keys = new Array();
  38307. this.keysUp = [38];
  38308. this.keysDown = [40];
  38309. this.keysLeft = [37];
  38310. this.keysRight = [39];
  38311. }
  38312. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38313. var _this = this;
  38314. if (this._onCanvasBlurObserver) {
  38315. return;
  38316. }
  38317. this._scene = this.camera.getScene();
  38318. this._engine = this._scene.getEngine();
  38319. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38320. _this._keys = [];
  38321. });
  38322. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38323. var evt = info.event;
  38324. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38325. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38326. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38327. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38328. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38329. var index = _this._keys.indexOf(evt.keyCode);
  38330. if (index === -1) {
  38331. _this._keys.push(evt.keyCode);
  38332. }
  38333. if (!noPreventDefault) {
  38334. evt.preventDefault();
  38335. }
  38336. }
  38337. }
  38338. else {
  38339. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38340. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38341. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38342. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38343. var index = _this._keys.indexOf(evt.keyCode);
  38344. if (index >= 0) {
  38345. _this._keys.splice(index, 1);
  38346. }
  38347. if (!noPreventDefault) {
  38348. evt.preventDefault();
  38349. }
  38350. }
  38351. }
  38352. });
  38353. };
  38354. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38355. if (this._scene) {
  38356. if (this._onKeyboardObserver) {
  38357. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38358. }
  38359. if (this._onCanvasBlurObserver) {
  38360. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38361. }
  38362. this._onKeyboardObserver = null;
  38363. this._onCanvasBlurObserver = null;
  38364. }
  38365. this._keys = [];
  38366. };
  38367. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38368. if (this._onKeyboardObserver) {
  38369. var camera = this.camera;
  38370. // Keyboard
  38371. for (var index = 0; index < this._keys.length; index++) {
  38372. var keyCode = this._keys[index];
  38373. var speed = camera._computeLocalCameraSpeed();
  38374. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38375. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38376. }
  38377. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38378. camera._localDirection.copyFromFloats(0, 0, speed);
  38379. }
  38380. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38381. camera._localDirection.copyFromFloats(speed, 0, 0);
  38382. }
  38383. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38384. camera._localDirection.copyFromFloats(0, 0, -speed);
  38385. }
  38386. if (camera.getScene().useRightHandedSystem) {
  38387. camera._localDirection.z *= -1;
  38388. }
  38389. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38390. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38391. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38392. }
  38393. }
  38394. };
  38395. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38396. return "FreeCameraKeyboardMoveInput";
  38397. };
  38398. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38399. this._keys = [];
  38400. };
  38401. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38402. return "keyboard";
  38403. };
  38404. __decorate([
  38405. BABYLON.serialize()
  38406. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38407. __decorate([
  38408. BABYLON.serialize()
  38409. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38410. __decorate([
  38411. BABYLON.serialize()
  38412. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38413. __decorate([
  38414. BABYLON.serialize()
  38415. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38416. return FreeCameraKeyboardMoveInput;
  38417. }());
  38418. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38419. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38420. })(BABYLON || (BABYLON = {}));
  38421. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38422. var BABYLON;
  38423. (function (BABYLON) {
  38424. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38425. __extends(FreeCameraInputsManager, _super);
  38426. function FreeCameraInputsManager(camera) {
  38427. return _super.call(this, camera) || this;
  38428. }
  38429. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38430. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38431. return this;
  38432. };
  38433. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38434. if (touchEnabled === void 0) { touchEnabled = true; }
  38435. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38436. return this;
  38437. };
  38438. FreeCameraInputsManager.prototype.addGamepad = function () {
  38439. this.add(new BABYLON.FreeCameraGamepadInput());
  38440. return this;
  38441. };
  38442. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38443. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38444. return this;
  38445. };
  38446. FreeCameraInputsManager.prototype.addTouch = function () {
  38447. this.add(new BABYLON.FreeCameraTouchInput());
  38448. return this;
  38449. };
  38450. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38451. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38452. return this;
  38453. };
  38454. return FreeCameraInputsManager;
  38455. }(BABYLON.CameraInputsManager));
  38456. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38457. })(BABYLON || (BABYLON = {}));
  38458. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38459. var BABYLON;
  38460. (function (BABYLON) {
  38461. var TargetCamera = /** @class */ (function (_super) {
  38462. __extends(TargetCamera, _super);
  38463. function TargetCamera(name, position, scene) {
  38464. var _this = _super.call(this, name, position, scene) || this;
  38465. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38466. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38467. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38468. _this.speed = 2.0;
  38469. _this.noRotationConstraint = false;
  38470. _this.lockedTarget = null;
  38471. _this._currentTarget = BABYLON.Vector3.Zero();
  38472. _this._viewMatrix = BABYLON.Matrix.Zero();
  38473. _this._camMatrix = BABYLON.Matrix.Zero();
  38474. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38475. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38476. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38477. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38478. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38479. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38480. _this._tempMatrix = BABYLON.Matrix.Zero();
  38481. return _this;
  38482. }
  38483. TargetCamera.prototype.getFrontPosition = function (distance) {
  38484. var direction = this.getTarget().subtract(this.position);
  38485. direction.normalize();
  38486. direction.scaleInPlace(distance);
  38487. return this.globalPosition.add(direction);
  38488. };
  38489. TargetCamera.prototype._getLockedTargetPosition = function () {
  38490. if (!this.lockedTarget) {
  38491. return null;
  38492. }
  38493. if (this.lockedTarget.absolutePosition) {
  38494. this.lockedTarget.computeWorldMatrix();
  38495. }
  38496. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38497. };
  38498. TargetCamera.prototype.storeState = function () {
  38499. this._storedPosition = this.position.clone();
  38500. this._storedRotation = this.rotation.clone();
  38501. if (this.rotationQuaternion) {
  38502. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38503. }
  38504. return _super.prototype.storeState.call(this);
  38505. };
  38506. /**
  38507. * Restored camera state. You must call storeState() first
  38508. */
  38509. TargetCamera.prototype._restoreStateValues = function () {
  38510. if (!_super.prototype._restoreStateValues.call(this)) {
  38511. return false;
  38512. }
  38513. this.position = this._storedPosition.clone();
  38514. this.rotation = this._storedRotation.clone();
  38515. if (this.rotationQuaternion) {
  38516. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38517. }
  38518. this.cameraDirection.copyFromFloats(0, 0, 0);
  38519. this.cameraRotation.copyFromFloats(0, 0);
  38520. return true;
  38521. };
  38522. // Cache
  38523. TargetCamera.prototype._initCache = function () {
  38524. _super.prototype._initCache.call(this);
  38525. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38526. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38527. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38528. };
  38529. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38530. if (!ignoreParentClass) {
  38531. _super.prototype._updateCache.call(this);
  38532. }
  38533. var lockedTargetPosition = this._getLockedTargetPosition();
  38534. if (!lockedTargetPosition) {
  38535. this._cache.lockedTarget = null;
  38536. }
  38537. else {
  38538. if (!this._cache.lockedTarget) {
  38539. this._cache.lockedTarget = lockedTargetPosition.clone();
  38540. }
  38541. else {
  38542. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38543. }
  38544. }
  38545. this._cache.rotation.copyFrom(this.rotation);
  38546. if (this.rotationQuaternion)
  38547. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38548. };
  38549. // Synchronized
  38550. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38551. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38552. return false;
  38553. }
  38554. var lockedTargetPosition = this._getLockedTargetPosition();
  38555. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38556. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38557. };
  38558. // Methods
  38559. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38560. var engine = this.getEngine();
  38561. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38562. };
  38563. // Target
  38564. TargetCamera.prototype.setTarget = function (target) {
  38565. this.upVector.normalize();
  38566. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38567. this._camMatrix.invert();
  38568. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38569. var vDir = target.subtract(this.position);
  38570. if (vDir.x >= 0.0) {
  38571. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38572. }
  38573. else {
  38574. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38575. }
  38576. this.rotation.z = 0;
  38577. if (isNaN(this.rotation.x)) {
  38578. this.rotation.x = 0;
  38579. }
  38580. if (isNaN(this.rotation.y)) {
  38581. this.rotation.y = 0;
  38582. }
  38583. if (isNaN(this.rotation.z)) {
  38584. this.rotation.z = 0;
  38585. }
  38586. if (this.rotationQuaternion) {
  38587. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38588. }
  38589. };
  38590. /**
  38591. * Return the current target position of the camera. This value is expressed in local space.
  38592. */
  38593. TargetCamera.prototype.getTarget = function () {
  38594. return this._currentTarget;
  38595. };
  38596. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38597. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38598. };
  38599. TargetCamera.prototype._updatePosition = function () {
  38600. if (this.parent) {
  38601. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38602. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38603. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38604. return;
  38605. }
  38606. this.position.addInPlace(this.cameraDirection);
  38607. };
  38608. TargetCamera.prototype._checkInputs = function () {
  38609. var needToMove = this._decideIfNeedsToMove();
  38610. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38611. // Move
  38612. if (needToMove) {
  38613. this._updatePosition();
  38614. }
  38615. // Rotate
  38616. if (needToRotate) {
  38617. this.rotation.x += this.cameraRotation.x;
  38618. this.rotation.y += this.cameraRotation.y;
  38619. //rotate, if quaternion is set and rotation was used
  38620. if (this.rotationQuaternion) {
  38621. var len = this.rotation.lengthSquared();
  38622. if (len) {
  38623. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38624. }
  38625. }
  38626. if (!this.noRotationConstraint) {
  38627. var limit = (Math.PI / 2) * 0.95;
  38628. if (this.rotation.x > limit)
  38629. this.rotation.x = limit;
  38630. if (this.rotation.x < -limit)
  38631. this.rotation.x = -limit;
  38632. }
  38633. }
  38634. // Inertia
  38635. if (needToMove) {
  38636. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38637. this.cameraDirection.x = 0;
  38638. }
  38639. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38640. this.cameraDirection.y = 0;
  38641. }
  38642. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38643. this.cameraDirection.z = 0;
  38644. }
  38645. this.cameraDirection.scaleInPlace(this.inertia);
  38646. }
  38647. if (needToRotate) {
  38648. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38649. this.cameraRotation.x = 0;
  38650. }
  38651. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38652. this.cameraRotation.y = 0;
  38653. }
  38654. this.cameraRotation.scaleInPlace(this.inertia);
  38655. }
  38656. _super.prototype._checkInputs.call(this);
  38657. };
  38658. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38659. if (this.rotationQuaternion) {
  38660. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38661. }
  38662. else {
  38663. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38664. }
  38665. //update the up vector!
  38666. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  38667. };
  38668. TargetCamera.prototype._getViewMatrix = function () {
  38669. if (this.lockedTarget) {
  38670. this.setTarget(this._getLockedTargetPosition());
  38671. }
  38672. // Compute
  38673. this._updateCameraRotationMatrix();
  38674. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38675. // Computing target and final matrix
  38676. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38677. if (this.getScene().useRightHandedSystem) {
  38678. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38679. }
  38680. else {
  38681. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  38682. }
  38683. return this._viewMatrix;
  38684. };
  38685. /**
  38686. * @override
  38687. * Override Camera.createRigCamera
  38688. */
  38689. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38690. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38691. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38692. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38693. if (!this.rotationQuaternion) {
  38694. this.rotationQuaternion = new BABYLON.Quaternion();
  38695. }
  38696. rigCamera._cameraRigParams = {};
  38697. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38698. }
  38699. return rigCamera;
  38700. }
  38701. return null;
  38702. };
  38703. /**
  38704. * @override
  38705. * Override Camera._updateRigCameras
  38706. */
  38707. TargetCamera.prototype._updateRigCameras = function () {
  38708. var camLeft = this._rigCameras[0];
  38709. var camRight = this._rigCameras[1];
  38710. switch (this.cameraRigMode) {
  38711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38713. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38714. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38715. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38716. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38717. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38718. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38719. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38720. camLeft.setTarget(this.getTarget());
  38721. camRight.setTarget(this.getTarget());
  38722. break;
  38723. case BABYLON.Camera.RIG_MODE_VR:
  38724. if (camLeft.rotationQuaternion) {
  38725. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38726. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38727. }
  38728. else {
  38729. camLeft.rotation.copyFrom(this.rotation);
  38730. camRight.rotation.copyFrom(this.rotation);
  38731. }
  38732. camLeft.position.copyFrom(this.position);
  38733. camRight.position.copyFrom(this.position);
  38734. break;
  38735. }
  38736. _super.prototype._updateRigCameras.call(this);
  38737. };
  38738. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38739. if (!this._rigCamTransformMatrix) {
  38740. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38741. }
  38742. var target = this.getTarget();
  38743. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38744. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38745. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38746. };
  38747. TargetCamera.prototype.getClassName = function () {
  38748. return "TargetCamera";
  38749. };
  38750. __decorate([
  38751. BABYLON.serializeAsVector3()
  38752. ], TargetCamera.prototype, "rotation", void 0);
  38753. __decorate([
  38754. BABYLON.serialize()
  38755. ], TargetCamera.prototype, "speed", void 0);
  38756. __decorate([
  38757. BABYLON.serializeAsMeshReference("lockedTargetId")
  38758. ], TargetCamera.prototype, "lockedTarget", void 0);
  38759. return TargetCamera;
  38760. }(BABYLON.Camera));
  38761. BABYLON.TargetCamera = TargetCamera;
  38762. })(BABYLON || (BABYLON = {}));
  38763. //# sourceMappingURL=babylon.targetCamera.js.map
  38764. var BABYLON;
  38765. (function (BABYLON) {
  38766. var FreeCamera = /** @class */ (function (_super) {
  38767. __extends(FreeCamera, _super);
  38768. function FreeCamera(name, position, scene) {
  38769. var _this = _super.call(this, name, position, scene) || this;
  38770. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38771. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  38772. _this.checkCollisions = false;
  38773. _this.applyGravity = false;
  38774. _this._needMoveForGravity = false;
  38775. _this._oldPosition = BABYLON.Vector3.Zero();
  38776. _this._diffPosition = BABYLON.Vector3.Zero();
  38777. _this._newPosition = BABYLON.Vector3.Zero();
  38778. // Collisions
  38779. _this._collisionMask = -1;
  38780. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38781. if (collidedMesh === void 0) { collidedMesh = null; }
  38782. //TODO move this to the collision coordinator!
  38783. if (_this.getScene().workerCollisions)
  38784. newPosition.multiplyInPlace(_this._collider._radius);
  38785. var updatePosition = function (newPos) {
  38786. _this._newPosition.copyFrom(newPos);
  38787. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38788. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38789. _this.position.addInPlace(_this._diffPosition);
  38790. if (_this.onCollide && collidedMesh) {
  38791. _this.onCollide(collidedMesh);
  38792. }
  38793. }
  38794. };
  38795. updatePosition(newPosition);
  38796. };
  38797. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38798. _this.inputs.addKeyboard().addMouse();
  38799. return _this;
  38800. }
  38801. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38802. //-- begin properties for backward compatibility for inputs
  38803. get: function () {
  38804. var mouse = this.inputs.attached["mouse"];
  38805. if (mouse)
  38806. return mouse.angularSensibility;
  38807. return 0;
  38808. },
  38809. set: function (value) {
  38810. var mouse = this.inputs.attached["mouse"];
  38811. if (mouse)
  38812. mouse.angularSensibility = value;
  38813. },
  38814. enumerable: true,
  38815. configurable: true
  38816. });
  38817. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38818. get: function () {
  38819. var keyboard = this.inputs.attached["keyboard"];
  38820. if (keyboard)
  38821. return keyboard.keysUp;
  38822. return [];
  38823. },
  38824. set: function (value) {
  38825. var keyboard = this.inputs.attached["keyboard"];
  38826. if (keyboard)
  38827. keyboard.keysUp = value;
  38828. },
  38829. enumerable: true,
  38830. configurable: true
  38831. });
  38832. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38833. get: function () {
  38834. var keyboard = this.inputs.attached["keyboard"];
  38835. if (keyboard)
  38836. return keyboard.keysDown;
  38837. return [];
  38838. },
  38839. set: function (value) {
  38840. var keyboard = this.inputs.attached["keyboard"];
  38841. if (keyboard)
  38842. keyboard.keysDown = value;
  38843. },
  38844. enumerable: true,
  38845. configurable: true
  38846. });
  38847. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38848. get: function () {
  38849. var keyboard = this.inputs.attached["keyboard"];
  38850. if (keyboard)
  38851. return keyboard.keysLeft;
  38852. return [];
  38853. },
  38854. set: function (value) {
  38855. var keyboard = this.inputs.attached["keyboard"];
  38856. if (keyboard)
  38857. keyboard.keysLeft = value;
  38858. },
  38859. enumerable: true,
  38860. configurable: true
  38861. });
  38862. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38863. get: function () {
  38864. var keyboard = this.inputs.attached["keyboard"];
  38865. if (keyboard)
  38866. return keyboard.keysRight;
  38867. return [];
  38868. },
  38869. set: function (value) {
  38870. var keyboard = this.inputs.attached["keyboard"];
  38871. if (keyboard)
  38872. keyboard.keysRight = value;
  38873. },
  38874. enumerable: true,
  38875. configurable: true
  38876. });
  38877. // Controls
  38878. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38879. this.inputs.attachElement(element, noPreventDefault);
  38880. };
  38881. FreeCamera.prototype.detachControl = function (element) {
  38882. this.inputs.detachElement(element);
  38883. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38884. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38885. };
  38886. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38887. get: function () {
  38888. return this._collisionMask;
  38889. },
  38890. set: function (mask) {
  38891. this._collisionMask = !isNaN(mask) ? mask : -1;
  38892. },
  38893. enumerable: true,
  38894. configurable: true
  38895. });
  38896. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38897. var globalPosition;
  38898. if (this.parent) {
  38899. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38900. }
  38901. else {
  38902. globalPosition = this.position;
  38903. }
  38904. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38905. this._oldPosition.addInPlace(this.ellipsoidOffset);
  38906. if (!this._collider) {
  38907. this._collider = new BABYLON.Collider();
  38908. }
  38909. this._collider._radius = this.ellipsoid;
  38910. this._collider.collisionMask = this._collisionMask;
  38911. //no need for clone, as long as gravity is not on.
  38912. var actualDisplacement = displacement;
  38913. //add gravity to the direction to prevent the dual-collision checking
  38914. if (this.applyGravity) {
  38915. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38916. actualDisplacement = displacement.add(this.getScene().gravity);
  38917. }
  38918. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38919. };
  38920. FreeCamera.prototype._checkInputs = function () {
  38921. if (!this._localDirection) {
  38922. this._localDirection = BABYLON.Vector3.Zero();
  38923. this._transformedDirection = BABYLON.Vector3.Zero();
  38924. }
  38925. this.inputs.checkInputs();
  38926. _super.prototype._checkInputs.call(this);
  38927. };
  38928. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38929. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38930. };
  38931. FreeCamera.prototype._updatePosition = function () {
  38932. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38933. this._collideWithWorld(this.cameraDirection);
  38934. }
  38935. else {
  38936. _super.prototype._updatePosition.call(this);
  38937. }
  38938. };
  38939. FreeCamera.prototype.dispose = function () {
  38940. this.inputs.clear();
  38941. _super.prototype.dispose.call(this);
  38942. };
  38943. FreeCamera.prototype.getClassName = function () {
  38944. return "FreeCamera";
  38945. };
  38946. __decorate([
  38947. BABYLON.serializeAsVector3()
  38948. ], FreeCamera.prototype, "ellipsoid", void 0);
  38949. __decorate([
  38950. BABYLON.serializeAsVector3()
  38951. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  38952. __decorate([
  38953. BABYLON.serialize()
  38954. ], FreeCamera.prototype, "checkCollisions", void 0);
  38955. __decorate([
  38956. BABYLON.serialize()
  38957. ], FreeCamera.prototype, "applyGravity", void 0);
  38958. return FreeCamera;
  38959. }(BABYLON.TargetCamera));
  38960. BABYLON.FreeCamera = FreeCamera;
  38961. })(BABYLON || (BABYLON = {}));
  38962. //# sourceMappingURL=babylon.freeCamera.js.map
  38963. var BABYLON;
  38964. (function (BABYLON) {
  38965. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38966. function ArcRotateCameraKeyboardMoveInput() {
  38967. this._keys = new Array();
  38968. this.keysUp = [38];
  38969. this.keysDown = [40];
  38970. this.keysLeft = [37];
  38971. this.keysRight = [39];
  38972. this.keysReset = [220];
  38973. this.panningSensibility = 50.0;
  38974. this.zoomingSensibility = 25.0;
  38975. this.useAltToZoom = true;
  38976. }
  38977. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38978. var _this = this;
  38979. if (this._onCanvasBlurObserver) {
  38980. return;
  38981. }
  38982. this._scene = this.camera.getScene();
  38983. this._engine = this._scene.getEngine();
  38984. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38985. _this._keys = [];
  38986. });
  38987. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38988. var evt = info.event;
  38989. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38990. _this._ctrlPressed = evt.ctrlKey;
  38991. _this._altPressed = evt.altKey;
  38992. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38993. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38994. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38995. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38996. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38997. var index = _this._keys.indexOf(evt.keyCode);
  38998. if (index === -1) {
  38999. _this._keys.push(evt.keyCode);
  39000. }
  39001. if (evt.preventDefault) {
  39002. if (!noPreventDefault) {
  39003. evt.preventDefault();
  39004. }
  39005. }
  39006. }
  39007. }
  39008. else {
  39009. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39010. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39011. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39012. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39013. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39014. var index = _this._keys.indexOf(evt.keyCode);
  39015. if (index >= 0) {
  39016. _this._keys.splice(index, 1);
  39017. }
  39018. if (evt.preventDefault) {
  39019. if (!noPreventDefault) {
  39020. evt.preventDefault();
  39021. }
  39022. }
  39023. }
  39024. }
  39025. });
  39026. };
  39027. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39028. if (this._scene) {
  39029. if (this._onKeyboardObserver) {
  39030. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39031. }
  39032. if (this._onCanvasBlurObserver) {
  39033. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39034. }
  39035. this._onKeyboardObserver = null;
  39036. this._onCanvasBlurObserver = null;
  39037. }
  39038. this._keys = [];
  39039. };
  39040. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39041. if (this._onKeyboardObserver) {
  39042. var camera = this.camera;
  39043. for (var index = 0; index < this._keys.length; index++) {
  39044. var keyCode = this._keys[index];
  39045. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39046. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39047. camera.inertialPanningX -= 1 / this.panningSensibility;
  39048. }
  39049. else {
  39050. camera.inertialAlphaOffset -= 0.01;
  39051. }
  39052. }
  39053. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39054. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39055. camera.inertialPanningY += 1 / this.panningSensibility;
  39056. }
  39057. else if (this._altPressed && this.useAltToZoom) {
  39058. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39059. }
  39060. else {
  39061. camera.inertialBetaOffset -= 0.01;
  39062. }
  39063. }
  39064. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39065. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39066. camera.inertialPanningX += 1 / this.panningSensibility;
  39067. }
  39068. else {
  39069. camera.inertialAlphaOffset += 0.01;
  39070. }
  39071. }
  39072. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39073. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39074. camera.inertialPanningY -= 1 / this.panningSensibility;
  39075. }
  39076. else if (this._altPressed && this.useAltToZoom) {
  39077. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39078. }
  39079. else {
  39080. camera.inertialBetaOffset += 0.01;
  39081. }
  39082. }
  39083. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39084. camera.restoreState();
  39085. }
  39086. }
  39087. }
  39088. };
  39089. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39090. return "ArcRotateCameraKeyboardMoveInput";
  39091. };
  39092. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39093. return "keyboard";
  39094. };
  39095. __decorate([
  39096. BABYLON.serialize()
  39097. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39098. __decorate([
  39099. BABYLON.serialize()
  39100. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39101. __decorate([
  39102. BABYLON.serialize()
  39103. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39104. __decorate([
  39105. BABYLON.serialize()
  39106. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39107. __decorate([
  39108. BABYLON.serialize()
  39109. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39110. __decorate([
  39111. BABYLON.serialize()
  39112. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39113. __decorate([
  39114. BABYLON.serialize()
  39115. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39116. __decorate([
  39117. BABYLON.serialize()
  39118. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39119. return ArcRotateCameraKeyboardMoveInput;
  39120. }());
  39121. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39122. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39123. })(BABYLON || (BABYLON = {}));
  39124. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39125. var BABYLON;
  39126. (function (BABYLON) {
  39127. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39128. function ArcRotateCameraMouseWheelInput() {
  39129. this.wheelPrecision = 3.0;
  39130. /**
  39131. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39132. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39133. */
  39134. this.wheelDeltaPercentage = 0;
  39135. }
  39136. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39137. var _this = this;
  39138. this._wheel = function (p, s) {
  39139. //sanity check - this should be a PointerWheel event.
  39140. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39141. return;
  39142. var event = p.event;
  39143. var delta = 0;
  39144. if (event.wheelDelta) {
  39145. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39146. }
  39147. else if (event.detail) {
  39148. delta = -event.detail / _this.wheelPrecision;
  39149. }
  39150. if (delta)
  39151. _this.camera.inertialRadiusOffset += delta;
  39152. if (event.preventDefault) {
  39153. if (!noPreventDefault) {
  39154. event.preventDefault();
  39155. }
  39156. }
  39157. };
  39158. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39159. };
  39160. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39161. if (this._observer && element) {
  39162. this.camera.getScene().onPointerObservable.remove(this._observer);
  39163. this._observer = null;
  39164. this._wheel = null;
  39165. }
  39166. };
  39167. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39168. return "ArcRotateCameraMouseWheelInput";
  39169. };
  39170. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39171. return "mousewheel";
  39172. };
  39173. __decorate([
  39174. BABYLON.serialize()
  39175. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39176. __decorate([
  39177. BABYLON.serialize()
  39178. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39179. return ArcRotateCameraMouseWheelInput;
  39180. }());
  39181. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39182. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39183. })(BABYLON || (BABYLON = {}));
  39184. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39185. var BABYLON;
  39186. (function (BABYLON) {
  39187. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39188. function ArcRotateCameraPointersInput() {
  39189. this.buttons = [0, 1, 2];
  39190. this.angularSensibilityX = 1000.0;
  39191. this.angularSensibilityY = 1000.0;
  39192. this.pinchPrecision = 12.0;
  39193. /**
  39194. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39195. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39196. */
  39197. this.pinchDeltaPercentage = 0;
  39198. this.panningSensibility = 1000.0;
  39199. this.multiTouchPanning = true;
  39200. this.multiTouchPanAndZoom = true;
  39201. this._isPanClick = false;
  39202. this.pinchInwards = true;
  39203. }
  39204. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39205. var _this = this;
  39206. var engine = this.camera.getEngine();
  39207. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39208. var pointA = null;
  39209. var pointB = null;
  39210. var previousPinchSquaredDistance = 0;
  39211. var initialDistance = 0;
  39212. var twoFingerActivityCount = 0;
  39213. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39214. this._pointerInput = function (p, s) {
  39215. var evt = p.event;
  39216. var isTouch = p.event.pointerType === "touch";
  39217. if (engine.isInVRExclusivePointerMode) {
  39218. return;
  39219. }
  39220. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39221. return;
  39222. }
  39223. var srcElement = (evt.srcElement || evt.target);
  39224. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39225. try {
  39226. srcElement.setPointerCapture(evt.pointerId);
  39227. }
  39228. catch (e) {
  39229. //Nothing to do with the error. Execution will continue.
  39230. }
  39231. // Manage panning with pan button click
  39232. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39233. // manage pointers
  39234. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39235. if (pointA === null) {
  39236. pointA = cacheSoloPointer;
  39237. }
  39238. else if (pointB === null) {
  39239. pointB = cacheSoloPointer;
  39240. }
  39241. if (!noPreventDefault) {
  39242. evt.preventDefault();
  39243. element.focus();
  39244. }
  39245. }
  39246. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39247. _this.camera.restoreState();
  39248. }
  39249. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39250. try {
  39251. srcElement.releasePointerCapture(evt.pointerId);
  39252. }
  39253. catch (e) {
  39254. //Nothing to do with the error.
  39255. }
  39256. cacheSoloPointer = null;
  39257. previousPinchSquaredDistance = 0;
  39258. previousMultiTouchPanPosition.isPaning = false;
  39259. previousMultiTouchPanPosition.isPinching = false;
  39260. twoFingerActivityCount = 0;
  39261. initialDistance = 0;
  39262. if (!isTouch) {
  39263. pointB = null; // Mouse and pen are mono pointer
  39264. }
  39265. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39266. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39267. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39268. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39269. if (engine.badOS) {
  39270. pointA = pointB = null;
  39271. }
  39272. else {
  39273. //only remove the impacted pointer in case of multitouch allowing on most
  39274. //platforms switching from rotate to zoom and pan seamlessly.
  39275. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39276. pointA = pointB;
  39277. pointB = null;
  39278. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39279. }
  39280. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39281. pointB = null;
  39282. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39283. }
  39284. else {
  39285. pointA = pointB = null;
  39286. }
  39287. }
  39288. if (!noPreventDefault) {
  39289. evt.preventDefault();
  39290. }
  39291. }
  39292. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39293. if (!noPreventDefault) {
  39294. evt.preventDefault();
  39295. }
  39296. // One button down
  39297. if (pointA && pointB === null && cacheSoloPointer) {
  39298. if (_this.panningSensibility !== 0 &&
  39299. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39300. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39301. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39302. }
  39303. else {
  39304. var offsetX = evt.clientX - cacheSoloPointer.x;
  39305. var offsetY = evt.clientY - cacheSoloPointer.y;
  39306. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39307. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39308. }
  39309. cacheSoloPointer.x = evt.clientX;
  39310. cacheSoloPointer.y = evt.clientY;
  39311. }
  39312. else if (pointA && pointB) {
  39313. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39314. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39315. ed.x = evt.clientX;
  39316. ed.y = evt.clientY;
  39317. var direction = _this.pinchInwards ? 1 : -1;
  39318. var distX = pointA.x - pointB.x;
  39319. var distY = pointA.y - pointB.y;
  39320. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39321. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39322. if (previousPinchSquaredDistance === 0) {
  39323. initialDistance = pinchDistance;
  39324. previousPinchSquaredDistance = pinchSquaredDistance;
  39325. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39326. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39327. return;
  39328. }
  39329. if (_this.multiTouchPanAndZoom) {
  39330. if (_this.pinchDeltaPercentage) {
  39331. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39332. }
  39333. else {
  39334. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39335. (_this.pinchPrecision *
  39336. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39337. direction);
  39338. }
  39339. if (_this.panningSensibility !== 0) {
  39340. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39341. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39342. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39343. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39344. previousMultiTouchPanPosition.x = pointersCenterX;
  39345. previousMultiTouchPanPosition.y = pointersCenterY;
  39346. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39347. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39348. }
  39349. }
  39350. else {
  39351. twoFingerActivityCount++;
  39352. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39353. if (_this.pinchDeltaPercentage) {
  39354. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39355. }
  39356. else {
  39357. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39358. (_this.pinchPrecision *
  39359. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39360. direction);
  39361. }
  39362. previousMultiTouchPanPosition.isPaning = false;
  39363. previousMultiTouchPanPosition.isPinching = true;
  39364. }
  39365. else {
  39366. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39367. if (!previousMultiTouchPanPosition.isPaning) {
  39368. previousMultiTouchPanPosition.isPaning = true;
  39369. previousMultiTouchPanPosition.isPinching = false;
  39370. previousMultiTouchPanPosition.x = ed.x;
  39371. previousMultiTouchPanPosition.y = ed.y;
  39372. return;
  39373. }
  39374. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39375. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39376. }
  39377. }
  39378. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39379. previousMultiTouchPanPosition.x = ed.x;
  39380. previousMultiTouchPanPosition.y = ed.y;
  39381. }
  39382. }
  39383. previousPinchSquaredDistance = pinchSquaredDistance;
  39384. }
  39385. }
  39386. };
  39387. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39388. this._onContextMenu = function (evt) {
  39389. evt.preventDefault();
  39390. };
  39391. if (!this.camera._useCtrlForPanning) {
  39392. element.addEventListener("contextmenu", this._onContextMenu, false);
  39393. }
  39394. this._onLostFocus = function () {
  39395. //this._keys = [];
  39396. pointA = pointB = null;
  39397. previousPinchSquaredDistance = 0;
  39398. previousMultiTouchPanPosition.isPaning = false;
  39399. previousMultiTouchPanPosition.isPinching = false;
  39400. twoFingerActivityCount = 0;
  39401. cacheSoloPointer = null;
  39402. initialDistance = 0;
  39403. };
  39404. this._onMouseMove = function (evt) {
  39405. if (!engine.isPointerLock) {
  39406. return;
  39407. }
  39408. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39409. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39410. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39411. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39412. if (!noPreventDefault) {
  39413. evt.preventDefault();
  39414. }
  39415. };
  39416. this._onGestureStart = function (e) {
  39417. if (window.MSGesture === undefined) {
  39418. return;
  39419. }
  39420. if (!_this._MSGestureHandler) {
  39421. _this._MSGestureHandler = new MSGesture();
  39422. _this._MSGestureHandler.target = element;
  39423. }
  39424. _this._MSGestureHandler.addPointer(e.pointerId);
  39425. };
  39426. this._onGesture = function (e) {
  39427. _this.camera.radius *= e.scale;
  39428. if (e.preventDefault) {
  39429. if (!noPreventDefault) {
  39430. e.stopPropagation();
  39431. e.preventDefault();
  39432. }
  39433. }
  39434. };
  39435. element.addEventListener("mousemove", this._onMouseMove, false);
  39436. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39437. element.addEventListener("MSGestureChange", this._onGesture, false);
  39438. BABYLON.Tools.RegisterTopRootEvents([
  39439. { name: "blur", handler: this._onLostFocus }
  39440. ]);
  39441. };
  39442. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39443. if (this._onLostFocus) {
  39444. BABYLON.Tools.UnregisterTopRootEvents([
  39445. { name: "blur", handler: this._onLostFocus }
  39446. ]);
  39447. }
  39448. if (element && this._observer) {
  39449. this.camera.getScene().onPointerObservable.remove(this._observer);
  39450. this._observer = null;
  39451. if (this._onContextMenu) {
  39452. element.removeEventListener("contextmenu", this._onContextMenu);
  39453. }
  39454. if (this._onMouseMove) {
  39455. element.removeEventListener("mousemove", this._onMouseMove);
  39456. }
  39457. if (this._onGestureStart) {
  39458. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39459. }
  39460. if (this._onGesture) {
  39461. element.removeEventListener("MSGestureChange", this._onGesture);
  39462. }
  39463. this._isPanClick = false;
  39464. this.pinchInwards = true;
  39465. this._onMouseMove = null;
  39466. this._onGestureStart = null;
  39467. this._onGesture = null;
  39468. this._MSGestureHandler = null;
  39469. this._onLostFocus = null;
  39470. this._onContextMenu = null;
  39471. }
  39472. };
  39473. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39474. return "ArcRotateCameraPointersInput";
  39475. };
  39476. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39477. return "pointers";
  39478. };
  39479. __decorate([
  39480. BABYLON.serialize()
  39481. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39482. __decorate([
  39483. BABYLON.serialize()
  39484. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39485. __decorate([
  39486. BABYLON.serialize()
  39487. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39488. __decorate([
  39489. BABYLON.serialize()
  39490. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39491. __decorate([
  39492. BABYLON.serialize()
  39493. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39494. __decorate([
  39495. BABYLON.serialize()
  39496. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39497. __decorate([
  39498. BABYLON.serialize()
  39499. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39500. __decorate([
  39501. BABYLON.serialize()
  39502. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39503. return ArcRotateCameraPointersInput;
  39504. }());
  39505. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39506. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39507. })(BABYLON || (BABYLON = {}));
  39508. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39509. var BABYLON;
  39510. (function (BABYLON) {
  39511. var ArcRotateCamera = /** @class */ (function (_super) {
  39512. __extends(ArcRotateCamera, _super);
  39513. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39514. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39515. _this.inertialAlphaOffset = 0;
  39516. _this.inertialBetaOffset = 0;
  39517. _this.inertialRadiusOffset = 0;
  39518. _this.lowerAlphaLimit = null;
  39519. _this.upperAlphaLimit = null;
  39520. _this.lowerBetaLimit = 0.01;
  39521. _this.upperBetaLimit = Math.PI;
  39522. _this.lowerRadiusLimit = null;
  39523. _this.upperRadiusLimit = null;
  39524. _this.inertialPanningX = 0;
  39525. _this.inertialPanningY = 0;
  39526. _this.pinchToPanMaxDistance = 20;
  39527. _this.panningDistanceLimit = null;
  39528. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39529. _this.panningInertia = 0.9;
  39530. //-- end properties for backward compatibility for inputs
  39531. _this.zoomOnFactor = 1;
  39532. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39533. _this.allowUpsideDown = true;
  39534. _this._viewMatrix = new BABYLON.Matrix();
  39535. // Panning
  39536. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39537. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39538. _this.checkCollisions = false;
  39539. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39540. _this._previousPosition = BABYLON.Vector3.Zero();
  39541. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39542. _this._newPosition = BABYLON.Vector3.Zero();
  39543. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39544. if (collidedMesh === void 0) { collidedMesh = null; }
  39545. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39546. newPosition.multiplyInPlace(_this._collider._radius);
  39547. }
  39548. if (!collidedMesh) {
  39549. _this._previousPosition.copyFrom(_this.position);
  39550. }
  39551. else {
  39552. _this.setPosition(newPosition);
  39553. if (_this.onCollide) {
  39554. _this.onCollide(collidedMesh);
  39555. }
  39556. }
  39557. // Recompute because of constraints
  39558. var cosa = Math.cos(_this.alpha);
  39559. var sina = Math.sin(_this.alpha);
  39560. var cosb = Math.cos(_this.beta);
  39561. var sinb = Math.sin(_this.beta);
  39562. if (sinb === 0) {
  39563. sinb = 0.0001;
  39564. }
  39565. var target = _this._getTargetPosition();
  39566. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39567. _this.position.copyFrom(_this._newPosition);
  39568. var up = _this.upVector;
  39569. if (_this.allowUpsideDown && _this.beta < 0) {
  39570. up = up.clone();
  39571. up = up.negate();
  39572. }
  39573. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39574. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39575. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39576. _this._collisionTriggered = false;
  39577. };
  39578. _this._target = BABYLON.Vector3.Zero();
  39579. if (target) {
  39580. _this.setTarget(target);
  39581. }
  39582. _this.alpha = alpha;
  39583. _this.beta = beta;
  39584. _this.radius = radius;
  39585. _this.getViewMatrix();
  39586. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39587. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39588. return _this;
  39589. }
  39590. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39591. get: function () {
  39592. return this._target;
  39593. },
  39594. set: function (value) {
  39595. this.setTarget(value);
  39596. },
  39597. enumerable: true,
  39598. configurable: true
  39599. });
  39600. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39601. //-- begin properties for backward compatibility for inputs
  39602. get: function () {
  39603. var pointers = this.inputs.attached["pointers"];
  39604. if (pointers)
  39605. return pointers.angularSensibilityX;
  39606. return 0;
  39607. },
  39608. set: function (value) {
  39609. var pointers = this.inputs.attached["pointers"];
  39610. if (pointers) {
  39611. pointers.angularSensibilityX = value;
  39612. }
  39613. },
  39614. enumerable: true,
  39615. configurable: true
  39616. });
  39617. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39618. get: function () {
  39619. var pointers = this.inputs.attached["pointers"];
  39620. if (pointers)
  39621. return pointers.angularSensibilityY;
  39622. return 0;
  39623. },
  39624. set: function (value) {
  39625. var pointers = this.inputs.attached["pointers"];
  39626. if (pointers) {
  39627. pointers.angularSensibilityY = value;
  39628. }
  39629. },
  39630. enumerable: true,
  39631. configurable: true
  39632. });
  39633. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39634. get: function () {
  39635. var pointers = this.inputs.attached["pointers"];
  39636. if (pointers)
  39637. return pointers.pinchPrecision;
  39638. return 0;
  39639. },
  39640. set: function (value) {
  39641. var pointers = this.inputs.attached["pointers"];
  39642. if (pointers) {
  39643. pointers.pinchPrecision = value;
  39644. }
  39645. },
  39646. enumerable: true,
  39647. configurable: true
  39648. });
  39649. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39650. get: function () {
  39651. var pointers = this.inputs.attached["pointers"];
  39652. if (pointers)
  39653. return pointers.pinchDeltaPercentage;
  39654. return 0;
  39655. },
  39656. set: function (value) {
  39657. var pointers = this.inputs.attached["pointers"];
  39658. if (pointers) {
  39659. pointers.pinchDeltaPercentage = value;
  39660. }
  39661. },
  39662. enumerable: true,
  39663. configurable: true
  39664. });
  39665. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39666. get: function () {
  39667. var pointers = this.inputs.attached["pointers"];
  39668. if (pointers)
  39669. return pointers.panningSensibility;
  39670. return 0;
  39671. },
  39672. set: function (value) {
  39673. var pointers = this.inputs.attached["pointers"];
  39674. if (pointers) {
  39675. pointers.panningSensibility = value;
  39676. }
  39677. },
  39678. enumerable: true,
  39679. configurable: true
  39680. });
  39681. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39682. get: function () {
  39683. var keyboard = this.inputs.attached["keyboard"];
  39684. if (keyboard)
  39685. return keyboard.keysUp;
  39686. return [];
  39687. },
  39688. set: function (value) {
  39689. var keyboard = this.inputs.attached["keyboard"];
  39690. if (keyboard)
  39691. keyboard.keysUp = value;
  39692. },
  39693. enumerable: true,
  39694. configurable: true
  39695. });
  39696. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39697. get: function () {
  39698. var keyboard = this.inputs.attached["keyboard"];
  39699. if (keyboard)
  39700. return keyboard.keysDown;
  39701. return [];
  39702. },
  39703. set: function (value) {
  39704. var keyboard = this.inputs.attached["keyboard"];
  39705. if (keyboard)
  39706. keyboard.keysDown = value;
  39707. },
  39708. enumerable: true,
  39709. configurable: true
  39710. });
  39711. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39712. get: function () {
  39713. var keyboard = this.inputs.attached["keyboard"];
  39714. if (keyboard)
  39715. return keyboard.keysLeft;
  39716. return [];
  39717. },
  39718. set: function (value) {
  39719. var keyboard = this.inputs.attached["keyboard"];
  39720. if (keyboard)
  39721. keyboard.keysLeft = value;
  39722. },
  39723. enumerable: true,
  39724. configurable: true
  39725. });
  39726. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39727. get: function () {
  39728. var keyboard = this.inputs.attached["keyboard"];
  39729. if (keyboard)
  39730. return keyboard.keysRight;
  39731. return [];
  39732. },
  39733. set: function (value) {
  39734. var keyboard = this.inputs.attached["keyboard"];
  39735. if (keyboard)
  39736. keyboard.keysRight = value;
  39737. },
  39738. enumerable: true,
  39739. configurable: true
  39740. });
  39741. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39742. get: function () {
  39743. var mousewheel = this.inputs.attached["mousewheel"];
  39744. if (mousewheel)
  39745. return mousewheel.wheelPrecision;
  39746. return 0;
  39747. },
  39748. set: function (value) {
  39749. var mousewheel = this.inputs.attached["mousewheel"];
  39750. if (mousewheel)
  39751. mousewheel.wheelPrecision = value;
  39752. },
  39753. enumerable: true,
  39754. configurable: true
  39755. });
  39756. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39757. get: function () {
  39758. var mousewheel = this.inputs.attached["mousewheel"];
  39759. if (mousewheel)
  39760. return mousewheel.wheelDeltaPercentage;
  39761. return 0;
  39762. },
  39763. set: function (value) {
  39764. var mousewheel = this.inputs.attached["mousewheel"];
  39765. if (mousewheel)
  39766. mousewheel.wheelDeltaPercentage = value;
  39767. },
  39768. enumerable: true,
  39769. configurable: true
  39770. });
  39771. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39772. get: function () {
  39773. return this._bouncingBehavior;
  39774. },
  39775. enumerable: true,
  39776. configurable: true
  39777. });
  39778. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39779. get: function () {
  39780. return this._bouncingBehavior != null;
  39781. },
  39782. set: function (value) {
  39783. if (value === this.useBouncingBehavior) {
  39784. return;
  39785. }
  39786. if (value) {
  39787. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39788. this.addBehavior(this._bouncingBehavior);
  39789. }
  39790. else if (this._bouncingBehavior) {
  39791. this.removeBehavior(this._bouncingBehavior);
  39792. this._bouncingBehavior = null;
  39793. }
  39794. },
  39795. enumerable: true,
  39796. configurable: true
  39797. });
  39798. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39799. get: function () {
  39800. return this._framingBehavior;
  39801. },
  39802. enumerable: true,
  39803. configurable: true
  39804. });
  39805. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39806. get: function () {
  39807. return this._framingBehavior != null;
  39808. },
  39809. set: function (value) {
  39810. if (value === this.useFramingBehavior) {
  39811. return;
  39812. }
  39813. if (value) {
  39814. this._framingBehavior = new BABYLON.FramingBehavior();
  39815. this.addBehavior(this._framingBehavior);
  39816. }
  39817. else if (this._framingBehavior) {
  39818. this.removeBehavior(this._framingBehavior);
  39819. this._framingBehavior = null;
  39820. }
  39821. },
  39822. enumerable: true,
  39823. configurable: true
  39824. });
  39825. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39826. get: function () {
  39827. return this._autoRotationBehavior;
  39828. },
  39829. enumerable: true,
  39830. configurable: true
  39831. });
  39832. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39833. get: function () {
  39834. return this._autoRotationBehavior != null;
  39835. },
  39836. set: function (value) {
  39837. if (value === this.useAutoRotationBehavior) {
  39838. return;
  39839. }
  39840. if (value) {
  39841. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39842. this.addBehavior(this._autoRotationBehavior);
  39843. }
  39844. else if (this._autoRotationBehavior) {
  39845. this.removeBehavior(this._autoRotationBehavior);
  39846. this._autoRotationBehavior = null;
  39847. }
  39848. },
  39849. enumerable: true,
  39850. configurable: true
  39851. });
  39852. // Cache
  39853. ArcRotateCamera.prototype._initCache = function () {
  39854. _super.prototype._initCache.call(this);
  39855. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39856. this._cache.alpha = undefined;
  39857. this._cache.beta = undefined;
  39858. this._cache.radius = undefined;
  39859. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39860. };
  39861. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39862. if (!ignoreParentClass) {
  39863. _super.prototype._updateCache.call(this);
  39864. }
  39865. this._cache._target.copyFrom(this._getTargetPosition());
  39866. this._cache.alpha = this.alpha;
  39867. this._cache.beta = this.beta;
  39868. this._cache.radius = this.radius;
  39869. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39870. };
  39871. ArcRotateCamera.prototype._getTargetPosition = function () {
  39872. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39873. var pos = this._targetHost.getAbsolutePosition();
  39874. if (this._targetBoundingCenter) {
  39875. pos.addToRef(this._targetBoundingCenter, this._target);
  39876. }
  39877. else {
  39878. this._target.copyFrom(pos);
  39879. }
  39880. }
  39881. var lockedTargetPosition = this._getLockedTargetPosition();
  39882. if (lockedTargetPosition) {
  39883. return lockedTargetPosition;
  39884. }
  39885. return this._target;
  39886. };
  39887. ArcRotateCamera.prototype.storeState = function () {
  39888. this._storedAlpha = this.alpha;
  39889. this._storedBeta = this.beta;
  39890. this._storedRadius = this.radius;
  39891. this._storedTarget = this._getTargetPosition().clone();
  39892. return _super.prototype.storeState.call(this);
  39893. };
  39894. /**
  39895. * Restored camera state. You must call storeState() first
  39896. */
  39897. ArcRotateCamera.prototype._restoreStateValues = function () {
  39898. if (!_super.prototype._restoreStateValues.call(this)) {
  39899. return false;
  39900. }
  39901. this.alpha = this._storedAlpha;
  39902. this.beta = this._storedBeta;
  39903. this.radius = this._storedRadius;
  39904. this.setTarget(this._storedTarget.clone());
  39905. this.inertialAlphaOffset = 0;
  39906. this.inertialBetaOffset = 0;
  39907. this.inertialRadiusOffset = 0;
  39908. this.inertialPanningX = 0;
  39909. this.inertialPanningY = 0;
  39910. return true;
  39911. };
  39912. // Synchronized
  39913. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39914. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39915. return false;
  39916. return this._cache._target.equals(this._getTargetPosition())
  39917. && this._cache.alpha === this.alpha
  39918. && this._cache.beta === this.beta
  39919. && this._cache.radius === this.radius
  39920. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39921. };
  39922. // Methods
  39923. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39924. var _this = this;
  39925. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39926. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39927. this._useCtrlForPanning = useCtrlForPanning;
  39928. this._panningMouseButton = panningMouseButton;
  39929. this.inputs.attachElement(element, noPreventDefault);
  39930. this._reset = function () {
  39931. _this.inertialAlphaOffset = 0;
  39932. _this.inertialBetaOffset = 0;
  39933. _this.inertialRadiusOffset = 0;
  39934. _this.inertialPanningX = 0;
  39935. _this.inertialPanningY = 0;
  39936. };
  39937. };
  39938. ArcRotateCamera.prototype.detachControl = function (element) {
  39939. this.inputs.detachElement(element);
  39940. if (this._reset) {
  39941. this._reset();
  39942. }
  39943. };
  39944. ArcRotateCamera.prototype._checkInputs = function () {
  39945. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39946. if (this._collisionTriggered) {
  39947. return;
  39948. }
  39949. this.inputs.checkInputs();
  39950. // Inertia
  39951. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39952. if (this.getScene().useRightHandedSystem) {
  39953. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39954. }
  39955. else {
  39956. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39957. }
  39958. this.beta += this.inertialBetaOffset;
  39959. this.radius -= this.inertialRadiusOffset;
  39960. this.inertialAlphaOffset *= this.inertia;
  39961. this.inertialBetaOffset *= this.inertia;
  39962. this.inertialRadiusOffset *= this.inertia;
  39963. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39964. this.inertialAlphaOffset = 0;
  39965. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39966. this.inertialBetaOffset = 0;
  39967. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39968. this.inertialRadiusOffset = 0;
  39969. }
  39970. // Panning inertia
  39971. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39972. if (!this._localDirection) {
  39973. this._localDirection = BABYLON.Vector3.Zero();
  39974. this._transformedDirection = BABYLON.Vector3.Zero();
  39975. }
  39976. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39977. this._localDirection.multiplyInPlace(this.panningAxis);
  39978. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39979. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39980. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39981. if (!this.panningAxis.y) {
  39982. this._transformedDirection.y = 0;
  39983. }
  39984. if (!this._targetHost) {
  39985. if (this.panningDistanceLimit) {
  39986. this._transformedDirection.addInPlace(this._target);
  39987. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39988. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39989. this._target.copyFrom(this._transformedDirection);
  39990. }
  39991. }
  39992. else {
  39993. this._target.addInPlace(this._transformedDirection);
  39994. }
  39995. }
  39996. this.inertialPanningX *= this.panningInertia;
  39997. this.inertialPanningY *= this.panningInertia;
  39998. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39999. this.inertialPanningX = 0;
  40000. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40001. this.inertialPanningY = 0;
  40002. }
  40003. // Limits
  40004. this._checkLimits();
  40005. _super.prototype._checkInputs.call(this);
  40006. };
  40007. ArcRotateCamera.prototype._checkLimits = function () {
  40008. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40009. if (this.allowUpsideDown && this.beta > Math.PI) {
  40010. this.beta = this.beta - (2 * Math.PI);
  40011. }
  40012. }
  40013. else {
  40014. if (this.beta < this.lowerBetaLimit) {
  40015. this.beta = this.lowerBetaLimit;
  40016. }
  40017. }
  40018. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40019. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40020. this.beta = this.beta + (2 * Math.PI);
  40021. }
  40022. }
  40023. else {
  40024. if (this.beta > this.upperBetaLimit) {
  40025. this.beta = this.upperBetaLimit;
  40026. }
  40027. }
  40028. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40029. this.alpha = this.lowerAlphaLimit;
  40030. }
  40031. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40032. this.alpha = this.upperAlphaLimit;
  40033. }
  40034. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40035. this.radius = this.lowerRadiusLimit;
  40036. }
  40037. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40038. this.radius = this.upperRadiusLimit;
  40039. }
  40040. };
  40041. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40042. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40043. this.radius = radiusv3.length();
  40044. if (this.radius === 0) {
  40045. this.radius = 0.0001; // Just to avoid division by zero
  40046. }
  40047. // Alpha
  40048. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40049. if (radiusv3.z < 0) {
  40050. this.alpha = 2 * Math.PI - this.alpha;
  40051. }
  40052. // Beta
  40053. this.beta = Math.acos(radiusv3.y / this.radius);
  40054. this._checkLimits();
  40055. };
  40056. ArcRotateCamera.prototype.setPosition = function (position) {
  40057. if (this.position.equals(position)) {
  40058. return;
  40059. }
  40060. this.position.copyFrom(position);
  40061. this.rebuildAnglesAndRadius();
  40062. };
  40063. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40064. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40065. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40066. if (target.getBoundingInfo) {
  40067. if (toBoundingCenter) {
  40068. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40069. }
  40070. else {
  40071. this._targetBoundingCenter = null;
  40072. }
  40073. this._targetHost = target;
  40074. this._target = this._getTargetPosition();
  40075. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40076. }
  40077. else {
  40078. var newTarget = target;
  40079. var currentTarget = this._getTargetPosition();
  40080. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40081. return;
  40082. }
  40083. this._targetHost = null;
  40084. this._target = newTarget;
  40085. this._targetBoundingCenter = null;
  40086. this.onMeshTargetChangedObservable.notifyObservers(null);
  40087. }
  40088. this.rebuildAnglesAndRadius();
  40089. };
  40090. ArcRotateCamera.prototype._getViewMatrix = function () {
  40091. // Compute
  40092. var cosa = Math.cos(this.alpha);
  40093. var sina = Math.sin(this.alpha);
  40094. var cosb = Math.cos(this.beta);
  40095. var sinb = Math.sin(this.beta);
  40096. if (sinb === 0) {
  40097. sinb = 0.0001;
  40098. }
  40099. var target = this._getTargetPosition();
  40100. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40101. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40102. if (!this._collider) {
  40103. this._collider = new BABYLON.Collider();
  40104. }
  40105. this._collider._radius = this.collisionRadius;
  40106. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40107. this._collisionTriggered = true;
  40108. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40109. }
  40110. else {
  40111. this.position.copyFrom(this._newPosition);
  40112. var up = this.upVector;
  40113. if (this.allowUpsideDown && sinb < 0) {
  40114. up = up.clone();
  40115. up = up.negate();
  40116. }
  40117. if (this.getScene().useRightHandedSystem) {
  40118. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40119. }
  40120. else {
  40121. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40122. }
  40123. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40124. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40125. }
  40126. this._currentTarget = target;
  40127. return this._viewMatrix;
  40128. };
  40129. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40130. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40131. meshes = meshes || this.getScene().meshes;
  40132. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40133. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40134. this.radius = distance * this.zoomOnFactor;
  40135. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40136. };
  40137. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40138. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40139. var meshesOrMinMaxVector;
  40140. var distance;
  40141. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40142. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40143. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40144. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40145. }
  40146. else {
  40147. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40148. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40149. distance = minMaxVectorAndDistance.distance;
  40150. }
  40151. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40152. if (!doNotUpdateMaxZ) {
  40153. this.maxZ = distance * 2;
  40154. }
  40155. };
  40156. /**
  40157. * @override
  40158. * Override Camera.createRigCamera
  40159. */
  40160. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40161. var alphaShift = 0;
  40162. switch (this.cameraRigMode) {
  40163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40166. case BABYLON.Camera.RIG_MODE_VR:
  40167. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40168. break;
  40169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40170. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40171. break;
  40172. }
  40173. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40174. rigCam._cameraRigParams = {};
  40175. return rigCam;
  40176. };
  40177. /**
  40178. * @override
  40179. * Override Camera._updateRigCameras
  40180. */
  40181. ArcRotateCamera.prototype._updateRigCameras = function () {
  40182. var camLeft = this._rigCameras[0];
  40183. var camRight = this._rigCameras[1];
  40184. camLeft.beta = camRight.beta = this.beta;
  40185. camLeft.radius = camRight.radius = this.radius;
  40186. switch (this.cameraRigMode) {
  40187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40190. case BABYLON.Camera.RIG_MODE_VR:
  40191. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40192. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40193. break;
  40194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40195. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40196. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40197. break;
  40198. }
  40199. _super.prototype._updateRigCameras.call(this);
  40200. };
  40201. ArcRotateCamera.prototype.dispose = function () {
  40202. this.inputs.clear();
  40203. _super.prototype.dispose.call(this);
  40204. };
  40205. ArcRotateCamera.prototype.getClassName = function () {
  40206. return "ArcRotateCamera";
  40207. };
  40208. __decorate([
  40209. BABYLON.serialize()
  40210. ], ArcRotateCamera.prototype, "alpha", void 0);
  40211. __decorate([
  40212. BABYLON.serialize()
  40213. ], ArcRotateCamera.prototype, "beta", void 0);
  40214. __decorate([
  40215. BABYLON.serialize()
  40216. ], ArcRotateCamera.prototype, "radius", void 0);
  40217. __decorate([
  40218. BABYLON.serializeAsVector3("target")
  40219. ], ArcRotateCamera.prototype, "_target", void 0);
  40220. __decorate([
  40221. BABYLON.serialize()
  40222. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40223. __decorate([
  40224. BABYLON.serialize()
  40225. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40226. __decorate([
  40227. BABYLON.serialize()
  40228. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40229. __decorate([
  40230. BABYLON.serialize()
  40231. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40232. __decorate([
  40233. BABYLON.serialize()
  40234. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40235. __decorate([
  40236. BABYLON.serialize()
  40237. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40238. __decorate([
  40239. BABYLON.serialize()
  40240. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40241. __decorate([
  40242. BABYLON.serialize()
  40243. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40244. __decorate([
  40245. BABYLON.serialize()
  40246. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40247. __decorate([
  40248. BABYLON.serialize()
  40249. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40250. __decorate([
  40251. BABYLON.serialize()
  40252. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40253. __decorate([
  40254. BABYLON.serialize()
  40255. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40256. __decorate([
  40257. BABYLON.serialize()
  40258. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40259. __decorate([
  40260. BABYLON.serializeAsVector3()
  40261. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40262. __decorate([
  40263. BABYLON.serialize()
  40264. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40265. __decorate([
  40266. BABYLON.serialize()
  40267. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40268. __decorate([
  40269. BABYLON.serialize()
  40270. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40271. return ArcRotateCamera;
  40272. }(BABYLON.TargetCamera));
  40273. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40274. })(BABYLON || (BABYLON = {}));
  40275. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40276. var BABYLON;
  40277. (function (BABYLON) {
  40278. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40279. __extends(ArcRotateCameraInputsManager, _super);
  40280. function ArcRotateCameraInputsManager(camera) {
  40281. return _super.call(this, camera) || this;
  40282. }
  40283. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40284. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40285. return this;
  40286. };
  40287. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40288. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40289. return this;
  40290. };
  40291. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40292. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40293. return this;
  40294. };
  40295. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40296. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40297. return this;
  40298. };
  40299. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40300. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40301. return this;
  40302. };
  40303. return ArcRotateCameraInputsManager;
  40304. }(BABYLON.CameraInputsManager));
  40305. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40306. })(BABYLON || (BABYLON = {}));
  40307. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40308. var BABYLON;
  40309. (function (BABYLON) {
  40310. var HemisphericLight = /** @class */ (function (_super) {
  40311. __extends(HemisphericLight, _super);
  40312. /**
  40313. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40314. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40315. * The HemisphericLight can't cast shadows.
  40316. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40317. */
  40318. function HemisphericLight(name, direction, scene) {
  40319. var _this = _super.call(this, name, scene) || this;
  40320. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40321. _this.direction = direction || BABYLON.Vector3.Up();
  40322. return _this;
  40323. }
  40324. HemisphericLight.prototype._buildUniformLayout = function () {
  40325. this._uniformBuffer.addUniform("vLightData", 4);
  40326. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40327. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40328. this._uniformBuffer.addUniform("vLightGround", 3);
  40329. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40330. this._uniformBuffer.addUniform("depthValues", 2);
  40331. this._uniformBuffer.create();
  40332. };
  40333. /**
  40334. * Returns the string "HemisphericLight".
  40335. */
  40336. HemisphericLight.prototype.getClassName = function () {
  40337. return "HemisphericLight";
  40338. };
  40339. /**
  40340. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40341. * Returns the updated direction.
  40342. */
  40343. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40344. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40345. return this.direction;
  40346. };
  40347. HemisphericLight.prototype.getShadowGenerator = function () {
  40348. return null;
  40349. };
  40350. /**
  40351. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40352. * Returns the HemisphericLight.
  40353. */
  40354. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40355. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40356. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40357. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40358. return this;
  40359. };
  40360. HemisphericLight.prototype._getWorldMatrix = function () {
  40361. if (!this._worldMatrix) {
  40362. this._worldMatrix = BABYLON.Matrix.Identity();
  40363. }
  40364. return this._worldMatrix;
  40365. };
  40366. /**
  40367. * Returns the integer 3.
  40368. */
  40369. HemisphericLight.prototype.getTypeID = function () {
  40370. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40371. };
  40372. __decorate([
  40373. BABYLON.serializeAsColor3()
  40374. ], HemisphericLight.prototype, "groundColor", void 0);
  40375. __decorate([
  40376. BABYLON.serializeAsVector3()
  40377. ], HemisphericLight.prototype, "direction", void 0);
  40378. return HemisphericLight;
  40379. }(BABYLON.Light));
  40380. BABYLON.HemisphericLight = HemisphericLight;
  40381. })(BABYLON || (BABYLON = {}));
  40382. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40383. var BABYLON;
  40384. (function (BABYLON) {
  40385. var ShadowLight = /** @class */ (function (_super) {
  40386. __extends(ShadowLight, _super);
  40387. function ShadowLight() {
  40388. var _this = _super !== null && _super.apply(this, arguments) || this;
  40389. _this._needProjectionMatrixCompute = true;
  40390. return _this;
  40391. }
  40392. Object.defineProperty(ShadowLight.prototype, "direction", {
  40393. get: function () {
  40394. return this._direction;
  40395. },
  40396. set: function (value) {
  40397. this._direction = value;
  40398. },
  40399. enumerable: true,
  40400. configurable: true
  40401. });
  40402. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40403. get: function () {
  40404. return this._shadowMinZ;
  40405. },
  40406. set: function (value) {
  40407. this._shadowMinZ = value;
  40408. this.forceProjectionMatrixCompute();
  40409. },
  40410. enumerable: true,
  40411. configurable: true
  40412. });
  40413. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40414. get: function () {
  40415. return this._shadowMaxZ;
  40416. },
  40417. set: function (value) {
  40418. this._shadowMaxZ = value;
  40419. this.forceProjectionMatrixCompute();
  40420. },
  40421. enumerable: true,
  40422. configurable: true
  40423. });
  40424. /**
  40425. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40426. */
  40427. ShadowLight.prototype.computeTransformedInformation = function () {
  40428. if (this.parent && this.parent.getWorldMatrix) {
  40429. if (!this.transformedPosition) {
  40430. this.transformedPosition = BABYLON.Vector3.Zero();
  40431. }
  40432. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40433. // In case the direction is present.
  40434. if (this.direction) {
  40435. if (!this.transformedDirection) {
  40436. this.transformedDirection = BABYLON.Vector3.Zero();
  40437. }
  40438. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40439. }
  40440. return true;
  40441. }
  40442. return false;
  40443. };
  40444. /**
  40445. * Return the depth scale used for the shadow map.
  40446. */
  40447. ShadowLight.prototype.getDepthScale = function () {
  40448. return 50.0;
  40449. };
  40450. /**
  40451. * Returns the light direction (Vector3) for any passed face index.
  40452. */
  40453. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40454. return this.transformedDirection ? this.transformedDirection : this.direction;
  40455. };
  40456. /**
  40457. * Returns the DirectionalLight absolute position in the World.
  40458. */
  40459. ShadowLight.prototype.getAbsolutePosition = function () {
  40460. return this.transformedPosition ? this.transformedPosition : this.position;
  40461. };
  40462. /**
  40463. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40464. * Returns the updated DirectionalLight direction (Vector3).
  40465. */
  40466. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40467. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40468. return this.direction;
  40469. };
  40470. /**
  40471. * Returns the light rotation (Vector3).
  40472. */
  40473. ShadowLight.prototype.getRotation = function () {
  40474. this.direction.normalize();
  40475. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40476. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40477. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40478. };
  40479. /**
  40480. * Boolean : false by default.
  40481. */
  40482. ShadowLight.prototype.needCube = function () {
  40483. return false;
  40484. };
  40485. /**
  40486. * Specifies wether or not the projection matrix should be recomputed this frame.
  40487. */
  40488. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40489. return this._needProjectionMatrixCompute;
  40490. };
  40491. /**
  40492. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40493. */
  40494. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40495. this._needProjectionMatrixCompute = true;
  40496. };
  40497. /**
  40498. * Get the world matrix of the sahdow lights.
  40499. */
  40500. ShadowLight.prototype._getWorldMatrix = function () {
  40501. if (!this._worldMatrix) {
  40502. this._worldMatrix = BABYLON.Matrix.Identity();
  40503. }
  40504. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40505. return this._worldMatrix;
  40506. };
  40507. /**
  40508. * Gets the minZ used for shadow according to both the scene and the light.
  40509. * @param activeCamera
  40510. */
  40511. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40512. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40513. };
  40514. /**
  40515. * Gets the maxZ used for shadow according to both the scene and the light.
  40516. * @param activeCamera
  40517. */
  40518. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40519. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40520. };
  40521. /**
  40522. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40523. * Returns the light.
  40524. */
  40525. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40526. if (this.customProjectionMatrixBuilder) {
  40527. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40528. }
  40529. else {
  40530. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40531. }
  40532. return this;
  40533. };
  40534. __decorate([
  40535. BABYLON.serializeAsVector3()
  40536. ], ShadowLight.prototype, "position", void 0);
  40537. __decorate([
  40538. BABYLON.serializeAsVector3()
  40539. ], ShadowLight.prototype, "direction", null);
  40540. __decorate([
  40541. BABYLON.serialize()
  40542. ], ShadowLight.prototype, "shadowMinZ", null);
  40543. __decorate([
  40544. BABYLON.serialize()
  40545. ], ShadowLight.prototype, "shadowMaxZ", null);
  40546. return ShadowLight;
  40547. }(BABYLON.Light));
  40548. BABYLON.ShadowLight = ShadowLight;
  40549. })(BABYLON || (BABYLON = {}));
  40550. //# sourceMappingURL=babylon.shadowLight.js.map
  40551. var BABYLON;
  40552. (function (BABYLON) {
  40553. var PointLight = /** @class */ (function (_super) {
  40554. __extends(PointLight, _super);
  40555. /**
  40556. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40557. * A PointLight emits the light in every direction.
  40558. * It can cast shadows.
  40559. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40560. * ```javascript
  40561. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40562. * ```
  40563. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40564. */
  40565. function PointLight(name, position, scene) {
  40566. var _this = _super.call(this, name, scene) || this;
  40567. _this._shadowAngle = Math.PI / 2;
  40568. _this.position = position;
  40569. return _this;
  40570. }
  40571. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40572. /**
  40573. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40574. * This specifies what angle the shadow will use to be created.
  40575. *
  40576. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40577. */
  40578. get: function () {
  40579. return this._shadowAngle;
  40580. },
  40581. /**
  40582. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40583. * This specifies what angle the shadow will use to be created.
  40584. *
  40585. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40586. */
  40587. set: function (value) {
  40588. this._shadowAngle = value;
  40589. this.forceProjectionMatrixCompute();
  40590. },
  40591. enumerable: true,
  40592. configurable: true
  40593. });
  40594. Object.defineProperty(PointLight.prototype, "direction", {
  40595. get: function () {
  40596. return this._direction;
  40597. },
  40598. /**
  40599. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40600. */
  40601. set: function (value) {
  40602. var previousNeedCube = this.needCube();
  40603. this._direction = value;
  40604. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40605. this._shadowGenerator.recreateShadowMap();
  40606. }
  40607. },
  40608. enumerable: true,
  40609. configurable: true
  40610. });
  40611. /**
  40612. * Returns the string "PointLight"
  40613. */
  40614. PointLight.prototype.getClassName = function () {
  40615. return "PointLight";
  40616. };
  40617. /**
  40618. * Returns the integer 0.
  40619. */
  40620. PointLight.prototype.getTypeID = function () {
  40621. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40622. };
  40623. /**
  40624. * Specifies wether or not the shadowmap should be a cube texture.
  40625. */
  40626. PointLight.prototype.needCube = function () {
  40627. return !this.direction;
  40628. };
  40629. /**
  40630. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40631. */
  40632. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40633. if (this.direction) {
  40634. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40635. }
  40636. else {
  40637. switch (faceIndex) {
  40638. case 0:
  40639. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40640. case 1:
  40641. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40642. case 2:
  40643. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40644. case 3:
  40645. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40646. case 4:
  40647. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40648. case 5:
  40649. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40650. }
  40651. }
  40652. return BABYLON.Vector3.Zero();
  40653. };
  40654. /**
  40655. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40656. * - fov = PI / 2
  40657. * - aspect ratio : 1.0
  40658. * - z-near and far equal to the active camera minZ and maxZ.
  40659. * Returns the PointLight.
  40660. */
  40661. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40662. var activeCamera = this.getScene().activeCamera;
  40663. if (!activeCamera) {
  40664. return;
  40665. }
  40666. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40667. };
  40668. PointLight.prototype._buildUniformLayout = function () {
  40669. this._uniformBuffer.addUniform("vLightData", 4);
  40670. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40671. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40672. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40673. this._uniformBuffer.addUniform("depthValues", 2);
  40674. this._uniformBuffer.create();
  40675. };
  40676. /**
  40677. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40678. * Returns the PointLight.
  40679. */
  40680. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40681. if (this.computeTransformedInformation()) {
  40682. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40683. return this;
  40684. }
  40685. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40686. return this;
  40687. };
  40688. __decorate([
  40689. BABYLON.serialize()
  40690. ], PointLight.prototype, "shadowAngle", null);
  40691. return PointLight;
  40692. }(BABYLON.ShadowLight));
  40693. BABYLON.PointLight = PointLight;
  40694. })(BABYLON || (BABYLON = {}));
  40695. //# sourceMappingURL=babylon.pointLight.js.map
  40696. var BABYLON;
  40697. (function (BABYLON) {
  40698. var DirectionalLight = /** @class */ (function (_super) {
  40699. __extends(DirectionalLight, _super);
  40700. /**
  40701. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40702. * The directional light is emitted from everywhere in the given direction.
  40703. * It can cast shawdows.
  40704. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40705. */
  40706. function DirectionalLight(name, direction, scene) {
  40707. var _this = _super.call(this, name, scene) || this;
  40708. _this._shadowFrustumSize = 0;
  40709. _this._shadowOrthoScale = 0.5;
  40710. _this.autoUpdateExtends = true;
  40711. // Cache
  40712. _this._orthoLeft = Number.MAX_VALUE;
  40713. _this._orthoRight = Number.MIN_VALUE;
  40714. _this._orthoTop = Number.MIN_VALUE;
  40715. _this._orthoBottom = Number.MAX_VALUE;
  40716. _this.position = direction.scale(-1.0);
  40717. _this.direction = direction;
  40718. return _this;
  40719. }
  40720. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40721. /**
  40722. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40723. */
  40724. get: function () {
  40725. return this._shadowFrustumSize;
  40726. },
  40727. /**
  40728. * Specifies a fix frustum size for the shadow generation.
  40729. */
  40730. set: function (value) {
  40731. this._shadowFrustumSize = value;
  40732. this.forceProjectionMatrixCompute();
  40733. },
  40734. enumerable: true,
  40735. configurable: true
  40736. });
  40737. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40738. get: function () {
  40739. return this._shadowOrthoScale;
  40740. },
  40741. set: function (value) {
  40742. this._shadowOrthoScale = value;
  40743. this.forceProjectionMatrixCompute();
  40744. },
  40745. enumerable: true,
  40746. configurable: true
  40747. });
  40748. /**
  40749. * Returns the string "DirectionalLight".
  40750. */
  40751. DirectionalLight.prototype.getClassName = function () {
  40752. return "DirectionalLight";
  40753. };
  40754. /**
  40755. * Returns the integer 1.
  40756. */
  40757. DirectionalLight.prototype.getTypeID = function () {
  40758. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40759. };
  40760. /**
  40761. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40762. * Returns the DirectionalLight Shadow projection matrix.
  40763. */
  40764. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40765. if (this.shadowFrustumSize > 0) {
  40766. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40767. }
  40768. else {
  40769. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40770. }
  40771. };
  40772. /**
  40773. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40774. * Returns the DirectionalLight Shadow projection matrix.
  40775. */
  40776. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40777. var activeCamera = this.getScene().activeCamera;
  40778. if (!activeCamera) {
  40779. return;
  40780. }
  40781. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40782. };
  40783. /**
  40784. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40785. * Returns the DirectionalLight Shadow projection matrix.
  40786. */
  40787. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40788. var activeCamera = this.getScene().activeCamera;
  40789. if (!activeCamera) {
  40790. return;
  40791. }
  40792. // Check extends
  40793. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40794. var tempVector3 = BABYLON.Vector3.Zero();
  40795. this._orthoLeft = Number.MAX_VALUE;
  40796. this._orthoRight = Number.MIN_VALUE;
  40797. this._orthoTop = Number.MIN_VALUE;
  40798. this._orthoBottom = Number.MAX_VALUE;
  40799. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40800. var mesh = renderList[meshIndex];
  40801. if (!mesh) {
  40802. continue;
  40803. }
  40804. var boundingInfo = mesh.getBoundingInfo();
  40805. var boundingBox = boundingInfo.boundingBox;
  40806. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40807. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40808. if (tempVector3.x < this._orthoLeft)
  40809. this._orthoLeft = tempVector3.x;
  40810. if (tempVector3.y < this._orthoBottom)
  40811. this._orthoBottom = tempVector3.y;
  40812. if (tempVector3.x > this._orthoRight)
  40813. this._orthoRight = tempVector3.x;
  40814. if (tempVector3.y > this._orthoTop)
  40815. this._orthoTop = tempVector3.y;
  40816. }
  40817. }
  40818. }
  40819. var xOffset = this._orthoRight - this._orthoLeft;
  40820. var yOffset = this._orthoTop - this._orthoBottom;
  40821. 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);
  40822. };
  40823. DirectionalLight.prototype._buildUniformLayout = function () {
  40824. this._uniformBuffer.addUniform("vLightData", 4);
  40825. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40826. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40827. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40828. this._uniformBuffer.addUniform("depthValues", 2);
  40829. this._uniformBuffer.create();
  40830. };
  40831. /**
  40832. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40833. * Returns the DirectionalLight.
  40834. */
  40835. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40836. if (this.computeTransformedInformation()) {
  40837. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40838. return this;
  40839. }
  40840. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40841. return this;
  40842. };
  40843. /**
  40844. * Gets the minZ used for shadow according to both the scene and the light.
  40845. *
  40846. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40847. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40848. * @param activeCamera
  40849. */
  40850. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40851. return 1;
  40852. };
  40853. /**
  40854. * Gets the maxZ used for shadow according to both the scene and the light.
  40855. *
  40856. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40857. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40858. * @param activeCamera
  40859. */
  40860. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40861. return 1;
  40862. };
  40863. __decorate([
  40864. BABYLON.serialize()
  40865. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40866. __decorate([
  40867. BABYLON.serialize()
  40868. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40869. __decorate([
  40870. BABYLON.serialize()
  40871. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40872. return DirectionalLight;
  40873. }(BABYLON.ShadowLight));
  40874. BABYLON.DirectionalLight = DirectionalLight;
  40875. })(BABYLON || (BABYLON = {}));
  40876. //# sourceMappingURL=babylon.directionalLight.js.map
  40877. var BABYLON;
  40878. (function (BABYLON) {
  40879. var SpotLight = /** @class */ (function (_super) {
  40880. __extends(SpotLight, _super);
  40881. /**
  40882. * Creates a SpotLight object in the scene with the passed parameters :
  40883. * - `position` (Vector3) is the initial SpotLight position,
  40884. * - `direction` (Vector3) is the initial SpotLight direction,
  40885. * - `angle` (float, in radians) is the spot light cone angle,
  40886. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40887. * A spot light is a simply light oriented cone.
  40888. * It can cast shadows.
  40889. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40890. */
  40891. function SpotLight(name, position, direction, angle, exponent, scene) {
  40892. var _this = _super.call(this, name, scene) || this;
  40893. _this.position = position;
  40894. _this.direction = direction;
  40895. _this.angle = angle;
  40896. _this.exponent = exponent;
  40897. return _this;
  40898. }
  40899. Object.defineProperty(SpotLight.prototype, "angle", {
  40900. get: function () {
  40901. return this._angle;
  40902. },
  40903. set: function (value) {
  40904. this._angle = value;
  40905. this.forceProjectionMatrixCompute();
  40906. },
  40907. enumerable: true,
  40908. configurable: true
  40909. });
  40910. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40911. get: function () {
  40912. return this._shadowAngleScale;
  40913. },
  40914. /**
  40915. * Allows scaling the angle of the light for shadow generation only.
  40916. */
  40917. set: function (value) {
  40918. this._shadowAngleScale = value;
  40919. this.forceProjectionMatrixCompute();
  40920. },
  40921. enumerable: true,
  40922. configurable: true
  40923. });
  40924. /**
  40925. * Returns the string "SpotLight".
  40926. */
  40927. SpotLight.prototype.getClassName = function () {
  40928. return "SpotLight";
  40929. };
  40930. /**
  40931. * Returns the integer 2.
  40932. */
  40933. SpotLight.prototype.getTypeID = function () {
  40934. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40935. };
  40936. /**
  40937. * 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.
  40938. * Returns the SpotLight.
  40939. */
  40940. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40941. var activeCamera = this.getScene().activeCamera;
  40942. if (!activeCamera) {
  40943. return;
  40944. }
  40945. this._shadowAngleScale = this._shadowAngleScale || 1;
  40946. var angle = this._shadowAngleScale * this._angle;
  40947. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40948. };
  40949. SpotLight.prototype._buildUniformLayout = function () {
  40950. this._uniformBuffer.addUniform("vLightData", 4);
  40951. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40952. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40953. this._uniformBuffer.addUniform("vLightDirection", 3);
  40954. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40955. this._uniformBuffer.addUniform("depthValues", 2);
  40956. this._uniformBuffer.create();
  40957. };
  40958. /**
  40959. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40960. * Return the SpotLight.
  40961. */
  40962. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40963. var normalizeDirection;
  40964. if (this.computeTransformedInformation()) {
  40965. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40966. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40967. }
  40968. else {
  40969. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40970. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40971. }
  40972. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40973. return this;
  40974. };
  40975. __decorate([
  40976. BABYLON.serialize()
  40977. ], SpotLight.prototype, "angle", null);
  40978. __decorate([
  40979. BABYLON.serialize()
  40980. /**
  40981. * Allows scaling the angle of the light for shadow generation only.
  40982. */
  40983. ], SpotLight.prototype, "shadowAngleScale", null);
  40984. __decorate([
  40985. BABYLON.serialize()
  40986. ], SpotLight.prototype, "exponent", void 0);
  40987. return SpotLight;
  40988. }(BABYLON.ShadowLight));
  40989. BABYLON.SpotLight = SpotLight;
  40990. })(BABYLON || (BABYLON = {}));
  40991. //# sourceMappingURL=babylon.spotLight.js.map
  40992. var BABYLON;
  40993. (function (BABYLON) {
  40994. var AnimationRange = /** @class */ (function () {
  40995. function AnimationRange(name, from, to) {
  40996. this.name = name;
  40997. this.from = from;
  40998. this.to = to;
  40999. }
  41000. AnimationRange.prototype.clone = function () {
  41001. return new AnimationRange(this.name, this.from, this.to);
  41002. };
  41003. return AnimationRange;
  41004. }());
  41005. BABYLON.AnimationRange = AnimationRange;
  41006. /**
  41007. * Composed of a frame, and an action function
  41008. */
  41009. var AnimationEvent = /** @class */ (function () {
  41010. function AnimationEvent(frame, action, onlyOnce) {
  41011. this.frame = frame;
  41012. this.action = action;
  41013. this.onlyOnce = onlyOnce;
  41014. this.isDone = false;
  41015. }
  41016. return AnimationEvent;
  41017. }());
  41018. BABYLON.AnimationEvent = AnimationEvent;
  41019. var PathCursor = /** @class */ (function () {
  41020. function PathCursor(path) {
  41021. this.path = path;
  41022. this._onchange = new Array();
  41023. this.value = 0;
  41024. this.animations = new Array();
  41025. }
  41026. PathCursor.prototype.getPoint = function () {
  41027. var point = this.path.getPointAtLengthPosition(this.value);
  41028. return new BABYLON.Vector3(point.x, 0, point.y);
  41029. };
  41030. PathCursor.prototype.moveAhead = function (step) {
  41031. if (step === void 0) { step = 0.002; }
  41032. this.move(step);
  41033. return this;
  41034. };
  41035. PathCursor.prototype.moveBack = function (step) {
  41036. if (step === void 0) { step = 0.002; }
  41037. this.move(-step);
  41038. return this;
  41039. };
  41040. PathCursor.prototype.move = function (step) {
  41041. if (Math.abs(step) > 1) {
  41042. throw "step size should be less than 1.";
  41043. }
  41044. this.value += step;
  41045. this.ensureLimits();
  41046. this.raiseOnChange();
  41047. return this;
  41048. };
  41049. PathCursor.prototype.ensureLimits = function () {
  41050. while (this.value > 1) {
  41051. this.value -= 1;
  41052. }
  41053. while (this.value < 0) {
  41054. this.value += 1;
  41055. }
  41056. return this;
  41057. };
  41058. // used by animation engine
  41059. PathCursor.prototype.raiseOnChange = function () {
  41060. var _this = this;
  41061. this._onchange.forEach(function (f) { return f(_this); });
  41062. return this;
  41063. };
  41064. PathCursor.prototype.onchange = function (f) {
  41065. this._onchange.push(f);
  41066. return this;
  41067. };
  41068. return PathCursor;
  41069. }());
  41070. BABYLON.PathCursor = PathCursor;
  41071. var Animation = /** @class */ (function () {
  41072. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41073. this.name = name;
  41074. this.targetProperty = targetProperty;
  41075. this.framePerSecond = framePerSecond;
  41076. this.dataType = dataType;
  41077. this.loopMode = loopMode;
  41078. this.enableBlending = enableBlending;
  41079. this._runtimeAnimations = new Array();
  41080. // The set of event that will be linked to this animation
  41081. this._events = new Array();
  41082. this.blendingSpeed = 0.01;
  41083. this._ranges = {};
  41084. this.targetPropertyPath = targetProperty.split(".");
  41085. this.dataType = dataType;
  41086. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41087. }
  41088. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41089. var dataType = undefined;
  41090. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41091. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41092. }
  41093. else if (from instanceof BABYLON.Quaternion) {
  41094. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41095. }
  41096. else if (from instanceof BABYLON.Vector3) {
  41097. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41098. }
  41099. else if (from instanceof BABYLON.Vector2) {
  41100. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41101. }
  41102. else if (from instanceof BABYLON.Color3) {
  41103. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41104. }
  41105. else if (from instanceof BABYLON.Size) {
  41106. dataType = Animation.ANIMATIONTYPE_SIZE;
  41107. }
  41108. if (dataType == undefined) {
  41109. return null;
  41110. }
  41111. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41112. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41113. animation.setKeys(keys);
  41114. if (easingFunction !== undefined) {
  41115. animation.setEasingFunction(easingFunction);
  41116. }
  41117. return animation;
  41118. };
  41119. /**
  41120. * Sets up an animation.
  41121. * @param property the property to animate
  41122. * @param animationType the animation type to apply
  41123. * @param easingFunction the easing function used in the animation
  41124. * @returns The created animation
  41125. */
  41126. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41127. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  41128. animation.setEasingFunction(easingFunction);
  41129. return animation;
  41130. };
  41131. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41132. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41133. if (!animation) {
  41134. return null;
  41135. }
  41136. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41137. };
  41138. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41139. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41140. if (!animation) {
  41141. return null;
  41142. }
  41143. node.animations.push(animation);
  41144. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41145. };
  41146. /**
  41147. * Transition property of the Camera to the target Value.
  41148. * @param property The property to transition
  41149. * @param targetValue The target Value of the property
  41150. * @param host The object where the property to animate belongs
  41151. * @param scene Scene used to run the animation
  41152. * @param frameRate Framerate (in frame/s) to use
  41153. * @param transition The transition type we want to use
  41154. * @param duration The duration of the animation, in milliseconds
  41155. * @param onAnimationEnd Call back trigger at the end of the animation.
  41156. */
  41157. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41158. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41159. if (duration <= 0) {
  41160. host[property] = targetValue;
  41161. if (onAnimationEnd) {
  41162. onAnimationEnd();
  41163. }
  41164. return null;
  41165. }
  41166. var endFrame = frameRate * (duration / 1000);
  41167. transition.setKeys([{
  41168. frame: 0,
  41169. value: host[property].clone ? host[property].clone() : host[property]
  41170. },
  41171. {
  41172. frame: endFrame,
  41173. value: targetValue
  41174. }]);
  41175. if (!host.animations) {
  41176. host.animations = [];
  41177. }
  41178. host.animations.push(transition);
  41179. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41180. animation.onAnimationEnd = onAnimationEnd;
  41181. return animation;
  41182. };
  41183. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41184. /**
  41185. * Return the array of runtime animations currently using this animation
  41186. */
  41187. get: function () {
  41188. return this._runtimeAnimations;
  41189. },
  41190. enumerable: true,
  41191. configurable: true
  41192. });
  41193. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41194. get: function () {
  41195. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41196. var runtimeAnimation = _a[_i];
  41197. if (!runtimeAnimation.isStopped) {
  41198. return true;
  41199. }
  41200. }
  41201. return false;
  41202. },
  41203. enumerable: true,
  41204. configurable: true
  41205. });
  41206. // Methods
  41207. /**
  41208. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41209. */
  41210. Animation.prototype.toString = function (fullDetails) {
  41211. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41212. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41213. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41214. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41215. if (fullDetails) {
  41216. ret += ", Ranges: {";
  41217. var first = true;
  41218. for (var name in this._ranges) {
  41219. if (first) {
  41220. ret += ", ";
  41221. first = false;
  41222. }
  41223. ret += name;
  41224. }
  41225. ret += "}";
  41226. }
  41227. return ret;
  41228. };
  41229. /**
  41230. * Add an event to this animation.
  41231. */
  41232. Animation.prototype.addEvent = function (event) {
  41233. this._events.push(event);
  41234. };
  41235. /**
  41236. * Remove all events found at the given frame
  41237. * @param frame
  41238. */
  41239. Animation.prototype.removeEvents = function (frame) {
  41240. for (var index = 0; index < this._events.length; index++) {
  41241. if (this._events[index].frame === frame) {
  41242. this._events.splice(index, 1);
  41243. index--;
  41244. }
  41245. }
  41246. };
  41247. Animation.prototype.getEvents = function () {
  41248. return this._events;
  41249. };
  41250. Animation.prototype.createRange = function (name, from, to) {
  41251. // check name not already in use; could happen for bones after serialized
  41252. if (!this._ranges[name]) {
  41253. this._ranges[name] = new AnimationRange(name, from, to);
  41254. }
  41255. };
  41256. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41257. if (deleteFrames === void 0) { deleteFrames = true; }
  41258. var range = this._ranges[name];
  41259. if (!range) {
  41260. return;
  41261. }
  41262. if (deleteFrames) {
  41263. var from = range.from;
  41264. var to = range.to;
  41265. // this loop MUST go high to low for multiple splices to work
  41266. for (var key = this._keys.length - 1; key >= 0; key--) {
  41267. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41268. this._keys.splice(key, 1);
  41269. }
  41270. }
  41271. }
  41272. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41273. };
  41274. Animation.prototype.getRange = function (name) {
  41275. return this._ranges[name];
  41276. };
  41277. Animation.prototype.getKeys = function () {
  41278. return this._keys;
  41279. };
  41280. Animation.prototype.getHighestFrame = function () {
  41281. var ret = 0;
  41282. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41283. if (ret < this._keys[key].frame) {
  41284. ret = this._keys[key].frame;
  41285. }
  41286. }
  41287. return ret;
  41288. };
  41289. Animation.prototype.getEasingFunction = function () {
  41290. return this._easingFunction;
  41291. };
  41292. Animation.prototype.setEasingFunction = function (easingFunction) {
  41293. this._easingFunction = easingFunction;
  41294. };
  41295. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41296. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41297. };
  41298. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41299. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41300. };
  41301. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41302. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41303. };
  41304. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41305. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41306. };
  41307. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41308. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41309. };
  41310. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41311. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41312. };
  41313. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41314. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41315. };
  41316. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41317. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41318. };
  41319. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41320. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41321. };
  41322. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41323. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41324. };
  41325. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41326. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41327. };
  41328. Animation.prototype.clone = function () {
  41329. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41330. clone.enableBlending = this.enableBlending;
  41331. clone.blendingSpeed = this.blendingSpeed;
  41332. if (this._keys) {
  41333. clone.setKeys(this._keys);
  41334. }
  41335. if (this._ranges) {
  41336. clone._ranges = {};
  41337. for (var name in this._ranges) {
  41338. var range = this._ranges[name];
  41339. if (!range) {
  41340. continue;
  41341. }
  41342. clone._ranges[name] = range.clone();
  41343. }
  41344. }
  41345. return clone;
  41346. };
  41347. Animation.prototype.setKeys = function (values) {
  41348. this._keys = values.slice(0);
  41349. };
  41350. Animation.prototype.serialize = function () {
  41351. var serializationObject = {};
  41352. serializationObject.name = this.name;
  41353. serializationObject.property = this.targetProperty;
  41354. serializationObject.framePerSecond = this.framePerSecond;
  41355. serializationObject.dataType = this.dataType;
  41356. serializationObject.loopBehavior = this.loopMode;
  41357. serializationObject.enableBlending = this.enableBlending;
  41358. serializationObject.blendingSpeed = this.blendingSpeed;
  41359. var dataType = this.dataType;
  41360. serializationObject.keys = [];
  41361. var keys = this.getKeys();
  41362. for (var index = 0; index < keys.length; index++) {
  41363. var animationKey = keys[index];
  41364. var key = {};
  41365. key.frame = animationKey.frame;
  41366. switch (dataType) {
  41367. case Animation.ANIMATIONTYPE_FLOAT:
  41368. key.values = [animationKey.value];
  41369. break;
  41370. case Animation.ANIMATIONTYPE_QUATERNION:
  41371. case Animation.ANIMATIONTYPE_MATRIX:
  41372. case Animation.ANIMATIONTYPE_VECTOR3:
  41373. case Animation.ANIMATIONTYPE_COLOR3:
  41374. key.values = animationKey.value.asArray();
  41375. break;
  41376. }
  41377. serializationObject.keys.push(key);
  41378. }
  41379. serializationObject.ranges = [];
  41380. for (var name in this._ranges) {
  41381. var source = this._ranges[name];
  41382. if (!source) {
  41383. continue;
  41384. }
  41385. var range = {};
  41386. range.name = name;
  41387. range.from = source.from;
  41388. range.to = source.to;
  41389. serializationObject.ranges.push(range);
  41390. }
  41391. return serializationObject;
  41392. };
  41393. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41394. get: function () {
  41395. return Animation._ANIMATIONTYPE_FLOAT;
  41396. },
  41397. enumerable: true,
  41398. configurable: true
  41399. });
  41400. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41401. get: function () {
  41402. return Animation._ANIMATIONTYPE_VECTOR3;
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41408. get: function () {
  41409. return Animation._ANIMATIONTYPE_VECTOR2;
  41410. },
  41411. enumerable: true,
  41412. configurable: true
  41413. });
  41414. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41415. get: function () {
  41416. return Animation._ANIMATIONTYPE_SIZE;
  41417. },
  41418. enumerable: true,
  41419. configurable: true
  41420. });
  41421. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41422. get: function () {
  41423. return Animation._ANIMATIONTYPE_QUATERNION;
  41424. },
  41425. enumerable: true,
  41426. configurable: true
  41427. });
  41428. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41429. get: function () {
  41430. return Animation._ANIMATIONTYPE_MATRIX;
  41431. },
  41432. enumerable: true,
  41433. configurable: true
  41434. });
  41435. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41436. get: function () {
  41437. return Animation._ANIMATIONTYPE_COLOR3;
  41438. },
  41439. enumerable: true,
  41440. configurable: true
  41441. });
  41442. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41443. get: function () {
  41444. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41450. get: function () {
  41451. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41457. get: function () {
  41458. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. Animation.Parse = function (parsedAnimation) {
  41464. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41465. var dataType = parsedAnimation.dataType;
  41466. var keys = [];
  41467. var data;
  41468. var index;
  41469. if (parsedAnimation.enableBlending) {
  41470. animation.enableBlending = parsedAnimation.enableBlending;
  41471. }
  41472. if (parsedAnimation.blendingSpeed) {
  41473. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41474. }
  41475. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41476. var key = parsedAnimation.keys[index];
  41477. var inTangent;
  41478. var outTangent;
  41479. switch (dataType) {
  41480. case Animation.ANIMATIONTYPE_FLOAT:
  41481. data = key.values[0];
  41482. if (key.values.length >= 1) {
  41483. inTangent = key.values[1];
  41484. }
  41485. if (key.values.length >= 2) {
  41486. outTangent = key.values[2];
  41487. }
  41488. break;
  41489. case Animation.ANIMATIONTYPE_QUATERNION:
  41490. data = BABYLON.Quaternion.FromArray(key.values);
  41491. if (key.values.length >= 8) {
  41492. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41493. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41494. inTangent = _inTangent;
  41495. }
  41496. }
  41497. if (key.values.length >= 12) {
  41498. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41499. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41500. outTangent = _outTangent;
  41501. }
  41502. }
  41503. break;
  41504. case Animation.ANIMATIONTYPE_MATRIX:
  41505. data = BABYLON.Matrix.FromArray(key.values);
  41506. break;
  41507. case Animation.ANIMATIONTYPE_COLOR3:
  41508. data = BABYLON.Color3.FromArray(key.values);
  41509. break;
  41510. case Animation.ANIMATIONTYPE_VECTOR3:
  41511. default:
  41512. data = BABYLON.Vector3.FromArray(key.values);
  41513. break;
  41514. }
  41515. var keyData = {};
  41516. keyData.frame = key.frame;
  41517. keyData.value = data;
  41518. if (inTangent != undefined) {
  41519. keyData.inTangent = inTangent;
  41520. }
  41521. if (outTangent != undefined) {
  41522. keyData.outTangent = outTangent;
  41523. }
  41524. keys.push(keyData);
  41525. }
  41526. animation.setKeys(keys);
  41527. if (parsedAnimation.ranges) {
  41528. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41529. data = parsedAnimation.ranges[index];
  41530. animation.createRange(data.name, data.from, data.to);
  41531. }
  41532. }
  41533. return animation;
  41534. };
  41535. Animation.AppendSerializedAnimations = function (source, destination) {
  41536. if (source.animations) {
  41537. destination.animations = [];
  41538. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41539. var animation = source.animations[animationIndex];
  41540. destination.animations.push(animation.serialize());
  41541. }
  41542. }
  41543. };
  41544. Animation.AllowMatricesInterpolation = false;
  41545. // Statics
  41546. Animation._ANIMATIONTYPE_FLOAT = 0;
  41547. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41548. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41549. Animation._ANIMATIONTYPE_MATRIX = 3;
  41550. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41551. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41552. Animation._ANIMATIONTYPE_SIZE = 6;
  41553. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41554. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41555. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41556. return Animation;
  41557. }());
  41558. BABYLON.Animation = Animation;
  41559. })(BABYLON || (BABYLON = {}));
  41560. //# sourceMappingURL=babylon.animation.js.map
  41561. var BABYLON;
  41562. (function (BABYLON) {
  41563. var RuntimeAnimation = /** @class */ (function () {
  41564. function RuntimeAnimation(target, animation) {
  41565. this._offsetsCache = {};
  41566. this._highLimitsCache = {};
  41567. this._stopped = false;
  41568. this._blendingFactor = 0;
  41569. this._ratioOffset = 0;
  41570. this._animation = animation;
  41571. this._target = target;
  41572. animation._runtimeAnimations.push(this);
  41573. }
  41574. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  41575. get: function () {
  41576. return this._animation;
  41577. },
  41578. enumerable: true,
  41579. configurable: true
  41580. });
  41581. RuntimeAnimation.prototype.reset = function () {
  41582. this._offsetsCache = {};
  41583. this._highLimitsCache = {};
  41584. this.currentFrame = 0;
  41585. this._blendingFactor = 0;
  41586. this._originalBlendValue = null;
  41587. };
  41588. RuntimeAnimation.prototype.isStopped = function () {
  41589. return this._stopped;
  41590. };
  41591. RuntimeAnimation.prototype.dispose = function () {
  41592. var index = this._animation.runtimeAnimations.indexOf(this);
  41593. if (index > -1) {
  41594. this._animation.runtimeAnimations.splice(index, 1);
  41595. }
  41596. };
  41597. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41598. if (typeof value === "function") {
  41599. return value();
  41600. }
  41601. return value;
  41602. };
  41603. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41604. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41605. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41606. }
  41607. this.currentFrame = currentFrame;
  41608. var keys = this._animation.getKeys();
  41609. // Try to get a hash to find the right key
  41610. 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));
  41611. if (keys[startKeyIndex].frame >= currentFrame) {
  41612. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41613. startKeyIndex--;
  41614. }
  41615. }
  41616. for (var key = startKeyIndex; key < keys.length; key++) {
  41617. var endKey = keys[key + 1];
  41618. if (endKey.frame >= currentFrame) {
  41619. var startKey = keys[key];
  41620. var startValue = this._getKeyValue(startKey.value);
  41621. var endValue = this._getKeyValue(endKey.value);
  41622. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41623. var frameDelta = endKey.frame - startKey.frame;
  41624. // gradient : percent of currentFrame between the frame inf and the frame sup
  41625. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41626. // check for easingFunction and correction of gradient
  41627. var easingFunction = this._animation.getEasingFunction();
  41628. if (easingFunction != null) {
  41629. gradient = easingFunction.ease(gradient);
  41630. }
  41631. switch (this._animation.dataType) {
  41632. // Float
  41633. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41634. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41635. switch (loopMode) {
  41636. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41637. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41638. return floatValue;
  41639. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41640. return offsetValue * repeatCount + floatValue;
  41641. }
  41642. break;
  41643. // Quaternion
  41644. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41645. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41646. switch (loopMode) {
  41647. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41648. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41649. return quatValue;
  41650. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41651. return quatValue.add(offsetValue.scale(repeatCount));
  41652. }
  41653. return quatValue;
  41654. // Vector3
  41655. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41656. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41657. switch (loopMode) {
  41658. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41659. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41660. return vec3Value;
  41661. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41662. return vec3Value.add(offsetValue.scale(repeatCount));
  41663. }
  41664. // Vector2
  41665. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41666. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41667. switch (loopMode) {
  41668. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41669. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41670. return vec2Value;
  41671. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41672. return vec2Value.add(offsetValue.scale(repeatCount));
  41673. }
  41674. // Size
  41675. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41676. switch (loopMode) {
  41677. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41678. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41679. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41680. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41681. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41682. }
  41683. // Color3
  41684. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41685. switch (loopMode) {
  41686. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41687. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41688. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41689. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41690. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41691. }
  41692. // Matrix
  41693. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41694. switch (loopMode) {
  41695. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41696. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41697. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41698. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41699. }
  41700. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41701. return startValue;
  41702. }
  41703. default:
  41704. break;
  41705. }
  41706. break;
  41707. }
  41708. }
  41709. return this._getKeyValue(keys[keys.length - 1].value);
  41710. };
  41711. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41712. if (blend === void 0) { blend = false; }
  41713. // Set value
  41714. var path;
  41715. var destination;
  41716. var targetPropertyPath = this._animation.targetPropertyPath;
  41717. if (targetPropertyPath.length > 1) {
  41718. var property = this._target[targetPropertyPath[0]];
  41719. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41720. property = property[targetPropertyPath[index]];
  41721. }
  41722. path = targetPropertyPath[targetPropertyPath.length - 1];
  41723. destination = property;
  41724. }
  41725. else {
  41726. path = targetPropertyPath[0];
  41727. destination = this._target;
  41728. }
  41729. // Blending
  41730. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41731. if (!this._originalBlendValue) {
  41732. if (destination[path].clone) {
  41733. this._originalBlendValue = destination[path].clone();
  41734. }
  41735. else {
  41736. this._originalBlendValue = destination[path];
  41737. }
  41738. }
  41739. if (this._originalBlendValue.prototype) {
  41740. if (this._originalBlendValue.prototype.Lerp) {
  41741. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41742. }
  41743. else {
  41744. destination[path] = currentValue;
  41745. }
  41746. }
  41747. else if (this._originalBlendValue.m) {
  41748. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41749. }
  41750. else {
  41751. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41752. }
  41753. this._blendingFactor += this._animation.blendingSpeed;
  41754. }
  41755. else {
  41756. destination[path] = currentValue;
  41757. }
  41758. if (this._target.markAsDirty) {
  41759. this._target.markAsDirty(this._animation.targetProperty);
  41760. }
  41761. };
  41762. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41763. var keys = this._animation.getKeys();
  41764. if (frame < keys[0].frame) {
  41765. frame = keys[0].frame;
  41766. }
  41767. else if (frame > keys[keys.length - 1].frame) {
  41768. frame = keys[keys.length - 1].frame;
  41769. }
  41770. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41771. this.setValue(currentValue);
  41772. };
  41773. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41774. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41775. this._ratioOffset = this._previousRatio - newRatio;
  41776. };
  41777. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41778. if (blend === void 0) { blend = false; }
  41779. var targetPropertyPath = this._animation.targetPropertyPath;
  41780. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41781. this._stopped = true;
  41782. return false;
  41783. }
  41784. var returnValue = true;
  41785. var keys = this._animation.getKeys();
  41786. // Adding a start key at frame 0 if missing
  41787. if (keys[0].frame !== 0) {
  41788. var newKey = { frame: 0, value: keys[0].value };
  41789. keys.splice(0, 0, newKey);
  41790. }
  41791. // Check limits
  41792. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41793. from = keys[0].frame;
  41794. }
  41795. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41796. to = keys[keys.length - 1].frame;
  41797. }
  41798. //to and from cannot be the same key
  41799. if (from === to) {
  41800. if (from > keys[0].frame) {
  41801. from--;
  41802. }
  41803. else if (to < keys[keys.length - 1].frame) {
  41804. to++;
  41805. }
  41806. }
  41807. // Compute ratio
  41808. var range = to - from;
  41809. var offsetValue;
  41810. // ratio represents the frame delta between from and to
  41811. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41812. var highLimitValue = 0;
  41813. this._previousDelay = delay;
  41814. this._previousRatio = ratio;
  41815. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41816. returnValue = false;
  41817. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41818. }
  41819. else {
  41820. // Get max value if required
  41821. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41822. var keyOffset = to.toString() + from.toString();
  41823. if (!this._offsetsCache[keyOffset]) {
  41824. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41825. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41826. switch (this._animation.dataType) {
  41827. // Float
  41828. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41829. this._offsetsCache[keyOffset] = toValue - fromValue;
  41830. break;
  41831. // Quaternion
  41832. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41833. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41834. break;
  41835. // Vector3
  41836. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41837. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41838. // Vector2
  41839. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41840. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41841. // Size
  41842. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41843. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41844. // Color3
  41845. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41846. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41847. default:
  41848. break;
  41849. }
  41850. this._highLimitsCache[keyOffset] = toValue;
  41851. }
  41852. highLimitValue = this._highLimitsCache[keyOffset];
  41853. offsetValue = this._offsetsCache[keyOffset];
  41854. }
  41855. }
  41856. if (offsetValue === undefined) {
  41857. switch (this._animation.dataType) {
  41858. // Float
  41859. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41860. offsetValue = 0;
  41861. break;
  41862. // Quaternion
  41863. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41864. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41865. break;
  41866. // Vector3
  41867. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41868. offsetValue = BABYLON.Vector3.Zero();
  41869. break;
  41870. // Vector2
  41871. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41872. offsetValue = BABYLON.Vector2.Zero();
  41873. break;
  41874. // Size
  41875. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41876. offsetValue = BABYLON.Size.Zero();
  41877. break;
  41878. // Color3
  41879. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41880. offsetValue = BABYLON.Color3.Black();
  41881. }
  41882. }
  41883. // Compute value
  41884. var repeatCount = (ratio / range) >> 0;
  41885. var currentFrame = returnValue ? from + ratio % range : to;
  41886. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41887. // Set value
  41888. this.setValue(currentValue);
  41889. // Check events
  41890. var events = this._animation.getEvents();
  41891. for (var index = 0; index < events.length; index++) {
  41892. // Make sure current frame has passed event frame and that event frame is within the current range
  41893. // Also, handle both forward and reverse animations
  41894. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41895. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41896. var event = events[index];
  41897. if (!event.isDone) {
  41898. // If event should be done only once, remove it.
  41899. if (event.onlyOnce) {
  41900. events.splice(index, 1);
  41901. index--;
  41902. }
  41903. event.isDone = true;
  41904. event.action();
  41905. } // Don't do anything if the event has already be done.
  41906. }
  41907. else if (events[index].isDone && !events[index].onlyOnce) {
  41908. // reset event, the animation is looping
  41909. events[index].isDone = false;
  41910. }
  41911. }
  41912. if (!returnValue) {
  41913. this._stopped = true;
  41914. }
  41915. return returnValue;
  41916. };
  41917. return RuntimeAnimation;
  41918. }());
  41919. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41920. })(BABYLON || (BABYLON = {}));
  41921. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41922. var BABYLON;
  41923. (function (BABYLON) {
  41924. var Animatable = /** @class */ (function () {
  41925. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41926. if (fromFrame === void 0) { fromFrame = 0; }
  41927. if (toFrame === void 0) { toFrame = 100; }
  41928. if (loopAnimation === void 0) { loopAnimation = false; }
  41929. if (speedRatio === void 0) { speedRatio = 1.0; }
  41930. this.target = target;
  41931. this.fromFrame = fromFrame;
  41932. this.toFrame = toFrame;
  41933. this.loopAnimation = loopAnimation;
  41934. this.onAnimationEnd = onAnimationEnd;
  41935. this._localDelayOffset = null;
  41936. this._pausedDelay = null;
  41937. this._runtimeAnimations = new Array();
  41938. this._paused = false;
  41939. this._speedRatio = 1;
  41940. this.animationStarted = false;
  41941. if (animations) {
  41942. this.appendAnimations(target, animations);
  41943. }
  41944. this._speedRatio = speedRatio;
  41945. this._scene = scene;
  41946. scene._activeAnimatables.push(this);
  41947. }
  41948. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41949. get: function () {
  41950. return this._speedRatio;
  41951. },
  41952. set: function (value) {
  41953. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41954. var animation = this._runtimeAnimations[index];
  41955. animation._prepareForSpeedRatioChange(value);
  41956. }
  41957. this._speedRatio = value;
  41958. },
  41959. enumerable: true,
  41960. configurable: true
  41961. });
  41962. // Methods
  41963. Animatable.prototype.getAnimations = function () {
  41964. return this._runtimeAnimations;
  41965. };
  41966. Animatable.prototype.appendAnimations = function (target, animations) {
  41967. for (var index = 0; index < animations.length; index++) {
  41968. var animation = animations[index];
  41969. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41970. }
  41971. };
  41972. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41973. var runtimeAnimations = this._runtimeAnimations;
  41974. for (var index = 0; index < runtimeAnimations.length; index++) {
  41975. if (runtimeAnimations[index].animation.targetProperty === property) {
  41976. return runtimeAnimations[index].animation;
  41977. }
  41978. }
  41979. return null;
  41980. };
  41981. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41982. var runtimeAnimations = this._runtimeAnimations;
  41983. for (var index = 0; index < runtimeAnimations.length; index++) {
  41984. if (runtimeAnimations[index].animation.targetProperty === property) {
  41985. return runtimeAnimations[index];
  41986. }
  41987. }
  41988. return null;
  41989. };
  41990. Animatable.prototype.reset = function () {
  41991. var runtimeAnimations = this._runtimeAnimations;
  41992. for (var index = 0; index < runtimeAnimations.length; index++) {
  41993. runtimeAnimations[index].reset();
  41994. }
  41995. this._localDelayOffset = null;
  41996. this._pausedDelay = null;
  41997. };
  41998. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41999. var runtimeAnimations = this._runtimeAnimations;
  42000. for (var index = 0; index < runtimeAnimations.length; index++) {
  42001. runtimeAnimations[index].animation.enableBlending = true;
  42002. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42003. }
  42004. };
  42005. Animatable.prototype.disableBlending = function () {
  42006. var runtimeAnimations = this._runtimeAnimations;
  42007. for (var index = 0; index < runtimeAnimations.length; index++) {
  42008. runtimeAnimations[index].animation.enableBlending = false;
  42009. }
  42010. };
  42011. Animatable.prototype.goToFrame = function (frame) {
  42012. var runtimeAnimations = this._runtimeAnimations;
  42013. if (runtimeAnimations[0]) {
  42014. var fps = runtimeAnimations[0].animation.framePerSecond;
  42015. var currentFrame = runtimeAnimations[0].currentFrame;
  42016. var adjustTime = frame - currentFrame;
  42017. var delay = adjustTime * 1000 / fps;
  42018. if (this._localDelayOffset === null) {
  42019. this._localDelayOffset = 0;
  42020. }
  42021. this._localDelayOffset -= delay;
  42022. }
  42023. for (var index = 0; index < runtimeAnimations.length; index++) {
  42024. runtimeAnimations[index].goToFrame(frame);
  42025. }
  42026. };
  42027. Animatable.prototype.pause = function () {
  42028. if (this._paused) {
  42029. return;
  42030. }
  42031. this._paused = true;
  42032. };
  42033. Animatable.prototype.restart = function () {
  42034. this._paused = false;
  42035. };
  42036. Animatable.prototype.stop = function (animationName) {
  42037. if (animationName) {
  42038. var idx = this._scene._activeAnimatables.indexOf(this);
  42039. if (idx > -1) {
  42040. var runtimeAnimations = this._runtimeAnimations;
  42041. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42042. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42043. continue;
  42044. }
  42045. runtimeAnimations[index].dispose();
  42046. runtimeAnimations.splice(index, 1);
  42047. }
  42048. if (runtimeAnimations.length == 0) {
  42049. this._scene._activeAnimatables.splice(idx, 1);
  42050. if (this.onAnimationEnd) {
  42051. this.onAnimationEnd();
  42052. }
  42053. }
  42054. }
  42055. }
  42056. else {
  42057. var index = this._scene._activeAnimatables.indexOf(this);
  42058. if (index > -1) {
  42059. this._scene._activeAnimatables.splice(index, 1);
  42060. var runtimeAnimations = this._runtimeAnimations;
  42061. for (var index = 0; index < runtimeAnimations.length; index++) {
  42062. runtimeAnimations[index].dispose();
  42063. }
  42064. if (this.onAnimationEnd) {
  42065. this.onAnimationEnd();
  42066. }
  42067. }
  42068. }
  42069. };
  42070. Animatable.prototype._animate = function (delay) {
  42071. if (this._paused) {
  42072. this.animationStarted = false;
  42073. if (this._pausedDelay === null) {
  42074. this._pausedDelay = delay;
  42075. }
  42076. return true;
  42077. }
  42078. if (this._localDelayOffset === null) {
  42079. this._localDelayOffset = delay;
  42080. }
  42081. else if (this._pausedDelay !== null) {
  42082. this._localDelayOffset += delay - this._pausedDelay;
  42083. this._pausedDelay = null;
  42084. }
  42085. // Animating
  42086. var running = false;
  42087. var runtimeAnimations = this._runtimeAnimations;
  42088. var index;
  42089. for (index = 0; index < runtimeAnimations.length; index++) {
  42090. var animation = runtimeAnimations[index];
  42091. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42092. running = running || isRunning;
  42093. }
  42094. this.animationStarted = running;
  42095. if (!running) {
  42096. // Remove from active animatables
  42097. index = this._scene._activeAnimatables.indexOf(this);
  42098. this._scene._activeAnimatables.splice(index, 1);
  42099. // Dispose all runtime animations
  42100. for (index = 0; index < runtimeAnimations.length; index++) {
  42101. runtimeAnimations[index].dispose();
  42102. }
  42103. }
  42104. if (!running && this.onAnimationEnd) {
  42105. this.onAnimationEnd();
  42106. this.onAnimationEnd = null;
  42107. }
  42108. return running;
  42109. };
  42110. return Animatable;
  42111. }());
  42112. BABYLON.Animatable = Animatable;
  42113. })(BABYLON || (BABYLON = {}));
  42114. //# sourceMappingURL=babylon.animatable.js.map
  42115. var BABYLON;
  42116. (function (BABYLON) {
  42117. var EasingFunction = /** @class */ (function () {
  42118. function EasingFunction() {
  42119. // Properties
  42120. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42121. }
  42122. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42123. get: function () {
  42124. return EasingFunction._EASINGMODE_EASEIN;
  42125. },
  42126. enumerable: true,
  42127. configurable: true
  42128. });
  42129. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42130. get: function () {
  42131. return EasingFunction._EASINGMODE_EASEOUT;
  42132. },
  42133. enumerable: true,
  42134. configurable: true
  42135. });
  42136. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42137. get: function () {
  42138. return EasingFunction._EASINGMODE_EASEINOUT;
  42139. },
  42140. enumerable: true,
  42141. configurable: true
  42142. });
  42143. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42144. var n = Math.min(Math.max(easingMode, 0), 2);
  42145. this._easingMode = n;
  42146. };
  42147. EasingFunction.prototype.getEasingMode = function () {
  42148. return this._easingMode;
  42149. };
  42150. EasingFunction.prototype.easeInCore = function (gradient) {
  42151. throw new Error('You must implement this method');
  42152. };
  42153. EasingFunction.prototype.ease = function (gradient) {
  42154. switch (this._easingMode) {
  42155. case EasingFunction.EASINGMODE_EASEIN:
  42156. return this.easeInCore(gradient);
  42157. case EasingFunction.EASINGMODE_EASEOUT:
  42158. return (1 - this.easeInCore(1 - gradient));
  42159. }
  42160. if (gradient >= 0.5) {
  42161. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42162. }
  42163. return (this.easeInCore(gradient * 2) * 0.5);
  42164. };
  42165. //Statics
  42166. EasingFunction._EASINGMODE_EASEIN = 0;
  42167. EasingFunction._EASINGMODE_EASEOUT = 1;
  42168. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42169. return EasingFunction;
  42170. }());
  42171. BABYLON.EasingFunction = EasingFunction;
  42172. var CircleEase = /** @class */ (function (_super) {
  42173. __extends(CircleEase, _super);
  42174. function CircleEase() {
  42175. return _super !== null && _super.apply(this, arguments) || this;
  42176. }
  42177. CircleEase.prototype.easeInCore = function (gradient) {
  42178. gradient = Math.max(0, Math.min(1, gradient));
  42179. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42180. };
  42181. return CircleEase;
  42182. }(EasingFunction));
  42183. BABYLON.CircleEase = CircleEase;
  42184. var BackEase = /** @class */ (function (_super) {
  42185. __extends(BackEase, _super);
  42186. function BackEase(amplitude) {
  42187. if (amplitude === void 0) { amplitude = 1; }
  42188. var _this = _super.call(this) || this;
  42189. _this.amplitude = amplitude;
  42190. return _this;
  42191. }
  42192. BackEase.prototype.easeInCore = function (gradient) {
  42193. var num = Math.max(0, this.amplitude);
  42194. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42195. };
  42196. return BackEase;
  42197. }(EasingFunction));
  42198. BABYLON.BackEase = BackEase;
  42199. var BounceEase = /** @class */ (function (_super) {
  42200. __extends(BounceEase, _super);
  42201. function BounceEase(bounces, bounciness) {
  42202. if (bounces === void 0) { bounces = 3; }
  42203. if (bounciness === void 0) { bounciness = 2; }
  42204. var _this = _super.call(this) || this;
  42205. _this.bounces = bounces;
  42206. _this.bounciness = bounciness;
  42207. return _this;
  42208. }
  42209. BounceEase.prototype.easeInCore = function (gradient) {
  42210. var y = Math.max(0.0, this.bounces);
  42211. var bounciness = this.bounciness;
  42212. if (bounciness <= 1.0) {
  42213. bounciness = 1.001;
  42214. }
  42215. var num9 = Math.pow(bounciness, y);
  42216. var num5 = 1.0 - bounciness;
  42217. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42218. var num15 = gradient * num4;
  42219. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42220. var num3 = Math.floor(num65);
  42221. var num13 = num3 + 1.0;
  42222. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42223. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  42224. var num7 = (num8 + num12) * 0.5;
  42225. var num6 = gradient - num7;
  42226. var num2 = num7 - num8;
  42227. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  42228. };
  42229. return BounceEase;
  42230. }(EasingFunction));
  42231. BABYLON.BounceEase = BounceEase;
  42232. var CubicEase = /** @class */ (function (_super) {
  42233. __extends(CubicEase, _super);
  42234. function CubicEase() {
  42235. return _super !== null && _super.apply(this, arguments) || this;
  42236. }
  42237. CubicEase.prototype.easeInCore = function (gradient) {
  42238. return (gradient * gradient * gradient);
  42239. };
  42240. return CubicEase;
  42241. }(EasingFunction));
  42242. BABYLON.CubicEase = CubicEase;
  42243. var ElasticEase = /** @class */ (function (_super) {
  42244. __extends(ElasticEase, _super);
  42245. function ElasticEase(oscillations, springiness) {
  42246. if (oscillations === void 0) { oscillations = 3; }
  42247. if (springiness === void 0) { springiness = 3; }
  42248. var _this = _super.call(this) || this;
  42249. _this.oscillations = oscillations;
  42250. _this.springiness = springiness;
  42251. return _this;
  42252. }
  42253. ElasticEase.prototype.easeInCore = function (gradient) {
  42254. var num2;
  42255. var num3 = Math.max(0.0, this.oscillations);
  42256. var num = Math.max(0.0, this.springiness);
  42257. if (num == 0) {
  42258. num2 = gradient;
  42259. }
  42260. else {
  42261. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42262. }
  42263. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42264. };
  42265. return ElasticEase;
  42266. }(EasingFunction));
  42267. BABYLON.ElasticEase = ElasticEase;
  42268. var ExponentialEase = /** @class */ (function (_super) {
  42269. __extends(ExponentialEase, _super);
  42270. function ExponentialEase(exponent) {
  42271. if (exponent === void 0) { exponent = 2; }
  42272. var _this = _super.call(this) || this;
  42273. _this.exponent = exponent;
  42274. return _this;
  42275. }
  42276. ExponentialEase.prototype.easeInCore = function (gradient) {
  42277. if (this.exponent <= 0) {
  42278. return gradient;
  42279. }
  42280. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42281. };
  42282. return ExponentialEase;
  42283. }(EasingFunction));
  42284. BABYLON.ExponentialEase = ExponentialEase;
  42285. var PowerEase = /** @class */ (function (_super) {
  42286. __extends(PowerEase, _super);
  42287. function PowerEase(power) {
  42288. if (power === void 0) { power = 2; }
  42289. var _this = _super.call(this) || this;
  42290. _this.power = power;
  42291. return _this;
  42292. }
  42293. PowerEase.prototype.easeInCore = function (gradient) {
  42294. var y = Math.max(0.0, this.power);
  42295. return Math.pow(gradient, y);
  42296. };
  42297. return PowerEase;
  42298. }(EasingFunction));
  42299. BABYLON.PowerEase = PowerEase;
  42300. var QuadraticEase = /** @class */ (function (_super) {
  42301. __extends(QuadraticEase, _super);
  42302. function QuadraticEase() {
  42303. return _super !== null && _super.apply(this, arguments) || this;
  42304. }
  42305. QuadraticEase.prototype.easeInCore = function (gradient) {
  42306. return (gradient * gradient);
  42307. };
  42308. return QuadraticEase;
  42309. }(EasingFunction));
  42310. BABYLON.QuadraticEase = QuadraticEase;
  42311. var QuarticEase = /** @class */ (function (_super) {
  42312. __extends(QuarticEase, _super);
  42313. function QuarticEase() {
  42314. return _super !== null && _super.apply(this, arguments) || this;
  42315. }
  42316. QuarticEase.prototype.easeInCore = function (gradient) {
  42317. return (gradient * gradient * gradient * gradient);
  42318. };
  42319. return QuarticEase;
  42320. }(EasingFunction));
  42321. BABYLON.QuarticEase = QuarticEase;
  42322. var QuinticEase = /** @class */ (function (_super) {
  42323. __extends(QuinticEase, _super);
  42324. function QuinticEase() {
  42325. return _super !== null && _super.apply(this, arguments) || this;
  42326. }
  42327. QuinticEase.prototype.easeInCore = function (gradient) {
  42328. return (gradient * gradient * gradient * gradient * gradient);
  42329. };
  42330. return QuinticEase;
  42331. }(EasingFunction));
  42332. BABYLON.QuinticEase = QuinticEase;
  42333. var SineEase = /** @class */ (function (_super) {
  42334. __extends(SineEase, _super);
  42335. function SineEase() {
  42336. return _super !== null && _super.apply(this, arguments) || this;
  42337. }
  42338. SineEase.prototype.easeInCore = function (gradient) {
  42339. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42340. };
  42341. return SineEase;
  42342. }(EasingFunction));
  42343. BABYLON.SineEase = SineEase;
  42344. var BezierCurveEase = /** @class */ (function (_super) {
  42345. __extends(BezierCurveEase, _super);
  42346. function BezierCurveEase(x1, y1, x2, y2) {
  42347. if (x1 === void 0) { x1 = 0; }
  42348. if (y1 === void 0) { y1 = 0; }
  42349. if (x2 === void 0) { x2 = 1; }
  42350. if (y2 === void 0) { y2 = 1; }
  42351. var _this = _super.call(this) || this;
  42352. _this.x1 = x1;
  42353. _this.y1 = y1;
  42354. _this.x2 = x2;
  42355. _this.y2 = y2;
  42356. return _this;
  42357. }
  42358. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42359. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42360. };
  42361. return BezierCurveEase;
  42362. }(EasingFunction));
  42363. BABYLON.BezierCurveEase = BezierCurveEase;
  42364. })(BABYLON || (BABYLON = {}));
  42365. //# sourceMappingURL=babylon.easing.js.map
  42366. var BABYLON;
  42367. (function (BABYLON) {
  42368. var Condition = /** @class */ (function () {
  42369. function Condition(actionManager) {
  42370. this._actionManager = actionManager;
  42371. }
  42372. Condition.prototype.isValid = function () {
  42373. return true;
  42374. };
  42375. Condition.prototype._getProperty = function (propertyPath) {
  42376. return this._actionManager._getProperty(propertyPath);
  42377. };
  42378. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42379. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42380. };
  42381. Condition.prototype.serialize = function () {
  42382. };
  42383. Condition.prototype._serialize = function (serializedCondition) {
  42384. return {
  42385. type: 2,
  42386. children: [],
  42387. name: serializedCondition.name,
  42388. properties: serializedCondition.properties
  42389. };
  42390. };
  42391. return Condition;
  42392. }());
  42393. BABYLON.Condition = Condition;
  42394. var ValueCondition = /** @class */ (function (_super) {
  42395. __extends(ValueCondition, _super);
  42396. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42397. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42398. var _this = _super.call(this, actionManager) || this;
  42399. _this.propertyPath = propertyPath;
  42400. _this.value = value;
  42401. _this.operator = operator;
  42402. _this._target = target;
  42403. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42404. _this._property = _this._getProperty(_this.propertyPath);
  42405. return _this;
  42406. }
  42407. Object.defineProperty(ValueCondition, "IsEqual", {
  42408. get: function () {
  42409. return ValueCondition._IsEqual;
  42410. },
  42411. enumerable: true,
  42412. configurable: true
  42413. });
  42414. Object.defineProperty(ValueCondition, "IsDifferent", {
  42415. get: function () {
  42416. return ValueCondition._IsDifferent;
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(ValueCondition, "IsGreater", {
  42422. get: function () {
  42423. return ValueCondition._IsGreater;
  42424. },
  42425. enumerable: true,
  42426. configurable: true
  42427. });
  42428. Object.defineProperty(ValueCondition, "IsLesser", {
  42429. get: function () {
  42430. return ValueCondition._IsLesser;
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. // Methods
  42436. ValueCondition.prototype.isValid = function () {
  42437. switch (this.operator) {
  42438. case ValueCondition.IsGreater:
  42439. return this._effectiveTarget[this._property] > this.value;
  42440. case ValueCondition.IsLesser:
  42441. return this._effectiveTarget[this._property] < this.value;
  42442. case ValueCondition.IsEqual:
  42443. case ValueCondition.IsDifferent:
  42444. var check;
  42445. if (this.value.equals) {
  42446. check = this.value.equals(this._effectiveTarget[this._property]);
  42447. }
  42448. else {
  42449. check = this.value === this._effectiveTarget[this._property];
  42450. }
  42451. return this.operator === ValueCondition.IsEqual ? check : !check;
  42452. }
  42453. return false;
  42454. };
  42455. ValueCondition.prototype.serialize = function () {
  42456. return this._serialize({
  42457. name: "ValueCondition",
  42458. properties: [
  42459. BABYLON.Action._GetTargetProperty(this._target),
  42460. { name: "propertyPath", value: this.propertyPath },
  42461. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42462. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42463. ]
  42464. });
  42465. };
  42466. ValueCondition.GetOperatorName = function (operator) {
  42467. switch (operator) {
  42468. case ValueCondition._IsEqual: return "IsEqual";
  42469. case ValueCondition._IsDifferent: return "IsDifferent";
  42470. case ValueCondition._IsGreater: return "IsGreater";
  42471. case ValueCondition._IsLesser: return "IsLesser";
  42472. default: return "";
  42473. }
  42474. };
  42475. // Statics
  42476. ValueCondition._IsEqual = 0;
  42477. ValueCondition._IsDifferent = 1;
  42478. ValueCondition._IsGreater = 2;
  42479. ValueCondition._IsLesser = 3;
  42480. return ValueCondition;
  42481. }(Condition));
  42482. BABYLON.ValueCondition = ValueCondition;
  42483. var PredicateCondition = /** @class */ (function (_super) {
  42484. __extends(PredicateCondition, _super);
  42485. function PredicateCondition(actionManager, predicate) {
  42486. var _this = _super.call(this, actionManager) || this;
  42487. _this.predicate = predicate;
  42488. return _this;
  42489. }
  42490. PredicateCondition.prototype.isValid = function () {
  42491. return this.predicate();
  42492. };
  42493. return PredicateCondition;
  42494. }(Condition));
  42495. BABYLON.PredicateCondition = PredicateCondition;
  42496. var StateCondition = /** @class */ (function (_super) {
  42497. __extends(StateCondition, _super);
  42498. function StateCondition(actionManager, target, value) {
  42499. var _this = _super.call(this, actionManager) || this;
  42500. _this.value = value;
  42501. _this._target = target;
  42502. return _this;
  42503. }
  42504. // Methods
  42505. StateCondition.prototype.isValid = function () {
  42506. return this._target.state === this.value;
  42507. };
  42508. StateCondition.prototype.serialize = function () {
  42509. return this._serialize({
  42510. name: "StateCondition",
  42511. properties: [
  42512. BABYLON.Action._GetTargetProperty(this._target),
  42513. { name: "value", value: this.value }
  42514. ]
  42515. });
  42516. };
  42517. return StateCondition;
  42518. }(Condition));
  42519. BABYLON.StateCondition = StateCondition;
  42520. })(BABYLON || (BABYLON = {}));
  42521. //# sourceMappingURL=babylon.condition.js.map
  42522. var BABYLON;
  42523. (function (BABYLON) {
  42524. var Action = /** @class */ (function () {
  42525. function Action(triggerOptions, condition) {
  42526. this.triggerOptions = triggerOptions;
  42527. this.onBeforeExecuteObservable = new BABYLON.Observable();
  42528. if (triggerOptions.parameter) {
  42529. this.trigger = triggerOptions.trigger;
  42530. this._triggerParameter = triggerOptions.parameter;
  42531. }
  42532. else {
  42533. this.trigger = triggerOptions;
  42534. }
  42535. this._nextActiveAction = this;
  42536. this._condition = condition;
  42537. }
  42538. // Methods
  42539. Action.prototype._prepare = function () {
  42540. };
  42541. Action.prototype.getTriggerParameter = function () {
  42542. return this._triggerParameter;
  42543. };
  42544. Action.prototype._executeCurrent = function (evt) {
  42545. if (this._nextActiveAction._condition) {
  42546. var condition = this._nextActiveAction._condition;
  42547. var currentRenderId = this._actionManager.getScene().getRenderId();
  42548. // We cache the current evaluation for the current frame
  42549. if (condition._evaluationId === currentRenderId) {
  42550. if (!condition._currentResult) {
  42551. return;
  42552. }
  42553. }
  42554. else {
  42555. condition._evaluationId = currentRenderId;
  42556. if (!condition.isValid()) {
  42557. condition._currentResult = false;
  42558. return;
  42559. }
  42560. condition._currentResult = true;
  42561. }
  42562. }
  42563. this.onBeforeExecuteObservable.notifyObservers(this);
  42564. this._nextActiveAction.execute(evt);
  42565. this.skipToNextActiveAction();
  42566. };
  42567. Action.prototype.execute = function (evt) {
  42568. };
  42569. Action.prototype.skipToNextActiveAction = function () {
  42570. if (this._nextActiveAction._child) {
  42571. if (!this._nextActiveAction._child._actionManager) {
  42572. this._nextActiveAction._child._actionManager = this._actionManager;
  42573. }
  42574. this._nextActiveAction = this._nextActiveAction._child;
  42575. }
  42576. else {
  42577. this._nextActiveAction = this;
  42578. }
  42579. };
  42580. Action.prototype.then = function (action) {
  42581. this._child = action;
  42582. action._actionManager = this._actionManager;
  42583. action._prepare();
  42584. return action;
  42585. };
  42586. Action.prototype._getProperty = function (propertyPath) {
  42587. return this._actionManager._getProperty(propertyPath);
  42588. };
  42589. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42590. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42591. };
  42592. Action.prototype.serialize = function (parent) {
  42593. };
  42594. // Called by BABYLON.Action objects in serialize(...). Internal use
  42595. Action.prototype._serialize = function (serializedAction, parent) {
  42596. var serializationObject = {
  42597. type: 1,
  42598. children: [],
  42599. name: serializedAction.name,
  42600. properties: serializedAction.properties || []
  42601. };
  42602. // Serialize child
  42603. if (this._child) {
  42604. this._child.serialize(serializationObject);
  42605. }
  42606. // Check if "this" has a condition
  42607. if (this._condition) {
  42608. var serializedCondition = this._condition.serialize();
  42609. serializedCondition.children.push(serializationObject);
  42610. if (parent) {
  42611. parent.children.push(serializedCondition);
  42612. }
  42613. return serializedCondition;
  42614. }
  42615. if (parent) {
  42616. parent.children.push(serializationObject);
  42617. }
  42618. return serializationObject;
  42619. };
  42620. Action._SerializeValueAsString = function (value) {
  42621. if (typeof value === "number") {
  42622. return value.toString();
  42623. }
  42624. if (typeof value === "boolean") {
  42625. return value ? "true" : "false";
  42626. }
  42627. if (value instanceof BABYLON.Vector2) {
  42628. return value.x + ", " + value.y;
  42629. }
  42630. if (value instanceof BABYLON.Vector3) {
  42631. return value.x + ", " + value.y + ", " + value.z;
  42632. }
  42633. if (value instanceof BABYLON.Color3) {
  42634. return value.r + ", " + value.g + ", " + value.b;
  42635. }
  42636. if (value instanceof BABYLON.Color4) {
  42637. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42638. }
  42639. return value; // string
  42640. };
  42641. Action._GetTargetProperty = function (target) {
  42642. return {
  42643. name: "target",
  42644. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42645. : target instanceof BABYLON.Light ? "LightProperties"
  42646. : target instanceof BABYLON.Camera ? "CameraProperties"
  42647. : "SceneProperties",
  42648. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42649. };
  42650. };
  42651. return Action;
  42652. }());
  42653. BABYLON.Action = Action;
  42654. })(BABYLON || (BABYLON = {}));
  42655. //# sourceMappingURL=babylon.action.js.map
  42656. var BABYLON;
  42657. (function (BABYLON) {
  42658. /**
  42659. * ActionEvent is the event beint sent when an action is triggered.
  42660. */
  42661. var ActionEvent = /** @class */ (function () {
  42662. /**
  42663. * @param source The mesh or sprite that triggered the action.
  42664. * @param pointerX The X mouse cursor position at the time of the event
  42665. * @param pointerY The Y mouse cursor position at the time of the event
  42666. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42667. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42668. */
  42669. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42670. this.source = source;
  42671. this.pointerX = pointerX;
  42672. this.pointerY = pointerY;
  42673. this.meshUnderPointer = meshUnderPointer;
  42674. this.sourceEvent = sourceEvent;
  42675. this.additionalData = additionalData;
  42676. }
  42677. /**
  42678. * Helper function to auto-create an ActionEvent from a source mesh.
  42679. * @param source The source mesh that triggered the event
  42680. * @param evt {Event} The original (browser) event
  42681. */
  42682. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42683. var scene = source.getScene();
  42684. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42685. };
  42686. /**
  42687. * Helper function to auto-create an ActionEvent from a source mesh.
  42688. * @param source The source sprite that triggered the event
  42689. * @param scene Scene associated with the sprite
  42690. * @param evt {Event} The original (browser) event
  42691. */
  42692. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42693. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42694. };
  42695. /**
  42696. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42697. * @param scene the scene where the event occurred
  42698. * @param evt {Event} The original (browser) event
  42699. */
  42700. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42701. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42702. };
  42703. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42704. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42705. };
  42706. return ActionEvent;
  42707. }());
  42708. BABYLON.ActionEvent = ActionEvent;
  42709. /**
  42710. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42711. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42712. */
  42713. var ActionManager = /** @class */ (function () {
  42714. function ActionManager(scene) {
  42715. // Members
  42716. this.actions = new Array();
  42717. this.hoverCursor = '';
  42718. this._scene = scene;
  42719. scene._actionManagers.push(this);
  42720. }
  42721. Object.defineProperty(ActionManager, "NothingTrigger", {
  42722. get: function () {
  42723. return ActionManager._NothingTrigger;
  42724. },
  42725. enumerable: true,
  42726. configurable: true
  42727. });
  42728. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42729. get: function () {
  42730. return ActionManager._OnPickTrigger;
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42736. get: function () {
  42737. return ActionManager._OnLeftPickTrigger;
  42738. },
  42739. enumerable: true,
  42740. configurable: true
  42741. });
  42742. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42743. get: function () {
  42744. return ActionManager._OnRightPickTrigger;
  42745. },
  42746. enumerable: true,
  42747. configurable: true
  42748. });
  42749. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42750. get: function () {
  42751. return ActionManager._OnCenterPickTrigger;
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42757. get: function () {
  42758. return ActionManager._OnPickDownTrigger;
  42759. },
  42760. enumerable: true,
  42761. configurable: true
  42762. });
  42763. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42764. get: function () {
  42765. return ActionManager._OnDoublePickTrigger;
  42766. },
  42767. enumerable: true,
  42768. configurable: true
  42769. });
  42770. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42771. get: function () {
  42772. return ActionManager._OnPickUpTrigger;
  42773. },
  42774. enumerable: true,
  42775. configurable: true
  42776. });
  42777. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42778. /// This trigger will only be raised if you also declared a OnPickDown
  42779. get: function () {
  42780. return ActionManager._OnPickOutTrigger;
  42781. },
  42782. enumerable: true,
  42783. configurable: true
  42784. });
  42785. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42786. get: function () {
  42787. return ActionManager._OnLongPressTrigger;
  42788. },
  42789. enumerable: true,
  42790. configurable: true
  42791. });
  42792. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42793. get: function () {
  42794. return ActionManager._OnPointerOverTrigger;
  42795. },
  42796. enumerable: true,
  42797. configurable: true
  42798. });
  42799. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42800. get: function () {
  42801. return ActionManager._OnPointerOutTrigger;
  42802. },
  42803. enumerable: true,
  42804. configurable: true
  42805. });
  42806. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42807. get: function () {
  42808. return ActionManager._OnEveryFrameTrigger;
  42809. },
  42810. enumerable: true,
  42811. configurable: true
  42812. });
  42813. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42814. get: function () {
  42815. return ActionManager._OnIntersectionEnterTrigger;
  42816. },
  42817. enumerable: true,
  42818. configurable: true
  42819. });
  42820. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42821. get: function () {
  42822. return ActionManager._OnIntersectionExitTrigger;
  42823. },
  42824. enumerable: true,
  42825. configurable: true
  42826. });
  42827. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42828. get: function () {
  42829. return ActionManager._OnKeyDownTrigger;
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42835. get: function () {
  42836. return ActionManager._OnKeyUpTrigger;
  42837. },
  42838. enumerable: true,
  42839. configurable: true
  42840. });
  42841. // Methods
  42842. ActionManager.prototype.dispose = function () {
  42843. var index = this._scene._actionManagers.indexOf(this);
  42844. for (var i = 0; i < this.actions.length; i++) {
  42845. var action = this.actions[i];
  42846. ActionManager.Triggers[action.trigger]--;
  42847. if (ActionManager.Triggers[action.trigger] === 0) {
  42848. delete ActionManager.Triggers[action.trigger];
  42849. }
  42850. }
  42851. if (index > -1) {
  42852. this._scene._actionManagers.splice(index, 1);
  42853. }
  42854. };
  42855. ActionManager.prototype.getScene = function () {
  42856. return this._scene;
  42857. };
  42858. /**
  42859. * Does this action manager handles actions of any of the given triggers
  42860. * @param {number[]} triggers - the triggers to be tested
  42861. * @return {boolean} whether one (or more) of the triggers is handeled
  42862. */
  42863. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42864. for (var index = 0; index < this.actions.length; index++) {
  42865. var action = this.actions[index];
  42866. if (triggers.indexOf(action.trigger) > -1) {
  42867. return true;
  42868. }
  42869. }
  42870. return false;
  42871. };
  42872. /**
  42873. * Does this action manager handles actions of a given trigger
  42874. * @param {number} trigger - the trigger to be tested
  42875. * @return {boolean} whether the trigger is handeled
  42876. */
  42877. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42878. for (var index = 0; index < this.actions.length; index++) {
  42879. var action = this.actions[index];
  42880. if (action.trigger === trigger) {
  42881. return true;
  42882. }
  42883. }
  42884. return false;
  42885. };
  42886. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42887. /**
  42888. * Does this action manager has pointer triggers
  42889. * @return {boolean} whether or not it has pointer triggers
  42890. */
  42891. get: function () {
  42892. for (var index = 0; index < this.actions.length; index++) {
  42893. var action = this.actions[index];
  42894. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42895. return true;
  42896. }
  42897. }
  42898. return false;
  42899. },
  42900. enumerable: true,
  42901. configurable: true
  42902. });
  42903. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42904. /**
  42905. * Does this action manager has pick triggers
  42906. * @return {boolean} whether or not it has pick triggers
  42907. */
  42908. get: function () {
  42909. for (var index = 0; index < this.actions.length; index++) {
  42910. var action = this.actions[index];
  42911. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42912. return true;
  42913. }
  42914. }
  42915. return false;
  42916. },
  42917. enumerable: true,
  42918. configurable: true
  42919. });
  42920. Object.defineProperty(ActionManager, "HasTriggers", {
  42921. /**
  42922. * Does exist one action manager with at least one trigger
  42923. * @return {boolean} whether or not it exists one action manager with one trigger
  42924. **/
  42925. get: function () {
  42926. for (var t in ActionManager.Triggers) {
  42927. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42928. return true;
  42929. }
  42930. }
  42931. return false;
  42932. },
  42933. enumerable: true,
  42934. configurable: true
  42935. });
  42936. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42937. /**
  42938. * Does exist one action manager with at least one pick trigger
  42939. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42940. **/
  42941. get: function () {
  42942. for (var t in ActionManager.Triggers) {
  42943. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42944. var t_int = parseInt(t);
  42945. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42946. return true;
  42947. }
  42948. }
  42949. }
  42950. return false;
  42951. },
  42952. enumerable: true,
  42953. configurable: true
  42954. });
  42955. /**
  42956. * Does exist one action manager that handles actions of a given trigger
  42957. * @param {number} trigger - the trigger to be tested
  42958. * @return {boolean} whether the trigger is handeled by at least one action manager
  42959. **/
  42960. ActionManager.HasSpecificTrigger = function (trigger) {
  42961. for (var t in ActionManager.Triggers) {
  42962. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42963. var t_int = parseInt(t);
  42964. if (t_int === trigger) {
  42965. return true;
  42966. }
  42967. }
  42968. }
  42969. return false;
  42970. };
  42971. /**
  42972. * Registers an action to this action manager
  42973. * @param {BABYLON.Action} action - the action to be registered
  42974. * @return {BABYLON.Action} the action amended (prepared) after registration
  42975. */
  42976. ActionManager.prototype.registerAction = function (action) {
  42977. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42978. if (this.getScene().actionManager !== this) {
  42979. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42980. return null;
  42981. }
  42982. }
  42983. this.actions.push(action);
  42984. if (ActionManager.Triggers[action.trigger]) {
  42985. ActionManager.Triggers[action.trigger]++;
  42986. }
  42987. else {
  42988. ActionManager.Triggers[action.trigger] = 1;
  42989. }
  42990. action._actionManager = this;
  42991. action._prepare();
  42992. return action;
  42993. };
  42994. /**
  42995. * Process a specific trigger
  42996. * @param {number} trigger - the trigger to process
  42997. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42998. */
  42999. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43000. for (var index = 0; index < this.actions.length; index++) {
  43001. var action = this.actions[index];
  43002. if (action.trigger === trigger) {
  43003. if (evt) {
  43004. if (trigger === ActionManager.OnKeyUpTrigger
  43005. || trigger === ActionManager.OnKeyDownTrigger) {
  43006. var parameter = action.getTriggerParameter();
  43007. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43008. if (!parameter.toLowerCase) {
  43009. continue;
  43010. }
  43011. var lowerCase = parameter.toLowerCase();
  43012. if (lowerCase !== evt.sourceEvent.key) {
  43013. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43014. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43015. if (actualkey !== lowerCase) {
  43016. continue;
  43017. }
  43018. }
  43019. }
  43020. }
  43021. }
  43022. action._executeCurrent(evt);
  43023. }
  43024. }
  43025. };
  43026. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43027. var properties = propertyPath.split(".");
  43028. for (var index = 0; index < properties.length - 1; index++) {
  43029. target = target[properties[index]];
  43030. }
  43031. return target;
  43032. };
  43033. ActionManager.prototype._getProperty = function (propertyPath) {
  43034. var properties = propertyPath.split(".");
  43035. return properties[properties.length - 1];
  43036. };
  43037. ActionManager.prototype.serialize = function (name) {
  43038. var root = {
  43039. children: new Array(),
  43040. name: name,
  43041. type: 3,
  43042. properties: new Array() // Empty for root but required
  43043. };
  43044. for (var i = 0; i < this.actions.length; i++) {
  43045. var triggerObject = {
  43046. type: 0,
  43047. children: new Array(),
  43048. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43049. properties: new Array()
  43050. };
  43051. var triggerOptions = this.actions[i].triggerOptions;
  43052. if (triggerOptions && typeof triggerOptions !== "number") {
  43053. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43054. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43055. }
  43056. else {
  43057. var parameter = {};
  43058. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43059. if (triggerOptions.parameter.mesh) {
  43060. parameter._meshId = triggerOptions.parameter.mesh.id;
  43061. }
  43062. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43063. }
  43064. }
  43065. // Serialize child action, recursively
  43066. this.actions[i].serialize(triggerObject);
  43067. // Add serialized trigger
  43068. root.children.push(triggerObject);
  43069. }
  43070. return root;
  43071. };
  43072. ActionManager.Parse = function (parsedActions, object, scene) {
  43073. var actionManager = new BABYLON.ActionManager(scene);
  43074. if (object === null)
  43075. scene.actionManager = actionManager;
  43076. else
  43077. object.actionManager = actionManager;
  43078. // instanciate a new object
  43079. var instanciate = function (name, params) {
  43080. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43081. newInstance.constructor.apply(newInstance, params);
  43082. return newInstance;
  43083. };
  43084. var parseParameter = function (name, value, target, propertyPath) {
  43085. if (propertyPath === null) {
  43086. // String, boolean or float
  43087. var floatValue = parseFloat(value);
  43088. if (value === "true" || value === "false")
  43089. return value === "true";
  43090. else
  43091. return isNaN(floatValue) ? value : floatValue;
  43092. }
  43093. var effectiveTarget = propertyPath.split(".");
  43094. var values = value.split(",");
  43095. // Get effective Target
  43096. for (var i = 0; i < effectiveTarget.length; i++) {
  43097. target = target[effectiveTarget[i]];
  43098. }
  43099. // Return appropriate value with its type
  43100. if (typeof (target) === "boolean")
  43101. return values[0] === "true";
  43102. if (typeof (target) === "string")
  43103. return values[0];
  43104. // Parameters with multiple values such as Vector3 etc.
  43105. var split = new Array();
  43106. for (var i = 0; i < values.length; i++)
  43107. split.push(parseFloat(values[i]));
  43108. if (target instanceof BABYLON.Vector3)
  43109. return BABYLON.Vector3.FromArray(split);
  43110. if (target instanceof BABYLON.Vector4)
  43111. return BABYLON.Vector4.FromArray(split);
  43112. if (target instanceof BABYLON.Color3)
  43113. return BABYLON.Color3.FromArray(split);
  43114. if (target instanceof BABYLON.Color4)
  43115. return BABYLON.Color4.FromArray(split);
  43116. return parseFloat(values[0]);
  43117. };
  43118. // traverse graph per trigger
  43119. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43120. if (combineArray === void 0) { combineArray = null; }
  43121. if (parsedAction.detached)
  43122. return;
  43123. var parameters = new Array();
  43124. var target = null;
  43125. var propertyPath = null;
  43126. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43127. // Parameters
  43128. if (parsedAction.type === 2)
  43129. parameters.push(actionManager);
  43130. else
  43131. parameters.push(trigger);
  43132. if (combine) {
  43133. var actions = new Array();
  43134. for (var j = 0; j < parsedAction.combine.length; j++) {
  43135. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43136. }
  43137. parameters.push(actions);
  43138. }
  43139. else {
  43140. for (var i = 0; i < parsedAction.properties.length; i++) {
  43141. var value = parsedAction.properties[i].value;
  43142. var name = parsedAction.properties[i].name;
  43143. var targetType = parsedAction.properties[i].targetType;
  43144. if (name === "target")
  43145. if (targetType !== null && targetType === "SceneProperties")
  43146. value = target = scene;
  43147. else
  43148. value = target = scene.getNodeByName(value);
  43149. else if (name === "parent")
  43150. value = scene.getNodeByName(value);
  43151. else if (name === "sound")
  43152. value = scene.getSoundByName(value);
  43153. else if (name !== "propertyPath") {
  43154. if (parsedAction.type === 2 && name === "operator")
  43155. value = BABYLON.ValueCondition[value];
  43156. else
  43157. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43158. }
  43159. else {
  43160. propertyPath = value;
  43161. }
  43162. parameters.push(value);
  43163. }
  43164. }
  43165. if (combineArray === null) {
  43166. parameters.push(condition);
  43167. }
  43168. else {
  43169. parameters.push(null);
  43170. }
  43171. // If interpolate value action
  43172. if (parsedAction.name === "InterpolateValueAction") {
  43173. var param = parameters[parameters.length - 2];
  43174. parameters[parameters.length - 1] = param;
  43175. parameters[parameters.length - 2] = condition;
  43176. }
  43177. // Action or condition(s) and not CombineAction
  43178. var newAction = instanciate(parsedAction.name, parameters);
  43179. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43180. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43181. if (action)
  43182. action.then(nothing);
  43183. else
  43184. actionManager.registerAction(nothing);
  43185. action = nothing;
  43186. }
  43187. if (combineArray === null) {
  43188. if (newAction instanceof BABYLON.Condition) {
  43189. condition = newAction;
  43190. newAction = action;
  43191. }
  43192. else {
  43193. condition = null;
  43194. if (action)
  43195. action.then(newAction);
  43196. else
  43197. actionManager.registerAction(newAction);
  43198. }
  43199. }
  43200. else {
  43201. combineArray.push(newAction);
  43202. }
  43203. for (var i = 0; i < parsedAction.children.length; i++)
  43204. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43205. };
  43206. // triggers
  43207. for (var i = 0; i < parsedActions.children.length; i++) {
  43208. var triggerParams;
  43209. var trigger = parsedActions.children[i];
  43210. if (trigger.properties.length > 0) {
  43211. var param = trigger.properties[0].value;
  43212. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43213. if (value._meshId) {
  43214. value.mesh = scene.getMeshByID(value._meshId);
  43215. }
  43216. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43217. }
  43218. else
  43219. triggerParams = ActionManager[trigger.name];
  43220. for (var j = 0; j < trigger.children.length; j++) {
  43221. if (!trigger.detached)
  43222. traverse(trigger.children[j], triggerParams, null, null);
  43223. }
  43224. }
  43225. };
  43226. ActionManager.GetTriggerName = function (trigger) {
  43227. switch (trigger) {
  43228. case 0: return "NothingTrigger";
  43229. case 1: return "OnPickTrigger";
  43230. case 2: return "OnLeftPickTrigger";
  43231. case 3: return "OnRightPickTrigger";
  43232. case 4: return "OnCenterPickTrigger";
  43233. case 5: return "OnPickDownTrigger";
  43234. case 6: return "OnPickUpTrigger";
  43235. case 7: return "OnLongPressTrigger";
  43236. case 8: return "OnPointerOverTrigger";
  43237. case 9: return "OnPointerOutTrigger";
  43238. case 10: return "OnEveryFrameTrigger";
  43239. case 11: return "OnIntersectionEnterTrigger";
  43240. case 12: return "OnIntersectionExitTrigger";
  43241. case 13: return "OnKeyDownTrigger";
  43242. case 14: return "OnKeyUpTrigger";
  43243. case 15: return "OnPickOutTrigger";
  43244. default: return "";
  43245. }
  43246. };
  43247. // Statics
  43248. ActionManager._NothingTrigger = 0;
  43249. ActionManager._OnPickTrigger = 1;
  43250. ActionManager._OnLeftPickTrigger = 2;
  43251. ActionManager._OnRightPickTrigger = 3;
  43252. ActionManager._OnCenterPickTrigger = 4;
  43253. ActionManager._OnPickDownTrigger = 5;
  43254. ActionManager._OnDoublePickTrigger = 6;
  43255. ActionManager._OnPickUpTrigger = 7;
  43256. ActionManager._OnLongPressTrigger = 8;
  43257. ActionManager._OnPointerOverTrigger = 9;
  43258. ActionManager._OnPointerOutTrigger = 10;
  43259. ActionManager._OnEveryFrameTrigger = 11;
  43260. ActionManager._OnIntersectionEnterTrigger = 12;
  43261. ActionManager._OnIntersectionExitTrigger = 13;
  43262. ActionManager._OnKeyDownTrigger = 14;
  43263. ActionManager._OnKeyUpTrigger = 15;
  43264. ActionManager._OnPickOutTrigger = 16;
  43265. ActionManager.Triggers = {};
  43266. return ActionManager;
  43267. }());
  43268. BABYLON.ActionManager = ActionManager;
  43269. })(BABYLON || (BABYLON = {}));
  43270. //# sourceMappingURL=babylon.actionManager.js.map
  43271. var BABYLON;
  43272. (function (BABYLON) {
  43273. var InterpolateValueAction = /** @class */ (function (_super) {
  43274. __extends(InterpolateValueAction, _super);
  43275. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43276. if (duration === void 0) { duration = 1000; }
  43277. var _this = _super.call(this, triggerOptions, condition) || this;
  43278. _this.propertyPath = propertyPath;
  43279. _this.value = value;
  43280. _this.duration = duration;
  43281. _this.stopOtherAnimations = stopOtherAnimations;
  43282. _this.onInterpolationDone = onInterpolationDone;
  43283. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43284. _this._target = _this._effectiveTarget = target;
  43285. return _this;
  43286. }
  43287. InterpolateValueAction.prototype._prepare = function () {
  43288. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43289. this._property = this._getProperty(this.propertyPath);
  43290. };
  43291. InterpolateValueAction.prototype.execute = function () {
  43292. var _this = this;
  43293. var scene = this._actionManager.getScene();
  43294. var keys = [
  43295. {
  43296. frame: 0,
  43297. value: this._effectiveTarget[this._property]
  43298. }, {
  43299. frame: 100,
  43300. value: this.value
  43301. }
  43302. ];
  43303. var dataType;
  43304. if (typeof this.value === "number") {
  43305. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43306. }
  43307. else if (this.value instanceof BABYLON.Color3) {
  43308. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43309. }
  43310. else if (this.value instanceof BABYLON.Vector3) {
  43311. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43312. }
  43313. else if (this.value instanceof BABYLON.Matrix) {
  43314. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43315. }
  43316. else if (this.value instanceof BABYLON.Quaternion) {
  43317. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43318. }
  43319. else {
  43320. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43321. return;
  43322. }
  43323. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43324. animation.setKeys(keys);
  43325. if (this.stopOtherAnimations) {
  43326. scene.stopAnimation(this._effectiveTarget);
  43327. }
  43328. var wrapper = function () {
  43329. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43330. if (_this.onInterpolationDone) {
  43331. _this.onInterpolationDone();
  43332. }
  43333. };
  43334. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43335. };
  43336. InterpolateValueAction.prototype.serialize = function (parent) {
  43337. return _super.prototype._serialize.call(this, {
  43338. name: "InterpolateValueAction",
  43339. properties: [
  43340. BABYLON.Action._GetTargetProperty(this._target),
  43341. { name: "propertyPath", value: this.propertyPath },
  43342. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43343. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43344. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43345. ]
  43346. }, parent);
  43347. };
  43348. return InterpolateValueAction;
  43349. }(BABYLON.Action));
  43350. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43351. })(BABYLON || (BABYLON = {}));
  43352. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43353. var BABYLON;
  43354. (function (BABYLON) {
  43355. var SwitchBooleanAction = /** @class */ (function (_super) {
  43356. __extends(SwitchBooleanAction, _super);
  43357. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43358. var _this = _super.call(this, triggerOptions, condition) || this;
  43359. _this.propertyPath = propertyPath;
  43360. _this._target = _this._effectiveTarget = target;
  43361. return _this;
  43362. }
  43363. SwitchBooleanAction.prototype._prepare = function () {
  43364. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43365. this._property = this._getProperty(this.propertyPath);
  43366. };
  43367. SwitchBooleanAction.prototype.execute = function () {
  43368. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43369. };
  43370. SwitchBooleanAction.prototype.serialize = function (parent) {
  43371. return _super.prototype._serialize.call(this, {
  43372. name: "SwitchBooleanAction",
  43373. properties: [
  43374. BABYLON.Action._GetTargetProperty(this._target),
  43375. { name: "propertyPath", value: this.propertyPath }
  43376. ]
  43377. }, parent);
  43378. };
  43379. return SwitchBooleanAction;
  43380. }(BABYLON.Action));
  43381. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43382. var SetStateAction = /** @class */ (function (_super) {
  43383. __extends(SetStateAction, _super);
  43384. function SetStateAction(triggerOptions, target, value, condition) {
  43385. var _this = _super.call(this, triggerOptions, condition) || this;
  43386. _this.value = value;
  43387. _this._target = target;
  43388. return _this;
  43389. }
  43390. SetStateAction.prototype.execute = function () {
  43391. this._target.state = this.value;
  43392. };
  43393. SetStateAction.prototype.serialize = function (parent) {
  43394. return _super.prototype._serialize.call(this, {
  43395. name: "SetStateAction",
  43396. properties: [
  43397. BABYLON.Action._GetTargetProperty(this._target),
  43398. { name: "value", value: this.value }
  43399. ]
  43400. }, parent);
  43401. };
  43402. return SetStateAction;
  43403. }(BABYLON.Action));
  43404. BABYLON.SetStateAction = SetStateAction;
  43405. var SetValueAction = /** @class */ (function (_super) {
  43406. __extends(SetValueAction, _super);
  43407. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43408. var _this = _super.call(this, triggerOptions, condition) || this;
  43409. _this.propertyPath = propertyPath;
  43410. _this.value = value;
  43411. _this._target = _this._effectiveTarget = target;
  43412. return _this;
  43413. }
  43414. SetValueAction.prototype._prepare = function () {
  43415. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43416. this._property = this._getProperty(this.propertyPath);
  43417. };
  43418. SetValueAction.prototype.execute = function () {
  43419. this._effectiveTarget[this._property] = this.value;
  43420. if (this._target.markAsDirty) {
  43421. this._target.markAsDirty(this._property);
  43422. }
  43423. };
  43424. SetValueAction.prototype.serialize = function (parent) {
  43425. return _super.prototype._serialize.call(this, {
  43426. name: "SetValueAction",
  43427. properties: [
  43428. BABYLON.Action._GetTargetProperty(this._target),
  43429. { name: "propertyPath", value: this.propertyPath },
  43430. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43431. ]
  43432. }, parent);
  43433. };
  43434. return SetValueAction;
  43435. }(BABYLON.Action));
  43436. BABYLON.SetValueAction = SetValueAction;
  43437. var IncrementValueAction = /** @class */ (function (_super) {
  43438. __extends(IncrementValueAction, _super);
  43439. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43440. var _this = _super.call(this, triggerOptions, condition) || this;
  43441. _this.propertyPath = propertyPath;
  43442. _this.value = value;
  43443. _this._target = _this._effectiveTarget = target;
  43444. return _this;
  43445. }
  43446. IncrementValueAction.prototype._prepare = function () {
  43447. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43448. this._property = this._getProperty(this.propertyPath);
  43449. if (typeof this._effectiveTarget[this._property] !== "number") {
  43450. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43451. }
  43452. };
  43453. IncrementValueAction.prototype.execute = function () {
  43454. this._effectiveTarget[this._property] += this.value;
  43455. if (this._target.markAsDirty) {
  43456. this._target.markAsDirty(this._property);
  43457. }
  43458. };
  43459. IncrementValueAction.prototype.serialize = function (parent) {
  43460. return _super.prototype._serialize.call(this, {
  43461. name: "IncrementValueAction",
  43462. properties: [
  43463. BABYLON.Action._GetTargetProperty(this._target),
  43464. { name: "propertyPath", value: this.propertyPath },
  43465. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43466. ]
  43467. }, parent);
  43468. };
  43469. return IncrementValueAction;
  43470. }(BABYLON.Action));
  43471. BABYLON.IncrementValueAction = IncrementValueAction;
  43472. var PlayAnimationAction = /** @class */ (function (_super) {
  43473. __extends(PlayAnimationAction, _super);
  43474. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43475. var _this = _super.call(this, triggerOptions, condition) || this;
  43476. _this.from = from;
  43477. _this.to = to;
  43478. _this.loop = loop;
  43479. _this._target = target;
  43480. return _this;
  43481. }
  43482. PlayAnimationAction.prototype._prepare = function () {
  43483. };
  43484. PlayAnimationAction.prototype.execute = function () {
  43485. var scene = this._actionManager.getScene();
  43486. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43487. };
  43488. PlayAnimationAction.prototype.serialize = function (parent) {
  43489. return _super.prototype._serialize.call(this, {
  43490. name: "PlayAnimationAction",
  43491. properties: [
  43492. BABYLON.Action._GetTargetProperty(this._target),
  43493. { name: "from", value: String(this.from) },
  43494. { name: "to", value: String(this.to) },
  43495. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43496. ]
  43497. }, parent);
  43498. };
  43499. return PlayAnimationAction;
  43500. }(BABYLON.Action));
  43501. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43502. var StopAnimationAction = /** @class */ (function (_super) {
  43503. __extends(StopAnimationAction, _super);
  43504. function StopAnimationAction(triggerOptions, target, condition) {
  43505. var _this = _super.call(this, triggerOptions, condition) || this;
  43506. _this._target = target;
  43507. return _this;
  43508. }
  43509. StopAnimationAction.prototype._prepare = function () {
  43510. };
  43511. StopAnimationAction.prototype.execute = function () {
  43512. var scene = this._actionManager.getScene();
  43513. scene.stopAnimation(this._target);
  43514. };
  43515. StopAnimationAction.prototype.serialize = function (parent) {
  43516. return _super.prototype._serialize.call(this, {
  43517. name: "StopAnimationAction",
  43518. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43519. }, parent);
  43520. };
  43521. return StopAnimationAction;
  43522. }(BABYLON.Action));
  43523. BABYLON.StopAnimationAction = StopAnimationAction;
  43524. var DoNothingAction = /** @class */ (function (_super) {
  43525. __extends(DoNothingAction, _super);
  43526. function DoNothingAction(triggerOptions, condition) {
  43527. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43528. return _super.call(this, triggerOptions, condition) || this;
  43529. }
  43530. DoNothingAction.prototype.execute = function () {
  43531. };
  43532. DoNothingAction.prototype.serialize = function (parent) {
  43533. return _super.prototype._serialize.call(this, {
  43534. name: "DoNothingAction",
  43535. properties: []
  43536. }, parent);
  43537. };
  43538. return DoNothingAction;
  43539. }(BABYLON.Action));
  43540. BABYLON.DoNothingAction = DoNothingAction;
  43541. var CombineAction = /** @class */ (function (_super) {
  43542. __extends(CombineAction, _super);
  43543. function CombineAction(triggerOptions, children, condition) {
  43544. var _this = _super.call(this, triggerOptions, condition) || this;
  43545. _this.children = children;
  43546. return _this;
  43547. }
  43548. CombineAction.prototype._prepare = function () {
  43549. for (var index = 0; index < this.children.length; index++) {
  43550. this.children[index]._actionManager = this._actionManager;
  43551. this.children[index]._prepare();
  43552. }
  43553. };
  43554. CombineAction.prototype.execute = function (evt) {
  43555. for (var index = 0; index < this.children.length; index++) {
  43556. this.children[index].execute(evt);
  43557. }
  43558. };
  43559. CombineAction.prototype.serialize = function (parent) {
  43560. var serializationObject = _super.prototype._serialize.call(this, {
  43561. name: "CombineAction",
  43562. properties: [],
  43563. combine: []
  43564. }, parent);
  43565. for (var i = 0; i < this.children.length; i++) {
  43566. serializationObject.combine.push(this.children[i].serialize(null));
  43567. }
  43568. return serializationObject;
  43569. };
  43570. return CombineAction;
  43571. }(BABYLON.Action));
  43572. BABYLON.CombineAction = CombineAction;
  43573. var ExecuteCodeAction = /** @class */ (function (_super) {
  43574. __extends(ExecuteCodeAction, _super);
  43575. function ExecuteCodeAction(triggerOptions, func, condition) {
  43576. var _this = _super.call(this, triggerOptions, condition) || this;
  43577. _this.func = func;
  43578. return _this;
  43579. }
  43580. ExecuteCodeAction.prototype.execute = function (evt) {
  43581. this.func(evt);
  43582. };
  43583. return ExecuteCodeAction;
  43584. }(BABYLON.Action));
  43585. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43586. var SetParentAction = /** @class */ (function (_super) {
  43587. __extends(SetParentAction, _super);
  43588. function SetParentAction(triggerOptions, target, parent, condition) {
  43589. var _this = _super.call(this, triggerOptions, condition) || this;
  43590. _this._target = target;
  43591. _this._parent = parent;
  43592. return _this;
  43593. }
  43594. SetParentAction.prototype._prepare = function () {
  43595. };
  43596. SetParentAction.prototype.execute = function () {
  43597. if (this._target.parent === this._parent) {
  43598. return;
  43599. }
  43600. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43601. invertParentWorldMatrix.invert();
  43602. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43603. this._target.parent = this._parent;
  43604. };
  43605. SetParentAction.prototype.serialize = function (parent) {
  43606. return _super.prototype._serialize.call(this, {
  43607. name: "SetParentAction",
  43608. properties: [
  43609. BABYLON.Action._GetTargetProperty(this._target),
  43610. BABYLON.Action._GetTargetProperty(this._parent),
  43611. ]
  43612. }, parent);
  43613. };
  43614. return SetParentAction;
  43615. }(BABYLON.Action));
  43616. BABYLON.SetParentAction = SetParentAction;
  43617. var PlaySoundAction = /** @class */ (function (_super) {
  43618. __extends(PlaySoundAction, _super);
  43619. function PlaySoundAction(triggerOptions, sound, condition) {
  43620. var _this = _super.call(this, triggerOptions, condition) || this;
  43621. _this._sound = sound;
  43622. return _this;
  43623. }
  43624. PlaySoundAction.prototype._prepare = function () {
  43625. };
  43626. PlaySoundAction.prototype.execute = function () {
  43627. if (this._sound !== undefined)
  43628. this._sound.play();
  43629. };
  43630. PlaySoundAction.prototype.serialize = function (parent) {
  43631. return _super.prototype._serialize.call(this, {
  43632. name: "PlaySoundAction",
  43633. properties: [{ name: "sound", value: this._sound.name }]
  43634. }, parent);
  43635. };
  43636. return PlaySoundAction;
  43637. }(BABYLON.Action));
  43638. BABYLON.PlaySoundAction = PlaySoundAction;
  43639. var StopSoundAction = /** @class */ (function (_super) {
  43640. __extends(StopSoundAction, _super);
  43641. function StopSoundAction(triggerOptions, sound, condition) {
  43642. var _this = _super.call(this, triggerOptions, condition) || this;
  43643. _this._sound = sound;
  43644. return _this;
  43645. }
  43646. StopSoundAction.prototype._prepare = function () {
  43647. };
  43648. StopSoundAction.prototype.execute = function () {
  43649. if (this._sound !== undefined)
  43650. this._sound.stop();
  43651. };
  43652. StopSoundAction.prototype.serialize = function (parent) {
  43653. return _super.prototype._serialize.call(this, {
  43654. name: "StopSoundAction",
  43655. properties: [{ name: "sound", value: this._sound.name }]
  43656. }, parent);
  43657. };
  43658. return StopSoundAction;
  43659. }(BABYLON.Action));
  43660. BABYLON.StopSoundAction = StopSoundAction;
  43661. })(BABYLON || (BABYLON = {}));
  43662. //# sourceMappingURL=babylon.directActions.js.map
  43663. var BABYLON;
  43664. (function (BABYLON) {
  43665. var SpriteManager = /** @class */ (function () {
  43666. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43667. if (epsilon === void 0) { epsilon = 0.01; }
  43668. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43669. this.name = name;
  43670. this.sprites = new Array();
  43671. this.renderingGroupId = 0;
  43672. this.layerMask = 0x0FFFFFFF;
  43673. this.fogEnabled = true;
  43674. this.isPickable = false;
  43675. /**
  43676. * An event triggered when the manager is disposed.
  43677. * @type {BABYLON.Observable}
  43678. */
  43679. this.onDisposeObservable = new BABYLON.Observable();
  43680. this._vertexBuffers = {};
  43681. this._capacity = capacity;
  43682. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43683. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43684. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43685. if (cellSize.width && cellSize.height) {
  43686. this.cellWidth = cellSize.width;
  43687. this.cellHeight = cellSize.height;
  43688. }
  43689. else if (cellSize !== undefined) {
  43690. this.cellWidth = cellSize;
  43691. this.cellHeight = cellSize;
  43692. }
  43693. else {
  43694. return;
  43695. }
  43696. this._epsilon = epsilon;
  43697. this._scene = scene;
  43698. this._scene.spriteManagers.push(this);
  43699. var indices = [];
  43700. var index = 0;
  43701. for (var count = 0; count < capacity; count++) {
  43702. indices.push(index);
  43703. indices.push(index + 1);
  43704. indices.push(index + 2);
  43705. indices.push(index);
  43706. indices.push(index + 2);
  43707. indices.push(index + 3);
  43708. index += 4;
  43709. }
  43710. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43711. // VBO
  43712. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43713. this._vertexData = new Float32Array(capacity * 16 * 4);
  43714. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43715. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43716. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43717. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43718. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43720. this._vertexBuffers["options"] = options;
  43721. this._vertexBuffers["cellInfo"] = cellInfo;
  43722. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43723. // Effects
  43724. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43725. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43726. }
  43727. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43728. set: function (callback) {
  43729. if (this._onDisposeObserver) {
  43730. this.onDisposeObservable.remove(this._onDisposeObserver);
  43731. }
  43732. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43733. },
  43734. enumerable: true,
  43735. configurable: true
  43736. });
  43737. Object.defineProperty(SpriteManager.prototype, "texture", {
  43738. get: function () {
  43739. return this._spriteTexture;
  43740. },
  43741. set: function (value) {
  43742. this._spriteTexture = value;
  43743. },
  43744. enumerable: true,
  43745. configurable: true
  43746. });
  43747. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43748. var arrayOffset = index * 16;
  43749. if (offsetX === 0)
  43750. offsetX = this._epsilon;
  43751. else if (offsetX === 1)
  43752. offsetX = 1 - this._epsilon;
  43753. if (offsetY === 0)
  43754. offsetY = this._epsilon;
  43755. else if (offsetY === 1)
  43756. offsetY = 1 - this._epsilon;
  43757. this._vertexData[arrayOffset] = sprite.position.x;
  43758. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43759. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43760. this._vertexData[arrayOffset + 3] = sprite.angle;
  43761. this._vertexData[arrayOffset + 4] = sprite.width;
  43762. this._vertexData[arrayOffset + 5] = sprite.height;
  43763. this._vertexData[arrayOffset + 6] = offsetX;
  43764. this._vertexData[arrayOffset + 7] = offsetY;
  43765. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43766. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43767. var offset = (sprite.cellIndex / rowSize) >> 0;
  43768. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43769. this._vertexData[arrayOffset + 11] = offset;
  43770. // Color
  43771. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43772. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43773. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43774. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43775. };
  43776. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43777. var count = Math.min(this._capacity, this.sprites.length);
  43778. var min = BABYLON.Vector3.Zero();
  43779. var max = BABYLON.Vector3.Zero();
  43780. var distance = Number.MAX_VALUE;
  43781. var currentSprite = null;
  43782. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43783. var cameraView = camera.getViewMatrix();
  43784. for (var index = 0; index < count; index++) {
  43785. var sprite = this.sprites[index];
  43786. if (!sprite) {
  43787. continue;
  43788. }
  43789. if (predicate) {
  43790. if (!predicate(sprite)) {
  43791. continue;
  43792. }
  43793. }
  43794. else if (!sprite.isPickable) {
  43795. continue;
  43796. }
  43797. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43798. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43799. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43800. if (ray.intersectsBoxMinMax(min, max)) {
  43801. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43802. if (distance > currentDistance) {
  43803. distance = currentDistance;
  43804. currentSprite = sprite;
  43805. if (fastCheck) {
  43806. break;
  43807. }
  43808. }
  43809. }
  43810. }
  43811. if (currentSprite) {
  43812. var result = new BABYLON.PickingInfo();
  43813. result.hit = true;
  43814. result.pickedSprite = currentSprite;
  43815. result.distance = distance;
  43816. return result;
  43817. }
  43818. return null;
  43819. };
  43820. SpriteManager.prototype.render = function () {
  43821. // Check
  43822. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43823. return;
  43824. var engine = this._scene.getEngine();
  43825. var baseSize = this._spriteTexture.getBaseSize();
  43826. // Sprites
  43827. var deltaTime = engine.getDeltaTime();
  43828. var max = Math.min(this._capacity, this.sprites.length);
  43829. var rowSize = baseSize.width / this.cellWidth;
  43830. var offset = 0;
  43831. for (var index = 0; index < max; index++) {
  43832. var sprite = this.sprites[index];
  43833. if (!sprite) {
  43834. continue;
  43835. }
  43836. sprite._animate(deltaTime);
  43837. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43838. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43839. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43840. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43841. }
  43842. this._buffer.update(this._vertexData);
  43843. // Render
  43844. var effect = this._effectBase;
  43845. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43846. effect = this._effectFog;
  43847. }
  43848. engine.enableEffect(effect);
  43849. var viewMatrix = this._scene.getViewMatrix();
  43850. effect.setTexture("diffuseSampler", this._spriteTexture);
  43851. effect.setMatrix("view", viewMatrix);
  43852. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43853. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43854. // Fog
  43855. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43856. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43857. effect.setColor3("vFogColor", this._scene.fogColor);
  43858. }
  43859. // VBOs
  43860. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43861. // Draw order
  43862. engine.setDepthFunctionToLessOrEqual();
  43863. effect.setBool("alphaTest", true);
  43864. engine.setColorWrite(false);
  43865. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  43866. engine.setColorWrite(true);
  43867. effect.setBool("alphaTest", false);
  43868. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43869. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  43870. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43871. };
  43872. SpriteManager.prototype.dispose = function () {
  43873. if (this._buffer) {
  43874. this._buffer.dispose();
  43875. this._buffer = null;
  43876. }
  43877. if (this._indexBuffer) {
  43878. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43879. this._indexBuffer = null;
  43880. }
  43881. if (this._spriteTexture) {
  43882. this._spriteTexture.dispose();
  43883. this._spriteTexture = null;
  43884. }
  43885. // Remove from scene
  43886. var index = this._scene.spriteManagers.indexOf(this);
  43887. this._scene.spriteManagers.splice(index, 1);
  43888. // Callback
  43889. this.onDisposeObservable.notifyObservers(this);
  43890. this.onDisposeObservable.clear();
  43891. };
  43892. return SpriteManager;
  43893. }());
  43894. BABYLON.SpriteManager = SpriteManager;
  43895. })(BABYLON || (BABYLON = {}));
  43896. //# sourceMappingURL=babylon.spriteManager.js.map
  43897. var BABYLON;
  43898. (function (BABYLON) {
  43899. var Sprite = /** @class */ (function () {
  43900. function Sprite(name, manager) {
  43901. this.name = name;
  43902. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43903. this.width = 1.0;
  43904. this.height = 1.0;
  43905. this.angle = 0;
  43906. this.cellIndex = 0;
  43907. this.invertU = 0;
  43908. this.invertV = 0;
  43909. this.animations = new Array();
  43910. this.isPickable = false;
  43911. this._animationStarted = false;
  43912. this._loopAnimation = false;
  43913. this._fromIndex = 0;
  43914. this._toIndex = 0;
  43915. this._delay = 0;
  43916. this._direction = 1;
  43917. this._time = 0;
  43918. this._manager = manager;
  43919. this._manager.sprites.push(this);
  43920. this.position = BABYLON.Vector3.Zero();
  43921. }
  43922. Object.defineProperty(Sprite.prototype, "size", {
  43923. get: function () {
  43924. return this.width;
  43925. },
  43926. set: function (value) {
  43927. this.width = value;
  43928. this.height = value;
  43929. },
  43930. enumerable: true,
  43931. configurable: true
  43932. });
  43933. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43934. this._fromIndex = from;
  43935. this._toIndex = to;
  43936. this._loopAnimation = loop;
  43937. this._delay = delay;
  43938. this._animationStarted = true;
  43939. this._direction = from < to ? 1 : -1;
  43940. this.cellIndex = from;
  43941. this._time = 0;
  43942. this._onAnimationEnd = onAnimationEnd;
  43943. };
  43944. Sprite.prototype.stopAnimation = function () {
  43945. this._animationStarted = false;
  43946. };
  43947. Sprite.prototype._animate = function (deltaTime) {
  43948. if (!this._animationStarted)
  43949. return;
  43950. this._time += deltaTime;
  43951. if (this._time > this._delay) {
  43952. this._time = this._time % this._delay;
  43953. this.cellIndex += this._direction;
  43954. if (this.cellIndex > this._toIndex) {
  43955. if (this._loopAnimation) {
  43956. this.cellIndex = this._fromIndex;
  43957. }
  43958. else {
  43959. this.cellIndex = this._toIndex;
  43960. this._animationStarted = false;
  43961. if (this._onAnimationEnd) {
  43962. this._onAnimationEnd();
  43963. }
  43964. if (this.disposeWhenFinishedAnimating) {
  43965. this.dispose();
  43966. }
  43967. }
  43968. }
  43969. }
  43970. };
  43971. Sprite.prototype.dispose = function () {
  43972. for (var i = 0; i < this._manager.sprites.length; i++) {
  43973. if (this._manager.sprites[i] == this) {
  43974. this._manager.sprites.splice(i, 1);
  43975. }
  43976. }
  43977. };
  43978. return Sprite;
  43979. }());
  43980. BABYLON.Sprite = Sprite;
  43981. })(BABYLON || (BABYLON = {}));
  43982. //# sourceMappingURL=babylon.sprite.js.map
  43983. var BABYLON;
  43984. (function (BABYLON) {
  43985. var IntersectionInfo = /** @class */ (function () {
  43986. function IntersectionInfo(bu, bv, distance) {
  43987. this.bu = bu;
  43988. this.bv = bv;
  43989. this.distance = distance;
  43990. this.faceId = 0;
  43991. this.subMeshId = 0;
  43992. }
  43993. return IntersectionInfo;
  43994. }());
  43995. BABYLON.IntersectionInfo = IntersectionInfo;
  43996. var PickingInfo = /** @class */ (function () {
  43997. function PickingInfo() {
  43998. this.hit = false;
  43999. this.distance = 0;
  44000. this.pickedPoint = null;
  44001. this.pickedMesh = null;
  44002. this.bu = 0;
  44003. this.bv = 0;
  44004. this.faceId = -1;
  44005. this.subMeshId = 0;
  44006. this.pickedSprite = null;
  44007. }
  44008. // Methods
  44009. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44010. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44011. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44012. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44013. return null;
  44014. }
  44015. var indices = this.pickedMesh.getIndices();
  44016. if (!indices) {
  44017. return null;
  44018. }
  44019. var result;
  44020. if (useVerticesNormals) {
  44021. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44022. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44023. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44024. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44025. normal0 = normal0.scale(this.bu);
  44026. normal1 = normal1.scale(this.bv);
  44027. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44028. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44029. }
  44030. else {
  44031. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44032. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44033. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44034. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44035. var p1p2 = vertex1.subtract(vertex2);
  44036. var p3p2 = vertex3.subtract(vertex2);
  44037. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44038. }
  44039. if (useWorldCoordinates) {
  44040. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44041. }
  44042. return BABYLON.Vector3.Normalize(result);
  44043. };
  44044. PickingInfo.prototype.getTextureCoordinates = function () {
  44045. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44046. return null;
  44047. }
  44048. var indices = this.pickedMesh.getIndices();
  44049. if (!indices) {
  44050. return null;
  44051. }
  44052. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44053. if (!uvs) {
  44054. return null;
  44055. }
  44056. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44057. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44058. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44059. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44060. uv1 = uv1.scale(this.bu);
  44061. uv2 = uv2.scale(this.bv);
  44062. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44063. };
  44064. return PickingInfo;
  44065. }());
  44066. BABYLON.PickingInfo = PickingInfo;
  44067. })(BABYLON || (BABYLON = {}));
  44068. //# sourceMappingURL=babylon.pickingInfo.js.map
  44069. var BABYLON;
  44070. (function (BABYLON) {
  44071. var Ray = /** @class */ (function () {
  44072. function Ray(origin, direction, length) {
  44073. if (length === void 0) { length = Number.MAX_VALUE; }
  44074. this.origin = origin;
  44075. this.direction = direction;
  44076. this.length = length;
  44077. }
  44078. // Methods
  44079. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44080. var d = 0.0;
  44081. var maxValue = Number.MAX_VALUE;
  44082. var inv;
  44083. var min;
  44084. var max;
  44085. var temp;
  44086. if (Math.abs(this.direction.x) < 0.0000001) {
  44087. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44088. return false;
  44089. }
  44090. }
  44091. else {
  44092. inv = 1.0 / this.direction.x;
  44093. min = (minimum.x - this.origin.x) * inv;
  44094. max = (maximum.x - this.origin.x) * inv;
  44095. if (max === -Infinity) {
  44096. max = Infinity;
  44097. }
  44098. if (min > max) {
  44099. temp = min;
  44100. min = max;
  44101. max = temp;
  44102. }
  44103. d = Math.max(min, d);
  44104. maxValue = Math.min(max, maxValue);
  44105. if (d > maxValue) {
  44106. return false;
  44107. }
  44108. }
  44109. if (Math.abs(this.direction.y) < 0.0000001) {
  44110. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44111. return false;
  44112. }
  44113. }
  44114. else {
  44115. inv = 1.0 / this.direction.y;
  44116. min = (minimum.y - this.origin.y) * inv;
  44117. max = (maximum.y - this.origin.y) * inv;
  44118. if (max === -Infinity) {
  44119. max = Infinity;
  44120. }
  44121. if (min > max) {
  44122. temp = min;
  44123. min = max;
  44124. max = temp;
  44125. }
  44126. d = Math.max(min, d);
  44127. maxValue = Math.min(max, maxValue);
  44128. if (d > maxValue) {
  44129. return false;
  44130. }
  44131. }
  44132. if (Math.abs(this.direction.z) < 0.0000001) {
  44133. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44134. return false;
  44135. }
  44136. }
  44137. else {
  44138. inv = 1.0 / this.direction.z;
  44139. min = (minimum.z - this.origin.z) * inv;
  44140. max = (maximum.z - this.origin.z) * inv;
  44141. if (max === -Infinity) {
  44142. max = Infinity;
  44143. }
  44144. if (min > max) {
  44145. temp = min;
  44146. min = max;
  44147. max = temp;
  44148. }
  44149. d = Math.max(min, d);
  44150. maxValue = Math.min(max, maxValue);
  44151. if (d > maxValue) {
  44152. return false;
  44153. }
  44154. }
  44155. return true;
  44156. };
  44157. Ray.prototype.intersectsBox = function (box) {
  44158. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44159. };
  44160. Ray.prototype.intersectsSphere = function (sphere) {
  44161. var x = sphere.center.x - this.origin.x;
  44162. var y = sphere.center.y - this.origin.y;
  44163. var z = sphere.center.z - this.origin.z;
  44164. var pyth = (x * x) + (y * y) + (z * z);
  44165. var rr = sphere.radius * sphere.radius;
  44166. if (pyth <= rr) {
  44167. return true;
  44168. }
  44169. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44170. if (dot < 0.0) {
  44171. return false;
  44172. }
  44173. var temp = pyth - (dot * dot);
  44174. return temp <= rr;
  44175. };
  44176. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44177. if (!this._edge1) {
  44178. this._edge1 = BABYLON.Vector3.Zero();
  44179. this._edge2 = BABYLON.Vector3.Zero();
  44180. this._pvec = BABYLON.Vector3.Zero();
  44181. this._tvec = BABYLON.Vector3.Zero();
  44182. this._qvec = BABYLON.Vector3.Zero();
  44183. }
  44184. vertex1.subtractToRef(vertex0, this._edge1);
  44185. vertex2.subtractToRef(vertex0, this._edge2);
  44186. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44187. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44188. if (det === 0) {
  44189. return null;
  44190. }
  44191. var invdet = 1 / det;
  44192. this.origin.subtractToRef(vertex0, this._tvec);
  44193. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44194. if (bu < 0 || bu > 1.0) {
  44195. return null;
  44196. }
  44197. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44198. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44199. if (bv < 0 || bu + bv > 1.0) {
  44200. return null;
  44201. }
  44202. //check if the distance is longer than the predefined length.
  44203. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44204. if (distance > this.length) {
  44205. return null;
  44206. }
  44207. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44208. };
  44209. Ray.prototype.intersectsPlane = function (plane) {
  44210. var distance;
  44211. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44212. if (Math.abs(result1) < 9.99999997475243E-07) {
  44213. return null;
  44214. }
  44215. else {
  44216. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44217. distance = (-plane.d - result2) / result1;
  44218. if (distance < 0.0) {
  44219. if (distance < -9.99999997475243E-07) {
  44220. return null;
  44221. }
  44222. else {
  44223. return 0;
  44224. }
  44225. }
  44226. return distance;
  44227. }
  44228. };
  44229. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  44230. var tm = BABYLON.Tmp.Matrix[0];
  44231. mesh.getWorldMatrix().invertToRef(tm);
  44232. if (this._tmpRay) {
  44233. Ray.TransformToRef(this, tm, this._tmpRay);
  44234. }
  44235. else {
  44236. this._tmpRay = Ray.Transform(this, tm);
  44237. }
  44238. return mesh.intersects(this._tmpRay, fastCheck);
  44239. };
  44240. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  44241. if (results) {
  44242. results.length = 0;
  44243. }
  44244. else {
  44245. results = [];
  44246. }
  44247. for (var i = 0; i < meshes.length; i++) {
  44248. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  44249. if (pickInfo.hit) {
  44250. results.push(pickInfo);
  44251. }
  44252. }
  44253. results.sort(this._comparePickingInfo);
  44254. return results;
  44255. };
  44256. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44257. if (pickingInfoA.distance < pickingInfoB.distance) {
  44258. return -1;
  44259. }
  44260. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44261. return 1;
  44262. }
  44263. else {
  44264. return 0;
  44265. }
  44266. };
  44267. /**
  44268. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44269. * @param sega the first point of the segment to test the intersection against
  44270. * @param segb the second point of the segment to test the intersection against
  44271. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44272. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44273. */
  44274. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44275. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44276. var u = segb.subtract(sega);
  44277. var v = rsegb.subtract(this.origin);
  44278. var w = sega.subtract(this.origin);
  44279. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44280. var b = BABYLON.Vector3.Dot(u, v);
  44281. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44282. var d = BABYLON.Vector3.Dot(u, w);
  44283. var e = BABYLON.Vector3.Dot(v, w);
  44284. var D = a * c - b * b; // always >= 0
  44285. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44286. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44287. // compute the line parameters of the two closest points
  44288. if (D < Ray.smallnum) {
  44289. sN = 0.0; // force using point P0 on segment S1
  44290. sD = 1.0; // to prevent possible division by 0.0 later
  44291. tN = e;
  44292. tD = c;
  44293. }
  44294. else {
  44295. sN = (b * e - c * d);
  44296. tN = (a * e - b * d);
  44297. if (sN < 0.0) {
  44298. sN = 0.0;
  44299. tN = e;
  44300. tD = c;
  44301. }
  44302. else if (sN > sD) {
  44303. sN = sD;
  44304. tN = e + b;
  44305. tD = c;
  44306. }
  44307. }
  44308. if (tN < 0.0) {
  44309. tN = 0.0;
  44310. // recompute sc for this edge
  44311. if (-d < 0.0) {
  44312. sN = 0.0;
  44313. }
  44314. else if (-d > a)
  44315. sN = sD;
  44316. else {
  44317. sN = -d;
  44318. sD = a;
  44319. }
  44320. }
  44321. else if (tN > tD) {
  44322. tN = tD;
  44323. // recompute sc for this edge
  44324. if ((-d + b) < 0.0) {
  44325. sN = 0;
  44326. }
  44327. else if ((-d + b) > a) {
  44328. sN = sD;
  44329. }
  44330. else {
  44331. sN = (-d + b);
  44332. sD = a;
  44333. }
  44334. }
  44335. // finally do the division to get sc and tc
  44336. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44337. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44338. // get the difference of the two closest points
  44339. var qtc = v.multiplyByFloats(tc, tc, tc);
  44340. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44341. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44342. if (isIntersected) {
  44343. return qtc.length();
  44344. }
  44345. return -1;
  44346. };
  44347. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44348. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44349. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44350. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44351. this.direction.normalize();
  44352. return this;
  44353. };
  44354. // Statics
  44355. Ray.Zero = function () {
  44356. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44357. };
  44358. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44359. var result = Ray.Zero();
  44360. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44361. };
  44362. /**
  44363. * 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
  44364. * transformed to the given world matrix.
  44365. * @param origin The origin point
  44366. * @param end The end point
  44367. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44368. */
  44369. Ray.CreateNewFromTo = function (origin, end, world) {
  44370. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44371. var direction = end.subtract(origin);
  44372. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44373. direction.normalize();
  44374. return Ray.Transform(new Ray(origin, direction, length), world);
  44375. };
  44376. Ray.Transform = function (ray, matrix) {
  44377. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44378. Ray.TransformToRef(ray, matrix, result);
  44379. return result;
  44380. };
  44381. Ray.TransformToRef = function (ray, matrix, result) {
  44382. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44383. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44384. result.length = ray.length;
  44385. var dir = result.direction;
  44386. var len = dir.length();
  44387. if (!(len === 0 || len === 1)) {
  44388. var num = 1.0 / len;
  44389. dir.x *= num;
  44390. dir.y *= num;
  44391. dir.z *= num;
  44392. result.length *= len;
  44393. }
  44394. };
  44395. Ray.smallnum = 0.00000001;
  44396. Ray.rayl = 10e8;
  44397. return Ray;
  44398. }());
  44399. BABYLON.Ray = Ray;
  44400. })(BABYLON || (BABYLON = {}));
  44401. //# sourceMappingURL=babylon.ray.js.map
  44402. var BABYLON;
  44403. (function (BABYLON) {
  44404. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44405. if (boxMin.x > sphereCenter.x + sphereRadius)
  44406. return false;
  44407. if (sphereCenter.x - sphereRadius > boxMax.x)
  44408. return false;
  44409. if (boxMin.y > sphereCenter.y + sphereRadius)
  44410. return false;
  44411. if (sphereCenter.y - sphereRadius > boxMax.y)
  44412. return false;
  44413. if (boxMin.z > sphereCenter.z + sphereRadius)
  44414. return false;
  44415. if (sphereCenter.z - sphereRadius > boxMax.z)
  44416. return false;
  44417. return true;
  44418. };
  44419. var getLowestRoot = (function () {
  44420. var result = { root: 0, found: false };
  44421. return function (a, b, c, maxR) {
  44422. result.root = 0;
  44423. result.found = false;
  44424. var determinant = b * b - 4.0 * a * c;
  44425. if (determinant < 0)
  44426. return result;
  44427. var sqrtD = Math.sqrt(determinant);
  44428. var r1 = (-b - sqrtD) / (2.0 * a);
  44429. var r2 = (-b + sqrtD) / (2.0 * a);
  44430. if (r1 > r2) {
  44431. var temp = r2;
  44432. r2 = r1;
  44433. r1 = temp;
  44434. }
  44435. if (r1 > 0 && r1 < maxR) {
  44436. result.root = r1;
  44437. result.found = true;
  44438. return result;
  44439. }
  44440. if (r2 > 0 && r2 < maxR) {
  44441. result.root = r2;
  44442. result.found = true;
  44443. return result;
  44444. }
  44445. return result;
  44446. };
  44447. })();
  44448. var Collider = /** @class */ (function () {
  44449. function Collider() {
  44450. this._collisionPoint = BABYLON.Vector3.Zero();
  44451. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  44452. this._tempVector = BABYLON.Vector3.Zero();
  44453. this._tempVector2 = BABYLON.Vector3.Zero();
  44454. this._tempVector3 = BABYLON.Vector3.Zero();
  44455. this._tempVector4 = BABYLON.Vector3.Zero();
  44456. this._edge = BABYLON.Vector3.Zero();
  44457. this._baseToVertex = BABYLON.Vector3.Zero();
  44458. this._destinationPoint = BABYLON.Vector3.Zero();
  44459. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  44460. this._displacementVector = BABYLON.Vector3.Zero();
  44461. this._radius = BABYLON.Vector3.One();
  44462. this._retry = 0;
  44463. this._basePointWorld = BABYLON.Vector3.Zero();
  44464. this._velocityWorld = BABYLON.Vector3.Zero();
  44465. this._normalizedVelocity = BABYLON.Vector3.Zero();
  44466. this._collisionMask = -1;
  44467. }
  44468. Object.defineProperty(Collider.prototype, "collisionMask", {
  44469. get: function () {
  44470. return this._collisionMask;
  44471. },
  44472. set: function (mask) {
  44473. this._collisionMask = !isNaN(mask) ? mask : -1;
  44474. },
  44475. enumerable: true,
  44476. configurable: true
  44477. });
  44478. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  44479. /**
  44480. * Gets the plane normal used to compute the sliding response (in local space)
  44481. */
  44482. get: function () {
  44483. return this._slidePlaneNormal;
  44484. },
  44485. enumerable: true,
  44486. configurable: true
  44487. });
  44488. // Methods
  44489. Collider.prototype._initialize = function (source, dir, e) {
  44490. this._velocity = dir;
  44491. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  44492. this._basePoint = source;
  44493. source.multiplyToRef(this._radius, this._basePointWorld);
  44494. dir.multiplyToRef(this._radius, this._velocityWorld);
  44495. this._velocityWorldLength = this._velocityWorld.length();
  44496. this._epsilon = e;
  44497. this.collisionFound = false;
  44498. };
  44499. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  44500. pa.subtractToRef(point, this._tempVector);
  44501. pb.subtractToRef(point, this._tempVector2);
  44502. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  44503. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44504. if (d < 0)
  44505. return false;
  44506. pc.subtractToRef(point, this._tempVector3);
  44507. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  44508. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44509. if (d < 0)
  44510. return false;
  44511. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  44512. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  44513. return d >= 0;
  44514. };
  44515. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  44516. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  44517. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  44518. if (distance > this._velocityWorldLength + max + sphereRadius) {
  44519. return false;
  44520. }
  44521. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  44522. return false;
  44523. return true;
  44524. };
  44525. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  44526. var t0;
  44527. var embeddedInPlane = false;
  44528. //defensive programming, actually not needed.
  44529. if (!trianglePlaneArray) {
  44530. trianglePlaneArray = [];
  44531. }
  44532. if (!trianglePlaneArray[faceIndex]) {
  44533. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  44534. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  44535. }
  44536. var trianglePlane = trianglePlaneArray[faceIndex];
  44537. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  44538. return;
  44539. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  44540. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  44541. if (normalDotVelocity == 0) {
  44542. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  44543. return;
  44544. embeddedInPlane = true;
  44545. t0 = 0;
  44546. }
  44547. else {
  44548. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44549. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  44550. if (t0 > t1) {
  44551. var temp = t1;
  44552. t1 = t0;
  44553. t0 = temp;
  44554. }
  44555. if (t0 > 1.0 || t1 < 0.0)
  44556. return;
  44557. if (t0 < 0)
  44558. t0 = 0;
  44559. if (t0 > 1.0)
  44560. t0 = 1.0;
  44561. }
  44562. this._collisionPoint.copyFromFloats(0, 0, 0);
  44563. var found = false;
  44564. var t = 1.0;
  44565. if (!embeddedInPlane) {
  44566. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  44567. this._velocity.scaleToRef(t0, this._tempVector);
  44568. this._planeIntersectionPoint.addInPlace(this._tempVector);
  44569. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  44570. found = true;
  44571. t = t0;
  44572. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  44573. }
  44574. }
  44575. if (!found) {
  44576. var velocitySquaredLength = this._velocity.lengthSquared();
  44577. var a = velocitySquaredLength;
  44578. this._basePoint.subtractToRef(p1, this._tempVector);
  44579. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44580. var c = this._tempVector.lengthSquared() - 1.0;
  44581. var lowestRoot = getLowestRoot(a, b, c, t);
  44582. if (lowestRoot.found) {
  44583. t = lowestRoot.root;
  44584. found = true;
  44585. this._collisionPoint.copyFrom(p1);
  44586. }
  44587. this._basePoint.subtractToRef(p2, this._tempVector);
  44588. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44589. c = this._tempVector.lengthSquared() - 1.0;
  44590. lowestRoot = getLowestRoot(a, b, c, t);
  44591. if (lowestRoot.found) {
  44592. t = lowestRoot.root;
  44593. found = true;
  44594. this._collisionPoint.copyFrom(p2);
  44595. }
  44596. this._basePoint.subtractToRef(p3, this._tempVector);
  44597. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  44598. c = this._tempVector.lengthSquared() - 1.0;
  44599. lowestRoot = getLowestRoot(a, b, c, t);
  44600. if (lowestRoot.found) {
  44601. t = lowestRoot.root;
  44602. found = true;
  44603. this._collisionPoint.copyFrom(p3);
  44604. }
  44605. p2.subtractToRef(p1, this._edge);
  44606. p1.subtractToRef(this._basePoint, this._baseToVertex);
  44607. var edgeSquaredLength = this._edge.lengthSquared();
  44608. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44609. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44610. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44611. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44612. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44613. lowestRoot = getLowestRoot(a, b, c, t);
  44614. if (lowestRoot.found) {
  44615. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44616. if (f >= 0.0 && f <= 1.0) {
  44617. t = lowestRoot.root;
  44618. found = true;
  44619. this._edge.scaleInPlace(f);
  44620. p1.addToRef(this._edge, this._collisionPoint);
  44621. }
  44622. }
  44623. p3.subtractToRef(p2, this._edge);
  44624. p2.subtractToRef(this._basePoint, this._baseToVertex);
  44625. edgeSquaredLength = this._edge.lengthSquared();
  44626. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44627. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44628. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44629. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44630. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44631. lowestRoot = getLowestRoot(a, b, c, t);
  44632. if (lowestRoot.found) {
  44633. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44634. if (f >= 0.0 && f <= 1.0) {
  44635. t = lowestRoot.root;
  44636. found = true;
  44637. this._edge.scaleInPlace(f);
  44638. p2.addToRef(this._edge, this._collisionPoint);
  44639. }
  44640. }
  44641. p1.subtractToRef(p3, this._edge);
  44642. p3.subtractToRef(this._basePoint, this._baseToVertex);
  44643. edgeSquaredLength = this._edge.lengthSquared();
  44644. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  44645. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44646. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44647. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44648. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44649. lowestRoot = getLowestRoot(a, b, c, t);
  44650. if (lowestRoot.found) {
  44651. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44652. if (f >= 0.0 && f <= 1.0) {
  44653. t = lowestRoot.root;
  44654. found = true;
  44655. this._edge.scaleInPlace(f);
  44656. p3.addToRef(this._edge, this._collisionPoint);
  44657. }
  44658. }
  44659. }
  44660. if (found) {
  44661. var distToCollision = t * this._velocity.length();
  44662. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  44663. if (!this.intersectionPoint) {
  44664. this.intersectionPoint = this._collisionPoint.clone();
  44665. }
  44666. else {
  44667. this.intersectionPoint.copyFrom(this._collisionPoint);
  44668. }
  44669. this._nearestDistance = distToCollision;
  44670. this.collisionFound = true;
  44671. }
  44672. }
  44673. };
  44674. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44675. for (var i = indexStart; i < indexEnd; i += 3) {
  44676. var p1 = pts[indices[i] - decal];
  44677. var p2 = pts[indices[i + 1] - decal];
  44678. var p3 = pts[indices[i + 2] - decal];
  44679. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44680. }
  44681. };
  44682. Collider.prototype._getResponse = function (pos, vel) {
  44683. pos.addToRef(vel, this._destinationPoint);
  44684. vel.scaleInPlace((this._nearestDistance / vel.length()));
  44685. this._basePoint.addToRef(vel, pos);
  44686. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44687. this._slidePlaneNormal.normalize();
  44688. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  44689. pos.addInPlace(this._displacementVector);
  44690. this.intersectionPoint.addInPlace(this._displacementVector);
  44691. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44692. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44693. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44694. };
  44695. return Collider;
  44696. }());
  44697. BABYLON.Collider = Collider;
  44698. })(BABYLON || (BABYLON = {}));
  44699. //# sourceMappingURL=babylon.collider.js.map
  44700. var BABYLON;
  44701. (function (BABYLON) {
  44702. //WebWorker code will be inserted to this variable.
  44703. BABYLON.CollisionWorker = "";
  44704. var WorkerTaskType;
  44705. (function (WorkerTaskType) {
  44706. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44707. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44708. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44709. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44710. var WorkerReplyType;
  44711. (function (WorkerReplyType) {
  44712. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44713. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44714. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44715. var CollisionCoordinatorWorker = /** @class */ (function () {
  44716. function CollisionCoordinatorWorker() {
  44717. var _this = this;
  44718. this._scaledPosition = BABYLON.Vector3.Zero();
  44719. this._scaledVelocity = BABYLON.Vector3.Zero();
  44720. this.onMeshUpdated = function (transformNode) {
  44721. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  44722. };
  44723. this.onGeometryUpdated = function (geometry) {
  44724. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44725. };
  44726. this._afterRender = function () {
  44727. if (!_this._init)
  44728. return;
  44729. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44730. return;
  44731. }
  44732. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44733. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44734. if (_this._runningUpdated > 4) {
  44735. return;
  44736. }
  44737. ++_this._runningUpdated;
  44738. var payload = {
  44739. updatedMeshes: _this._addUpdateMeshesList,
  44740. updatedGeometries: _this._addUpdateGeometriesList,
  44741. removedGeometries: _this._toRemoveGeometryArray,
  44742. removedMeshes: _this._toRemoveMeshesArray
  44743. };
  44744. var message = {
  44745. payload: payload,
  44746. taskType: WorkerTaskType.UPDATE
  44747. };
  44748. var serializable = [];
  44749. for (var id in payload.updatedGeometries) {
  44750. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44751. //prepare transferables
  44752. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44753. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44754. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44755. }
  44756. }
  44757. _this._worker.postMessage(message, serializable);
  44758. _this._addUpdateMeshesList = {};
  44759. _this._addUpdateGeometriesList = {};
  44760. _this._toRemoveGeometryArray = [];
  44761. _this._toRemoveMeshesArray = [];
  44762. };
  44763. this._onMessageFromWorker = function (e) {
  44764. var returnData = e.data;
  44765. if (returnData.error != WorkerReplyType.SUCCESS) {
  44766. //TODO what errors can be returned from the worker?
  44767. BABYLON.Tools.Warn("error returned from worker!");
  44768. return;
  44769. }
  44770. switch (returnData.taskType) {
  44771. case WorkerTaskType.INIT:
  44772. _this._init = true;
  44773. //Update the worked with ALL of the scene's current state
  44774. _this._scene.meshes.forEach(function (mesh) {
  44775. _this.onMeshAdded(mesh);
  44776. });
  44777. _this._scene.getGeometries().forEach(function (geometry) {
  44778. _this.onGeometryAdded(geometry);
  44779. });
  44780. break;
  44781. case WorkerTaskType.UPDATE:
  44782. _this._runningUpdated--;
  44783. break;
  44784. case WorkerTaskType.COLLIDE:
  44785. var returnPayload = returnData.payload;
  44786. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44787. return;
  44788. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44789. if (callback) {
  44790. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44791. if (mesh) {
  44792. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44793. }
  44794. }
  44795. //cleanup
  44796. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44797. break;
  44798. }
  44799. };
  44800. this._collisionsCallbackArray = [];
  44801. this._init = false;
  44802. this._runningUpdated = 0;
  44803. this._addUpdateMeshesList = {};
  44804. this._addUpdateGeometriesList = {};
  44805. this._toRemoveGeometryArray = [];
  44806. this._toRemoveMeshesArray = [];
  44807. }
  44808. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44809. if (!this._init)
  44810. return;
  44811. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44812. return;
  44813. position.divideToRef(collider._radius, this._scaledPosition);
  44814. displacement.divideToRef(collider._radius, this._scaledVelocity);
  44815. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44816. var payload = {
  44817. collider: {
  44818. position: this._scaledPosition.asArray(),
  44819. velocity: this._scaledVelocity.asArray(),
  44820. radius: collider._radius.asArray()
  44821. },
  44822. collisionId: collisionIndex,
  44823. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44824. maximumRetry: maximumRetry
  44825. };
  44826. var message = {
  44827. payload: payload,
  44828. taskType: WorkerTaskType.COLLIDE
  44829. };
  44830. this._worker.postMessage(message);
  44831. };
  44832. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44833. this._scene = scene;
  44834. this._scene.registerAfterRender(this._afterRender);
  44835. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44836. this._worker = new Worker(workerUrl);
  44837. this._worker.onmessage = this._onMessageFromWorker;
  44838. var message = {
  44839. payload: {},
  44840. taskType: WorkerTaskType.INIT
  44841. };
  44842. this._worker.postMessage(message);
  44843. };
  44844. CollisionCoordinatorWorker.prototype.destroy = function () {
  44845. this._scene.unregisterAfterRender(this._afterRender);
  44846. this._worker.terminate();
  44847. };
  44848. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44849. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44850. this.onMeshUpdated(mesh);
  44851. };
  44852. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44853. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44854. };
  44855. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44856. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44857. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44858. this.onGeometryUpdated(geometry);
  44859. };
  44860. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44861. this._toRemoveGeometryArray.push(geometry.id);
  44862. };
  44863. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44864. var submeshes = [];
  44865. if (mesh.subMeshes) {
  44866. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44867. var boundingInfo = sm.getBoundingInfo();
  44868. return {
  44869. position: idx,
  44870. verticesStart: sm.verticesStart,
  44871. verticesCount: sm.verticesCount,
  44872. indexStart: sm.indexStart,
  44873. indexCount: sm.indexCount,
  44874. hasMaterial: !!sm.getMaterial(),
  44875. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44876. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44877. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44878. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44879. };
  44880. });
  44881. }
  44882. var geometryId = null;
  44883. if (mesh instanceof BABYLON.Mesh) {
  44884. var geometry = mesh.geometry;
  44885. geometryId = geometry ? geometry.id : null;
  44886. }
  44887. else if (mesh instanceof BABYLON.InstancedMesh) {
  44888. var geometry = mesh.sourceMesh.geometry;
  44889. geometryId = geometry ? geometry.id : null;
  44890. }
  44891. var boundingInfo = mesh.getBoundingInfo();
  44892. return {
  44893. uniqueId: mesh.uniqueId,
  44894. id: mesh.id,
  44895. name: mesh.name,
  44896. geometryId: geometryId,
  44897. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44898. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44899. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44900. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44901. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44902. subMeshes: submeshes,
  44903. checkCollisions: mesh.checkCollisions
  44904. };
  44905. };
  44906. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44907. return {
  44908. id: geometry.id,
  44909. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44910. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44911. indices: new Uint32Array(geometry.getIndices() || []),
  44912. };
  44913. };
  44914. return CollisionCoordinatorWorker;
  44915. }());
  44916. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44917. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44918. function CollisionCoordinatorLegacy() {
  44919. this._scaledPosition = BABYLON.Vector3.Zero();
  44920. this._scaledVelocity = BABYLON.Vector3.Zero();
  44921. this._finalPosition = BABYLON.Vector3.Zero();
  44922. }
  44923. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44924. position.divideToRef(collider._radius, this._scaledPosition);
  44925. displacement.divideToRef(collider._radius, this._scaledVelocity);
  44926. collider.collidedMesh = null;
  44927. collider._retry = 0;
  44928. collider._initialVelocity = this._scaledVelocity;
  44929. collider._initialPosition = this._scaledPosition;
  44930. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44931. this._finalPosition.multiplyInPlace(collider._radius);
  44932. //run the callback
  44933. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44934. };
  44935. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44936. this._scene = scene;
  44937. };
  44938. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44939. //Legacy need no destruction method.
  44940. };
  44941. //No update in legacy mode
  44942. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44943. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44944. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44945. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44946. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44947. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44948. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44949. if (excludedMesh === void 0) { excludedMesh = null; }
  44950. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44951. if (collider._retry >= maximumRetry) {
  44952. finalPosition.copyFrom(position);
  44953. return;
  44954. }
  44955. // Check if this is a mesh else camera or -1
  44956. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44957. collider._initialize(position, velocity, closeDistance);
  44958. // Check all meshes
  44959. for (var index = 0; index < this._scene.meshes.length; index++) {
  44960. var mesh = this._scene.meshes[index];
  44961. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44962. mesh._checkCollision(collider);
  44963. }
  44964. }
  44965. if (!collider.collisionFound) {
  44966. position.addToRef(velocity, finalPosition);
  44967. return;
  44968. }
  44969. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44970. collider._getResponse(position, velocity);
  44971. }
  44972. if (velocity.length() <= closeDistance) {
  44973. finalPosition.copyFrom(position);
  44974. return;
  44975. }
  44976. collider._retry++;
  44977. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44978. };
  44979. return CollisionCoordinatorLegacy;
  44980. }());
  44981. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44982. })(BABYLON || (BABYLON = {}));
  44983. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44984. var BABYLON;
  44985. (function (BABYLON) {
  44986. var Particle = /** @class */ (function () {
  44987. function Particle(particleSystem) {
  44988. this.particleSystem = particleSystem;
  44989. this.position = BABYLON.Vector3.Zero();
  44990. this.direction = BABYLON.Vector3.Zero();
  44991. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44992. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44993. this.lifeTime = 1.0;
  44994. this.age = 0;
  44995. this.size = 0;
  44996. this.angle = 0;
  44997. this.angularSpeed = 0;
  44998. this._currentFrameCounter = 0;
  44999. this.cellIndex = 0;
  45000. if (!this.particleSystem.isAnimationSheetEnabled) {
  45001. return;
  45002. }
  45003. this.cellIndex = this.particleSystem.startSpriteCellID;
  45004. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45005. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45006. }
  45007. else {
  45008. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45009. }
  45010. }
  45011. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45012. // (ageOffset / scaledUpdateSpeed) / available cells
  45013. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45014. this._currentFrameCounter += scaledUpdateSpeed;
  45015. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45016. this._currentFrameCounter = 0;
  45017. this.cellIndex++;
  45018. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45019. this.cellIndex = this.particleSystem.endSpriteCellID;
  45020. }
  45021. }
  45022. };
  45023. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45024. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45025. this.cellIndex++;
  45026. this._currentFrameCounter = 0;
  45027. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45028. if (this.particleSystem.spriteCellLoop) {
  45029. this.cellIndex = this.particleSystem.startSpriteCellID;
  45030. }
  45031. else {
  45032. this.cellIndex = this.particleSystem.endSpriteCellID;
  45033. }
  45034. }
  45035. }
  45036. else {
  45037. this._currentFrameCounter++;
  45038. }
  45039. };
  45040. Particle.prototype.copyTo = function (other) {
  45041. other.position.copyFrom(this.position);
  45042. other.direction.copyFrom(this.direction);
  45043. other.color.copyFrom(this.color);
  45044. other.colorStep.copyFrom(this.colorStep);
  45045. other.lifeTime = this.lifeTime;
  45046. other.age = this.age;
  45047. other.size = this.size;
  45048. other.angle = this.angle;
  45049. other.angularSpeed = this.angularSpeed;
  45050. other.particleSystem = this.particleSystem;
  45051. other.cellIndex = this.cellIndex;
  45052. };
  45053. return Particle;
  45054. }());
  45055. BABYLON.Particle = Particle;
  45056. })(BABYLON || (BABYLON = {}));
  45057. //# sourceMappingURL=babylon.particle.js.map
  45058. var BABYLON;
  45059. (function (BABYLON) {
  45060. var randomNumber = function (min, max) {
  45061. if (min === max) {
  45062. return (min);
  45063. }
  45064. var random = Math.random();
  45065. return ((random * (max - min)) + min);
  45066. };
  45067. var ParticleSystem = /** @class */ (function () {
  45068. // end of sheet animation
  45069. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45070. if (customEffect === void 0) { customEffect = null; }
  45071. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45072. if (epsilon === void 0) { epsilon = 0.01; }
  45073. var _this = this;
  45074. this.name = name;
  45075. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45076. // Members
  45077. this.animations = [];
  45078. this.renderingGroupId = 0;
  45079. this.emitter = null;
  45080. this.emitRate = 10;
  45081. this.manualEmitCount = -1;
  45082. this.updateSpeed = 0.01;
  45083. this.targetStopDuration = 0;
  45084. this.disposeOnStop = false;
  45085. this.minEmitPower = 1;
  45086. this.maxEmitPower = 1;
  45087. this.minLifeTime = 1;
  45088. this.maxLifeTime = 1;
  45089. this.minSize = 1;
  45090. this.maxSize = 1;
  45091. this.minAngularSpeed = 0;
  45092. this.maxAngularSpeed = 0;
  45093. this.layerMask = 0x0FFFFFFF;
  45094. this.customShader = null;
  45095. this.preventAutoStart = false;
  45096. /**
  45097. * An event triggered when the system is disposed.
  45098. * @type {BABYLON.Observable}
  45099. */
  45100. this.onDisposeObservable = new BABYLON.Observable();
  45101. this.onAnimationEnd = null;
  45102. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45103. this.forceDepthWrite = false;
  45104. this.gravity = BABYLON.Vector3.Zero();
  45105. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45106. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45107. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45108. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45109. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45110. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45111. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45112. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45113. this.particles = new Array();
  45114. this._stockParticles = new Array();
  45115. this._newPartsExcess = 0;
  45116. this._vertexBuffers = {};
  45117. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45118. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45119. this._scaledDirection = BABYLON.Vector3.Zero();
  45120. this._scaledGravity = BABYLON.Vector3.Zero();
  45121. this._currentRenderId = -1;
  45122. this._started = false;
  45123. this._stopped = false;
  45124. this._actualFrame = 0;
  45125. // sheet animation
  45126. this.startSpriteCellID = 0;
  45127. this.endSpriteCellID = 0;
  45128. this.spriteCellLoop = true;
  45129. this.spriteCellChangeSpeed = 0;
  45130. this.spriteCellWidth = 0;
  45131. this.spriteCellHeight = 0;
  45132. this._vertexBufferSize = 11;
  45133. this.appendParticleVertexes = null;
  45134. this.id = name;
  45135. this._capacity = capacity;
  45136. this._epsilon = epsilon;
  45137. if (_isAnimationSheetEnabled) {
  45138. this._vertexBufferSize = 12;
  45139. }
  45140. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45141. this._customEffect = customEffect;
  45142. scene.particleSystems.push(this);
  45143. this._createIndexBuffer();
  45144. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45145. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45146. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45147. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45148. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45149. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45150. if (this._isAnimationSheetEnabled) {
  45151. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45152. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45153. }
  45154. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45155. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45156. this._vertexBuffers["options"] = options;
  45157. // Default behaviors
  45158. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  45159. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  45160. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  45161. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  45162. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  45163. };
  45164. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  45165. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  45166. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  45167. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  45168. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  45169. };
  45170. this.updateFunction = function (particles) {
  45171. for (var index = 0; index < particles.length; index++) {
  45172. var particle = particles[index];
  45173. particle.age += _this._scaledUpdateSpeed;
  45174. if (particle.age >= particle.lifeTime) {
  45175. _this.recycleParticle(particle);
  45176. index--;
  45177. continue;
  45178. }
  45179. else {
  45180. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45181. particle.color.addInPlace(_this._scaledColorStep);
  45182. if (particle.color.a < 0)
  45183. particle.color.a = 0;
  45184. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45185. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45186. particle.position.addInPlace(_this._scaledDirection);
  45187. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45188. particle.direction.addInPlace(_this._scaledGravity);
  45189. if (_this._isAnimationSheetEnabled) {
  45190. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45191. }
  45192. }
  45193. }
  45194. };
  45195. }
  45196. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45197. set: function (callback) {
  45198. if (this._onDisposeObserver) {
  45199. this.onDisposeObservable.remove(this._onDisposeObserver);
  45200. }
  45201. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45202. },
  45203. enumerable: true,
  45204. configurable: true
  45205. });
  45206. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45207. get: function () {
  45208. return this._isAnimationSheetEnabled;
  45209. },
  45210. enumerable: true,
  45211. configurable: true
  45212. });
  45213. ParticleSystem.prototype._createIndexBuffer = function () {
  45214. var indices = [];
  45215. var index = 0;
  45216. for (var count = 0; count < this._capacity; count++) {
  45217. indices.push(index);
  45218. indices.push(index + 1);
  45219. indices.push(index + 2);
  45220. indices.push(index);
  45221. indices.push(index + 2);
  45222. indices.push(index + 3);
  45223. index += 4;
  45224. }
  45225. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45226. };
  45227. ParticleSystem.prototype.recycleParticle = function (particle) {
  45228. var lastParticle = this.particles.pop();
  45229. if (lastParticle !== particle) {
  45230. lastParticle.copyTo(particle);
  45231. this._stockParticles.push(lastParticle);
  45232. }
  45233. };
  45234. ParticleSystem.prototype.getCapacity = function () {
  45235. return this._capacity;
  45236. };
  45237. ParticleSystem.prototype.isAlive = function () {
  45238. return this._alive;
  45239. };
  45240. ParticleSystem.prototype.isStarted = function () {
  45241. return this._started;
  45242. };
  45243. ParticleSystem.prototype.start = function () {
  45244. this._started = true;
  45245. this._stopped = false;
  45246. this._actualFrame = 0;
  45247. };
  45248. ParticleSystem.prototype.stop = function () {
  45249. this._stopped = true;
  45250. };
  45251. // animation sheet
  45252. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  45253. var offset = index * this._vertexBufferSize;
  45254. this._vertexData[offset] = particle.position.x;
  45255. this._vertexData[offset + 1] = particle.position.y;
  45256. this._vertexData[offset + 2] = particle.position.z;
  45257. this._vertexData[offset + 3] = particle.color.r;
  45258. this._vertexData[offset + 4] = particle.color.g;
  45259. this._vertexData[offset + 5] = particle.color.b;
  45260. this._vertexData[offset + 6] = particle.color.a;
  45261. this._vertexData[offset + 7] = particle.angle;
  45262. this._vertexData[offset + 8] = particle.size;
  45263. this._vertexData[offset + 9] = offsetX;
  45264. this._vertexData[offset + 10] = offsetY;
  45265. };
  45266. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45267. if (offsetX === 0)
  45268. offsetX = this._epsilon;
  45269. else if (offsetX === 1)
  45270. offsetX = 1 - this._epsilon;
  45271. if (offsetY === 0)
  45272. offsetY = this._epsilon;
  45273. else if (offsetY === 1)
  45274. offsetY = 1 - this._epsilon;
  45275. var offset = index * this._vertexBufferSize;
  45276. this._vertexData[offset] = particle.position.x;
  45277. this._vertexData[offset + 1] = particle.position.y;
  45278. this._vertexData[offset + 2] = particle.position.z;
  45279. this._vertexData[offset + 3] = particle.color.r;
  45280. this._vertexData[offset + 4] = particle.color.g;
  45281. this._vertexData[offset + 5] = particle.color.b;
  45282. this._vertexData[offset + 6] = particle.color.a;
  45283. this._vertexData[offset + 7] = particle.angle;
  45284. this._vertexData[offset + 8] = particle.size;
  45285. this._vertexData[offset + 9] = offsetX;
  45286. this._vertexData[offset + 10] = offsetY;
  45287. this._vertexData[offset + 11] = particle.cellIndex;
  45288. };
  45289. ParticleSystem.prototype._update = function (newParticles) {
  45290. // Update current
  45291. this._alive = this.particles.length > 0;
  45292. this.updateFunction(this.particles);
  45293. // Add new ones
  45294. var worldMatrix;
  45295. if (this.emitter.position) {
  45296. var emitterMesh = this.emitter;
  45297. worldMatrix = emitterMesh.getWorldMatrix();
  45298. }
  45299. else {
  45300. var emitterPosition = this.emitter;
  45301. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45302. }
  45303. var particle;
  45304. for (var index = 0; index < newParticles; index++) {
  45305. if (this.particles.length === this._capacity) {
  45306. break;
  45307. }
  45308. if (this._stockParticles.length !== 0) {
  45309. particle = this._stockParticles.pop();
  45310. particle.age = 0;
  45311. particle.cellIndex = this.startSpriteCellID;
  45312. }
  45313. else {
  45314. particle = new BABYLON.Particle(this);
  45315. }
  45316. this.particles.push(particle);
  45317. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45318. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45319. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45320. particle.size = randomNumber(this.minSize, this.maxSize);
  45321. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45322. this.startPositionFunction(worldMatrix, particle.position, particle);
  45323. var step = randomNumber(0, 1.0);
  45324. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45325. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45326. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45327. }
  45328. };
  45329. ParticleSystem.prototype._getEffect = function () {
  45330. if (this._customEffect) {
  45331. return this._customEffect;
  45332. }
  45333. ;
  45334. var defines = [];
  45335. if (this._scene.clipPlane) {
  45336. defines.push("#define CLIPPLANE");
  45337. }
  45338. if (this._isAnimationSheetEnabled) {
  45339. defines.push("#define ANIMATESHEET");
  45340. }
  45341. // Effect
  45342. var join = defines.join("\n");
  45343. if (this._cachedDefines !== join) {
  45344. this._cachedDefines = join;
  45345. var attributesNamesOrOptions;
  45346. var effectCreationOption;
  45347. if (this._isAnimationSheetEnabled) {
  45348. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45349. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45350. }
  45351. else {
  45352. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45353. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45354. }
  45355. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45356. }
  45357. return this._effect;
  45358. };
  45359. ParticleSystem.prototype.animate = function () {
  45360. if (!this._started)
  45361. return;
  45362. var effect = this._getEffect();
  45363. // Check
  45364. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45365. return;
  45366. if (this._currentRenderId === this._scene.getRenderId()) {
  45367. return;
  45368. }
  45369. this._currentRenderId = this._scene.getRenderId();
  45370. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45371. // determine the number of particles we need to create
  45372. var newParticles;
  45373. if (this.manualEmitCount > -1) {
  45374. newParticles = this.manualEmitCount;
  45375. this._newPartsExcess = 0;
  45376. this.manualEmitCount = 0;
  45377. }
  45378. else {
  45379. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45380. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45381. }
  45382. if (this._newPartsExcess > 1.0) {
  45383. newParticles += this._newPartsExcess >> 0;
  45384. this._newPartsExcess -= this._newPartsExcess >> 0;
  45385. }
  45386. this._alive = false;
  45387. if (!this._stopped) {
  45388. this._actualFrame += this._scaledUpdateSpeed;
  45389. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45390. this.stop();
  45391. }
  45392. else {
  45393. newParticles = 0;
  45394. }
  45395. this._update(newParticles);
  45396. // Stopped?
  45397. if (this._stopped) {
  45398. if (!this._alive) {
  45399. this._started = false;
  45400. if (this.onAnimationEnd) {
  45401. this.onAnimationEnd();
  45402. }
  45403. if (this.disposeOnStop) {
  45404. this._scene._toBeDisposed.push(this);
  45405. }
  45406. }
  45407. }
  45408. // Animation sheet
  45409. if (this._isAnimationSheetEnabled) {
  45410. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45411. }
  45412. else {
  45413. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45414. }
  45415. // Update VBO
  45416. var offset = 0;
  45417. for (var index = 0; index < this.particles.length; index++) {
  45418. var particle = this.particles[index];
  45419. this.appendParticleVertexes(offset, particle);
  45420. offset += 4;
  45421. }
  45422. if (this._vertexBuffer) {
  45423. this._vertexBuffer.update(this._vertexData);
  45424. }
  45425. };
  45426. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  45427. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  45428. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  45429. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  45430. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  45431. };
  45432. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  45433. this._appendParticleVertex(offset++, particle, 0, 0);
  45434. this._appendParticleVertex(offset++, particle, 1, 0);
  45435. this._appendParticleVertex(offset++, particle, 1, 1);
  45436. this._appendParticleVertex(offset++, particle, 0, 1);
  45437. };
  45438. ParticleSystem.prototype.rebuild = function () {
  45439. this._createIndexBuffer();
  45440. if (this._vertexBuffer) {
  45441. this._vertexBuffer._rebuild();
  45442. }
  45443. };
  45444. ParticleSystem.prototype.render = function () {
  45445. var effect = this._getEffect();
  45446. // Check
  45447. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  45448. return 0;
  45449. var engine = this._scene.getEngine();
  45450. // Render
  45451. engine.enableEffect(effect);
  45452. engine.setState(false);
  45453. var viewMatrix = this._scene.getViewMatrix();
  45454. effect.setTexture("diffuseSampler", this.particleTexture);
  45455. effect.setMatrix("view", viewMatrix);
  45456. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45457. if (this._isAnimationSheetEnabled) {
  45458. var baseSize = this.particleTexture.getBaseSize();
  45459. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  45460. }
  45461. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  45462. if (this._scene.clipPlane) {
  45463. var clipPlane = this._scene.clipPlane;
  45464. var invView = viewMatrix.clone();
  45465. invView.invert();
  45466. effect.setMatrix("invView", invView);
  45467. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  45468. }
  45469. // VBOs
  45470. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45471. // Draw order
  45472. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  45473. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  45474. }
  45475. else {
  45476. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45477. }
  45478. if (this.forceDepthWrite) {
  45479. engine.setDepthWrite(true);
  45480. }
  45481. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  45482. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45483. return this.particles.length;
  45484. };
  45485. ParticleSystem.prototype.dispose = function () {
  45486. if (this._vertexBuffer) {
  45487. this._vertexBuffer.dispose();
  45488. this._vertexBuffer = null;
  45489. }
  45490. if (this._indexBuffer) {
  45491. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45492. this._indexBuffer = null;
  45493. }
  45494. if (this.particleTexture) {
  45495. this.particleTexture.dispose();
  45496. this.particleTexture = null;
  45497. }
  45498. // Remove from scene
  45499. var index = this._scene.particleSystems.indexOf(this);
  45500. if (index > -1) {
  45501. this._scene.particleSystems.splice(index, 1);
  45502. }
  45503. // Callback
  45504. this.onDisposeObservable.notifyObservers(this);
  45505. this.onDisposeObservable.clear();
  45506. };
  45507. // Clone
  45508. ParticleSystem.prototype.clone = function (name, newEmitter) {
  45509. var custom = null;
  45510. var program = null;
  45511. if (this.customShader != null) {
  45512. program = this.customShader;
  45513. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45514. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45515. }
  45516. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  45517. result.customShader = program;
  45518. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  45519. if (newEmitter === undefined) {
  45520. newEmitter = this.emitter;
  45521. }
  45522. result.emitter = newEmitter;
  45523. if (this.particleTexture) {
  45524. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  45525. }
  45526. if (!this.preventAutoStart) {
  45527. result.start();
  45528. }
  45529. return result;
  45530. };
  45531. ParticleSystem.prototype.serialize = function () {
  45532. var serializationObject = {};
  45533. serializationObject.name = this.name;
  45534. serializationObject.id = this.id;
  45535. // Emitter
  45536. if (this.emitter.position) {
  45537. var emitterMesh = this.emitter;
  45538. serializationObject.emitterId = emitterMesh.id;
  45539. }
  45540. else {
  45541. var emitterPosition = this.emitter;
  45542. serializationObject.emitter = emitterPosition.asArray();
  45543. }
  45544. serializationObject.capacity = this.getCapacity();
  45545. if (this.particleTexture) {
  45546. serializationObject.textureName = this.particleTexture.name;
  45547. }
  45548. // Animations
  45549. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  45550. // Particle system
  45551. serializationObject.minAngularSpeed = this.minAngularSpeed;
  45552. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  45553. serializationObject.minSize = this.minSize;
  45554. serializationObject.maxSize = this.maxSize;
  45555. serializationObject.minEmitPower = this.minEmitPower;
  45556. serializationObject.maxEmitPower = this.maxEmitPower;
  45557. serializationObject.minLifeTime = this.minLifeTime;
  45558. serializationObject.maxLifeTime = this.maxLifeTime;
  45559. serializationObject.emitRate = this.emitRate;
  45560. serializationObject.minEmitBox = this.minEmitBox.asArray();
  45561. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  45562. serializationObject.gravity = this.gravity.asArray();
  45563. serializationObject.direction1 = this.direction1.asArray();
  45564. serializationObject.direction2 = this.direction2.asArray();
  45565. serializationObject.color1 = this.color1.asArray();
  45566. serializationObject.color2 = this.color2.asArray();
  45567. serializationObject.colorDead = this.colorDead.asArray();
  45568. serializationObject.updateSpeed = this.updateSpeed;
  45569. serializationObject.targetStopDuration = this.targetStopDuration;
  45570. serializationObject.textureMask = this.textureMask.asArray();
  45571. serializationObject.blendMode = this.blendMode;
  45572. serializationObject.customShader = this.customShader;
  45573. serializationObject.preventAutoStart = this.preventAutoStart;
  45574. serializationObject.startSpriteCellID = this.startSpriteCellID;
  45575. serializationObject.endSpriteCellID = this.endSpriteCellID;
  45576. serializationObject.spriteCellLoop = this.spriteCellLoop;
  45577. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  45578. serializationObject.spriteCellWidth = this.spriteCellWidth;
  45579. serializationObject.spriteCellHeight = this.spriteCellHeight;
  45580. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  45581. return serializationObject;
  45582. };
  45583. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  45584. var name = parsedParticleSystem.name;
  45585. var custom = null;
  45586. var program = null;
  45587. if (parsedParticleSystem.customShader) {
  45588. program = parsedParticleSystem.customShader;
  45589. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  45590. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  45591. }
  45592. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  45593. particleSystem.customShader = program;
  45594. if (parsedParticleSystem.id) {
  45595. particleSystem.id = parsedParticleSystem.id;
  45596. }
  45597. // Auto start
  45598. if (parsedParticleSystem.preventAutoStart) {
  45599. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  45600. }
  45601. // Texture
  45602. if (parsedParticleSystem.textureName) {
  45603. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45604. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45605. }
  45606. // Emitter
  45607. if (parsedParticleSystem.emitterId) {
  45608. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45609. }
  45610. else {
  45611. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45612. }
  45613. // Animations
  45614. if (parsedParticleSystem.animations) {
  45615. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45616. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45617. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45618. }
  45619. }
  45620. if (parsedParticleSystem.autoAnimate) {
  45621. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45622. }
  45623. // Particle system
  45624. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45625. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45626. particleSystem.minSize = parsedParticleSystem.minSize;
  45627. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45628. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45629. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45630. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45631. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45632. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45633. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45634. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45635. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45636. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45637. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45638. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45639. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45640. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45641. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45642. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45643. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45644. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45645. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  45646. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  45647. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  45648. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  45649. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  45650. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  45651. if (!particleSystem.preventAutoStart) {
  45652. particleSystem.start();
  45653. }
  45654. return particleSystem;
  45655. };
  45656. // Statics
  45657. ParticleSystem.BLENDMODE_ONEONE = 0;
  45658. ParticleSystem.BLENDMODE_STANDARD = 1;
  45659. return ParticleSystem;
  45660. }());
  45661. BABYLON.ParticleSystem = ParticleSystem;
  45662. })(BABYLON || (BABYLON = {}));
  45663. //# sourceMappingURL=babylon.particleSystem.js.map
  45664. var BABYLON;
  45665. (function (BABYLON) {
  45666. var SolidParticle = /** @class */ (function () {
  45667. /**
  45668. * Creates a Solid Particle object.
  45669. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45670. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45671. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45672. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45673. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45674. * `shapeId` (integer) is the model shape identifier in the SPS.
  45675. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45676. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45677. */
  45678. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45679. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45680. this.idx = 0; // particle global index
  45681. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45682. this.position = BABYLON.Vector3.Zero(); // position
  45683. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45684. this.scaling = BABYLON.Vector3.One(); // scaling
  45685. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45686. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45687. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45688. this.alive = true; // alive
  45689. this.isVisible = true; // visibility
  45690. this._pos = 0; // index of this particle in the global "positions" array
  45691. this._ind = 0; // index of this particle in the global "indices" array
  45692. this.shapeId = 0; // model shape id
  45693. this.idxInShape = 0; // index of the particle in its shape id
  45694. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45695. this.idx = particleIndex;
  45696. this._pos = positionIndex;
  45697. this._ind = indiceIndex;
  45698. this._model = model;
  45699. this.shapeId = shapeId;
  45700. this.idxInShape = idxInShape;
  45701. this._sps = sps;
  45702. if (modelBoundingInfo) {
  45703. this._modelBoundingInfo = modelBoundingInfo;
  45704. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45705. }
  45706. }
  45707. Object.defineProperty(SolidParticle.prototype, "scale", {
  45708. /**
  45709. * legacy support, changed scale to scaling
  45710. */
  45711. get: function () {
  45712. return this.scaling;
  45713. },
  45714. set: function (scale) {
  45715. this.scaling = scale;
  45716. },
  45717. enumerable: true,
  45718. configurable: true
  45719. });
  45720. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45721. /**
  45722. * legacy support, changed quaternion to rotationQuaternion
  45723. */
  45724. get: function () {
  45725. return this.rotationQuaternion;
  45726. },
  45727. set: function (q) {
  45728. this.rotationQuaternion = q;
  45729. },
  45730. enumerable: true,
  45731. configurable: true
  45732. });
  45733. /**
  45734. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45735. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45736. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45737. */
  45738. SolidParticle.prototype.intersectsMesh = function (target) {
  45739. if (!this._boundingInfo || !target._boundingInfo) {
  45740. return false;
  45741. }
  45742. if (this._sps._bSphereOnly) {
  45743. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45744. }
  45745. return this._boundingInfo.intersects(target._boundingInfo, false);
  45746. };
  45747. return SolidParticle;
  45748. }());
  45749. BABYLON.SolidParticle = SolidParticle;
  45750. var ModelShape = /** @class */ (function () {
  45751. /**
  45752. * 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.
  45753. * SPS internal tool, don't use it manually.
  45754. */
  45755. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45756. this._indicesLength = 0; // length of the shape in the model indices array
  45757. this.shapeID = id;
  45758. this._shape = shape;
  45759. this._indicesLength = indicesLength;
  45760. this._shapeUV = shapeUV;
  45761. this._positionFunction = posFunction;
  45762. this._vertexFunction = vtxFunction;
  45763. }
  45764. return ModelShape;
  45765. }());
  45766. BABYLON.ModelShape = ModelShape;
  45767. var DepthSortedParticle = /** @class */ (function () {
  45768. function DepthSortedParticle() {
  45769. this.ind = 0; // index of the particle in the "indices" array
  45770. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45771. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45772. }
  45773. return DepthSortedParticle;
  45774. }());
  45775. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45776. })(BABYLON || (BABYLON = {}));
  45777. //# sourceMappingURL=babylon.solidParticle.js.map
  45778. var BABYLON;
  45779. (function (BABYLON) {
  45780. /**
  45781. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45782. */
  45783. var SolidParticleSystem = /** @class */ (function () {
  45784. /**
  45785. * Creates a SPS (Solid Particle System) object.
  45786. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45787. * `scene` (Scene) is the scene in which the SPS is added.
  45788. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45789. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45790. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45791. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45792. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45793. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45794. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45795. */
  45796. function SolidParticleSystem(name, scene, options) {
  45797. // public members
  45798. /**
  45799. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45800. * Example : var p = SPS.particles[i];
  45801. */
  45802. this.particles = new Array();
  45803. /**
  45804. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45805. */
  45806. this.nbParticles = 0;
  45807. /**
  45808. * If the particles must ever face the camera (default false). Useful for planar particles.
  45809. */
  45810. this.billboard = false;
  45811. /**
  45812. * Recompute normals when adding a shape
  45813. */
  45814. this.recomputeNormals = true;
  45815. /**
  45816. * This a counter ofr your own usage. It's not set by any SPS functions.
  45817. */
  45818. this.counter = 0;
  45819. /**
  45820. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45821. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45822. */
  45823. this.vars = {};
  45824. this._positions = new Array();
  45825. this._indices = new Array();
  45826. this._normals = new Array();
  45827. this._colors = new Array();
  45828. this._uvs = new Array();
  45829. this._index = 0; // indices index
  45830. this._updatable = true;
  45831. this._pickable = false;
  45832. this._isVisibilityBoxLocked = false;
  45833. this._alwaysVisible = false;
  45834. this._depthSort = false;
  45835. this._shapeCounter = 0;
  45836. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45837. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45838. this._computeParticleColor = true;
  45839. this._computeParticleTexture = true;
  45840. this._computeParticleRotation = true;
  45841. this._computeParticleVertex = false;
  45842. this._computeBoundingBox = false;
  45843. this._depthSortParticles = true;
  45844. this._cam_axisZ = BABYLON.Vector3.Zero();
  45845. this._cam_axisY = BABYLON.Vector3.Zero();
  45846. this._cam_axisX = BABYLON.Vector3.Zero();
  45847. this._axisZ = BABYLON.Axis.Z;
  45848. this._camDir = BABYLON.Vector3.Zero();
  45849. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45850. this._rotMatrix = new BABYLON.Matrix();
  45851. this._invertMatrix = new BABYLON.Matrix();
  45852. this._rotated = BABYLON.Vector3.Zero();
  45853. this._quaternion = new BABYLON.Quaternion();
  45854. this._vertex = BABYLON.Vector3.Zero();
  45855. this._normal = BABYLON.Vector3.Zero();
  45856. this._yaw = 0.0;
  45857. this._pitch = 0.0;
  45858. this._roll = 0.0;
  45859. this._halfroll = 0.0;
  45860. this._halfpitch = 0.0;
  45861. this._halfyaw = 0.0;
  45862. this._sinRoll = 0.0;
  45863. this._cosRoll = 0.0;
  45864. this._sinPitch = 0.0;
  45865. this._cosPitch = 0.0;
  45866. this._sinYaw = 0.0;
  45867. this._cosYaw = 0.0;
  45868. this._mustUnrotateFixedNormals = false;
  45869. this._minimum = BABYLON.Tmp.Vector3[0];
  45870. this._maximum = BABYLON.Tmp.Vector3[1];
  45871. this._minBbox = BABYLON.Tmp.Vector3[4];
  45872. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45873. this._particlesIntersect = false;
  45874. this._depthSortFunction = function (p1, p2) {
  45875. return (p2.sqDistance - p1.sqDistance);
  45876. };
  45877. this._needs32Bits = false;
  45878. this._bSphereOnly = false;
  45879. this._bSphereRadiusFactor = 1.0;
  45880. this.name = name;
  45881. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45882. this._camera = scene.activeCamera;
  45883. this._pickable = options ? options.isPickable : false;
  45884. this._depthSort = options ? options.enableDepthSort : false;
  45885. this._particlesIntersect = options ? options.particleIntersection : false;
  45886. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45887. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45888. if (options && options.updatable) {
  45889. this._updatable = options.updatable;
  45890. }
  45891. else {
  45892. this._updatable = true;
  45893. }
  45894. if (this._pickable) {
  45895. this.pickedParticles = [];
  45896. }
  45897. if (this._depthSort) {
  45898. this.depthSortedParticles = [];
  45899. }
  45900. }
  45901. /**
  45902. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45903. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45904. */
  45905. SolidParticleSystem.prototype.buildMesh = function () {
  45906. if (this.nbParticles === 0) {
  45907. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45908. this.addShape(triangle, 1);
  45909. triangle.dispose();
  45910. }
  45911. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45912. this._positions32 = new Float32Array(this._positions);
  45913. this._uvs32 = new Float32Array(this._uvs);
  45914. this._colors32 = new Float32Array(this._colors);
  45915. if (this.recomputeNormals) {
  45916. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45917. }
  45918. this._normals32 = new Float32Array(this._normals);
  45919. this._fixedNormal32 = new Float32Array(this._normals);
  45920. if (this._mustUnrotateFixedNormals) {
  45921. this._unrotateFixedNormals();
  45922. }
  45923. var vertexData = new BABYLON.VertexData();
  45924. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  45925. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45926. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45927. if (this._uvs32) {
  45928. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45929. ;
  45930. }
  45931. if (this._colors32) {
  45932. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45933. }
  45934. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45935. vertexData.applyToMesh(mesh, this._updatable);
  45936. this.mesh = mesh;
  45937. this.mesh.isPickable = this._pickable;
  45938. // free memory
  45939. if (!this._depthSort) {
  45940. this._indices = null;
  45941. }
  45942. this._positions = null;
  45943. this._normals = null;
  45944. this._uvs = null;
  45945. this._colors = null;
  45946. if (!this._updatable) {
  45947. this.particles.length = 0;
  45948. }
  45949. return mesh;
  45950. };
  45951. /**
  45952. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45953. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45954. * Thus the particles generated from `digest()` have their property `position` set yet.
  45955. * `mesh` ( Mesh ) is the mesh to be digested
  45956. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45957. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45958. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45959. */
  45960. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45961. var size = (options && options.facetNb) || 1;
  45962. var number = (options && options.number) || 0;
  45963. var delta = (options && options.delta) || 0;
  45964. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45965. var meshInd = mesh.getIndices();
  45966. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45967. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45968. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45969. var f = 0; // facet counter
  45970. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45971. // compute size from number
  45972. if (number) {
  45973. number = (number > totalFacets) ? totalFacets : number;
  45974. size = Math.round(totalFacets / number);
  45975. delta = 0;
  45976. }
  45977. else {
  45978. size = (size > totalFacets) ? totalFacets : size;
  45979. }
  45980. var facetPos = []; // submesh positions
  45981. var facetInd = []; // submesh indices
  45982. var facetUV = []; // submesh UV
  45983. var facetCol = []; // submesh colors
  45984. var barycenter = BABYLON.Tmp.Vector3[0];
  45985. var sizeO = size;
  45986. while (f < totalFacets) {
  45987. size = sizeO + Math.floor((1 + delta) * Math.random());
  45988. if (f > totalFacets - size) {
  45989. size = totalFacets - f;
  45990. }
  45991. // reset temp arrays
  45992. facetPos.length = 0;
  45993. facetInd.length = 0;
  45994. facetUV.length = 0;
  45995. facetCol.length = 0;
  45996. // iterate over "size" facets
  45997. var fi = 0;
  45998. for (var j = f * 3; j < (f + size) * 3; j++) {
  45999. facetInd.push(fi);
  46000. var i = meshInd[j];
  46001. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  46002. if (meshUV) {
  46003. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  46004. }
  46005. if (meshCol) {
  46006. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  46007. }
  46008. fi++;
  46009. }
  46010. // create a model shape for each single particle
  46011. var idx = this.nbParticles;
  46012. var shape = this._posToShape(facetPos);
  46013. var shapeUV = this._uvsToShapeUV(facetUV);
  46014. // compute the barycenter of the shape
  46015. var v;
  46016. for (v = 0; v < shape.length; v++) {
  46017. barycenter.addInPlace(shape[v]);
  46018. }
  46019. barycenter.scaleInPlace(1 / shape.length);
  46020. // shift the shape from its barycenter to the origin
  46021. for (v = 0; v < shape.length; v++) {
  46022. shape[v].subtractInPlace(barycenter);
  46023. }
  46024. var bInfo;
  46025. if (this._particlesIntersect) {
  46026. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  46027. }
  46028. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  46029. // add the particle in the SPS
  46030. var currentPos = this._positions.length;
  46031. var currentInd = this._indices.length;
  46032. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  46033. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  46034. // initialize the particle position
  46035. this.particles[this.nbParticles].position.addInPlace(barycenter);
  46036. this._index += shape.length;
  46037. idx++;
  46038. this.nbParticles++;
  46039. this._shapeCounter++;
  46040. f += size;
  46041. }
  46042. return this;
  46043. };
  46044. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  46045. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  46046. var index = 0;
  46047. var idx = 0;
  46048. for (var p = 0; p < this.particles.length; p++) {
  46049. this._particle = this.particles[p];
  46050. this._shape = this._particle._model._shape;
  46051. if (this._particle.rotationQuaternion) {
  46052. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46053. }
  46054. else {
  46055. this._yaw = this._particle.rotation.y;
  46056. this._pitch = this._particle.rotation.x;
  46057. this._roll = this._particle.rotation.z;
  46058. this._quaternionRotationYPR();
  46059. }
  46060. this._quaternionToRotationMatrix();
  46061. this._rotMatrix.invertToRef(this._invertMatrix);
  46062. for (var pt = 0; pt < this._shape.length; pt++) {
  46063. idx = index + pt * 3;
  46064. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  46065. this._fixedNormal32[idx] = this._normal.x;
  46066. this._fixedNormal32[idx + 1] = this._normal.y;
  46067. this._fixedNormal32[idx + 2] = this._normal.z;
  46068. }
  46069. index = idx + 3;
  46070. }
  46071. };
  46072. //reset copy
  46073. SolidParticleSystem.prototype._resetCopy = function () {
  46074. this._copy.position.x = 0;
  46075. this._copy.position.y = 0;
  46076. this._copy.position.z = 0;
  46077. this._copy.rotation.x = 0;
  46078. this._copy.rotation.y = 0;
  46079. this._copy.rotation.z = 0;
  46080. this._copy.rotationQuaternion = null;
  46081. this._copy.scaling.x = 1.0;
  46082. this._copy.scaling.y = 1.0;
  46083. this._copy.scaling.z = 1.0;
  46084. this._copy.uvs.x = 0;
  46085. this._copy.uvs.y = 0;
  46086. this._copy.uvs.z = 1.0;
  46087. this._copy.uvs.w = 1.0;
  46088. this._copy.color = null;
  46089. };
  46090. // _meshBuilder : inserts the shape model in the global SPS mesh
  46091. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  46092. var i;
  46093. var u = 0;
  46094. var c = 0;
  46095. var n = 0;
  46096. this._resetCopy();
  46097. if (options && options.positionFunction) {
  46098. options.positionFunction(this._copy, idx, idxInShape);
  46099. this._mustUnrotateFixedNormals = true;
  46100. }
  46101. if (this._copy.rotationQuaternion) {
  46102. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46103. }
  46104. else {
  46105. this._yaw = this._copy.rotation.y;
  46106. this._pitch = this._copy.rotation.x;
  46107. this._roll = this._copy.rotation.z;
  46108. this._quaternionRotationYPR();
  46109. }
  46110. this._quaternionToRotationMatrix();
  46111. for (i = 0; i < shape.length; i++) {
  46112. this._vertex.x = shape[i].x;
  46113. this._vertex.y = shape[i].y;
  46114. this._vertex.z = shape[i].z;
  46115. if (options && options.vertexFunction) {
  46116. options.vertexFunction(this._copy, this._vertex, i);
  46117. }
  46118. this._vertex.x *= this._copy.scaling.x;
  46119. this._vertex.y *= this._copy.scaling.y;
  46120. this._vertex.z *= this._copy.scaling.z;
  46121. this._vertex.x += this._copy.pivot.x;
  46122. this._vertex.y += this._copy.pivot.y;
  46123. this._vertex.z += this._copy.pivot.z;
  46124. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46125. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  46126. if (meshUV) {
  46127. 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);
  46128. u += 2;
  46129. }
  46130. if (this._copy.color) {
  46131. this._color = this._copy.color;
  46132. }
  46133. else if (meshCol && meshCol[c] !== undefined) {
  46134. this._color.r = meshCol[c];
  46135. this._color.g = meshCol[c + 1];
  46136. this._color.b = meshCol[c + 2];
  46137. this._color.a = meshCol[c + 3];
  46138. }
  46139. else {
  46140. this._color.r = 1.0;
  46141. this._color.g = 1.0;
  46142. this._color.b = 1.0;
  46143. this._color.a = 1.0;
  46144. }
  46145. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  46146. c += 4;
  46147. if (!this.recomputeNormals && meshNor) {
  46148. this._normal.x = meshNor[n];
  46149. this._normal.y = meshNor[n + 1];
  46150. this._normal.z = meshNor[n + 2];
  46151. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  46152. normals.push(this._normal.x, this._normal.y, this._normal.z);
  46153. n += 3;
  46154. }
  46155. }
  46156. for (i = 0; i < meshInd.length; i++) {
  46157. var current_ind = p + meshInd[i];
  46158. indices.push(current_ind);
  46159. if (current_ind > 65535) {
  46160. this._needs32Bits = true;
  46161. }
  46162. }
  46163. if (this._pickable) {
  46164. var nbfaces = meshInd.length / 3;
  46165. for (i = 0; i < nbfaces; i++) {
  46166. this.pickedParticles.push({ idx: idx, faceId: i });
  46167. }
  46168. }
  46169. if (this._depthSort) {
  46170. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  46171. }
  46172. return this._copy;
  46173. };
  46174. // returns a shape array from positions array
  46175. SolidParticleSystem.prototype._posToShape = function (positions) {
  46176. var shape = [];
  46177. for (var i = 0; i < positions.length; i += 3) {
  46178. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  46179. }
  46180. return shape;
  46181. };
  46182. // returns a shapeUV array from a Vector4 uvs
  46183. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  46184. var shapeUV = [];
  46185. if (uvs) {
  46186. for (var i = 0; i < uvs.length; i++)
  46187. shapeUV.push(uvs[i]);
  46188. }
  46189. return shapeUV;
  46190. };
  46191. // adds a new particle object in the particles array
  46192. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  46193. if (bInfo === void 0) { bInfo = null; }
  46194. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  46195. this.particles.push(sp);
  46196. return sp;
  46197. };
  46198. /**
  46199. * Adds some particles to the SPS from the model shape. Returns the shape id.
  46200. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  46201. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  46202. * `nb` (positive integer) the number of particles to be created from this model
  46203. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  46204. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  46205. */
  46206. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  46207. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46208. var meshInd = mesh.getIndices();
  46209. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46210. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46211. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46212. var bbInfo;
  46213. if (this._particlesIntersect) {
  46214. bbInfo = mesh.getBoundingInfo();
  46215. }
  46216. var shape = this._posToShape(meshPos);
  46217. var shapeUV = this._uvsToShapeUV(meshUV);
  46218. var posfunc = options ? options.positionFunction : null;
  46219. var vtxfunc = options ? options.vertexFunction : null;
  46220. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  46221. // particles
  46222. var sp;
  46223. var currentCopy;
  46224. var idx = this.nbParticles;
  46225. for (var i = 0; i < nb; i++) {
  46226. var currentPos = this._positions.length;
  46227. var currentInd = this._indices.length;
  46228. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  46229. if (this._updatable) {
  46230. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  46231. sp.position.copyFrom(currentCopy.position);
  46232. sp.rotation.copyFrom(currentCopy.rotation);
  46233. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  46234. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  46235. }
  46236. if (currentCopy.color && sp.color) {
  46237. sp.color.copyFrom(currentCopy.color);
  46238. }
  46239. sp.scaling.copyFrom(currentCopy.scaling);
  46240. sp.uvs.copyFrom(currentCopy.uvs);
  46241. }
  46242. this._index += shape.length;
  46243. idx++;
  46244. }
  46245. this.nbParticles += nb;
  46246. this._shapeCounter++;
  46247. return this._shapeCounter - 1;
  46248. };
  46249. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  46250. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  46251. this._resetCopy();
  46252. if (particle._model._positionFunction) {
  46253. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  46254. }
  46255. if (this._copy.rotationQuaternion) {
  46256. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46257. }
  46258. else {
  46259. this._yaw = this._copy.rotation.y;
  46260. this._pitch = this._copy.rotation.x;
  46261. this._roll = this._copy.rotation.z;
  46262. this._quaternionRotationYPR();
  46263. }
  46264. this._quaternionToRotationMatrix();
  46265. this._shape = particle._model._shape;
  46266. for (var pt = 0; pt < this._shape.length; pt++) {
  46267. this._vertex.x = this._shape[pt].x;
  46268. this._vertex.y = this._shape[pt].y;
  46269. this._vertex.z = this._shape[pt].z;
  46270. if (particle._model._vertexFunction) {
  46271. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  46272. }
  46273. this._vertex.x *= this._copy.scaling.x;
  46274. this._vertex.y *= this._copy.scaling.y;
  46275. this._vertex.z *= this._copy.scaling.z;
  46276. this._vertex.x += this._copy.pivot.x;
  46277. this._vertex.y += this._copy.pivot.y;
  46278. this._vertex.z += this._copy.pivot.z;
  46279. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46280. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  46281. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  46282. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  46283. }
  46284. particle.position.x = 0.0;
  46285. particle.position.y = 0.0;
  46286. particle.position.z = 0.0;
  46287. particle.rotation.x = 0.0;
  46288. particle.rotation.y = 0.0;
  46289. particle.rotation.z = 0.0;
  46290. particle.rotationQuaternion = null;
  46291. particle.scaling.x = 1.0;
  46292. particle.scaling.y = 1.0;
  46293. particle.scaling.z = 1.0;
  46294. };
  46295. /**
  46296. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  46297. * Returns the SPS.
  46298. */
  46299. SolidParticleSystem.prototype.rebuildMesh = function () {
  46300. for (var p = 0; p < this.particles.length; p++) {
  46301. this._rebuildParticle(this.particles[p]);
  46302. }
  46303. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46304. return this;
  46305. };
  46306. /**
  46307. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  46308. * This method calls `updateParticle()` for each particle of the SPS.
  46309. * For an animated SPS, it is usually called within the render loop.
  46310. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  46311. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  46312. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  46313. * Returns the SPS.
  46314. */
  46315. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  46316. if (start === void 0) { start = 0; }
  46317. if (end === void 0) { end = this.nbParticles - 1; }
  46318. if (update === void 0) { update = true; }
  46319. if (!this._updatable) {
  46320. return this;
  46321. }
  46322. // custom beforeUpdate
  46323. this.beforeUpdateParticles(start, end, update);
  46324. this._cam_axisX.x = 1.0;
  46325. this._cam_axisX.y = 0.0;
  46326. this._cam_axisX.z = 0.0;
  46327. this._cam_axisY.x = 0.0;
  46328. this._cam_axisY.y = 1.0;
  46329. this._cam_axisY.z = 0.0;
  46330. this._cam_axisZ.x = 0.0;
  46331. this._cam_axisZ.y = 0.0;
  46332. this._cam_axisZ.z = 1.0;
  46333. // cases when the World Matrix is to be computed first
  46334. if (this.billboard || this._depthSort) {
  46335. this.mesh.computeWorldMatrix(true);
  46336. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  46337. }
  46338. // if the particles will always face the camera
  46339. if (this.billboard) {
  46340. // compute the camera position and un-rotate it by the current mesh rotation
  46341. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  46342. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  46343. this._cam_axisZ.normalize();
  46344. // same for camera up vector extracted from the cam view matrix
  46345. var view = this._camera.getViewMatrix(true);
  46346. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  46347. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  46348. this._cam_axisY.normalize();
  46349. this._cam_axisX.normalize();
  46350. }
  46351. // if depthSort, compute the camera global position in the mesh local system
  46352. if (this._depthSort) {
  46353. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  46354. }
  46355. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  46356. var idx = 0; // current position index in the global array positions32
  46357. var index = 0; // position start index in the global array positions32 of the current particle
  46358. var colidx = 0; // current color index in the global array colors32
  46359. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  46360. var uvidx = 0; // current uv index in the global array uvs32
  46361. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  46362. var pt = 0; // current index in the particle model shape
  46363. if (this.mesh.isFacetDataEnabled) {
  46364. this._computeBoundingBox = true;
  46365. }
  46366. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  46367. if (this._computeBoundingBox) {
  46368. if (start == 0 && end == this.nbParticles - 1) {
  46369. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  46370. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  46371. }
  46372. else {
  46373. if (this.mesh._boundingInfo) {
  46374. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  46375. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  46376. }
  46377. }
  46378. }
  46379. // particle loop
  46380. index = this.particles[start]._pos;
  46381. var vpos = (index / 3) | 0;
  46382. colorIndex = vpos * 4;
  46383. uvIndex = vpos * 2;
  46384. for (var p = start; p <= end; p++) {
  46385. this._particle = this.particles[p];
  46386. this._shape = this._particle._model._shape;
  46387. this._shapeUV = this._particle._model._shapeUV;
  46388. // call to custom user function to update the particle properties
  46389. this.updateParticle(this._particle);
  46390. // camera-particle distance for depth sorting
  46391. if (this._depthSort && this._depthSortParticles) {
  46392. var dsp = this.depthSortedParticles[p];
  46393. dsp.ind = this._particle._ind;
  46394. dsp.indicesLength = this._particle._model._indicesLength;
  46395. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  46396. }
  46397. // skip the computations for inactive or already invisible particles
  46398. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  46399. // increment indexes for the next particle
  46400. pt = this._shape.length;
  46401. index += pt * 3;
  46402. colorIndex += pt * 4;
  46403. uvIndex += pt * 2;
  46404. continue;
  46405. }
  46406. if (this._particle.isVisible) {
  46407. this._particle._stillInvisible = false; // un-mark permanent invisibility
  46408. // particle rotation matrix
  46409. if (this.billboard) {
  46410. this._particle.rotation.x = 0.0;
  46411. this._particle.rotation.y = 0.0;
  46412. }
  46413. if (this._computeParticleRotation || this.billboard) {
  46414. if (this._particle.rotationQuaternion) {
  46415. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46416. }
  46417. else {
  46418. this._yaw = this._particle.rotation.y;
  46419. this._pitch = this._particle.rotation.x;
  46420. this._roll = this._particle.rotation.z;
  46421. this._quaternionRotationYPR();
  46422. }
  46423. this._quaternionToRotationMatrix();
  46424. }
  46425. // particle vertex loop
  46426. for (pt = 0; pt < this._shape.length; pt++) {
  46427. idx = index + pt * 3;
  46428. colidx = colorIndex + pt * 4;
  46429. uvidx = uvIndex + pt * 2;
  46430. this._vertex.x = this._shape[pt].x;
  46431. this._vertex.y = this._shape[pt].y;
  46432. this._vertex.z = this._shape[pt].z;
  46433. if (this._computeParticleVertex) {
  46434. this.updateParticleVertex(this._particle, this._vertex, pt);
  46435. }
  46436. // positions
  46437. this._vertex.x *= this._particle.scaling.x;
  46438. this._vertex.y *= this._particle.scaling.y;
  46439. this._vertex.z *= this._particle.scaling.z;
  46440. this._vertex.x += this._particle.pivot.x;
  46441. this._vertex.y += this._particle.pivot.y;
  46442. this._vertex.z += this._particle.pivot.z;
  46443. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46444. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46445. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46446. 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;
  46447. 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;
  46448. 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;
  46449. if (this._computeBoundingBox) {
  46450. if (this._positions32[idx] < this._minimum.x) {
  46451. this._minimum.x = this._positions32[idx];
  46452. }
  46453. if (this._positions32[idx] > this._maximum.x) {
  46454. this._maximum.x = this._positions32[idx];
  46455. }
  46456. if (this._positions32[idx + 1] < this._minimum.y) {
  46457. this._minimum.y = this._positions32[idx + 1];
  46458. }
  46459. if (this._positions32[idx + 1] > this._maximum.y) {
  46460. this._maximum.y = this._positions32[idx + 1];
  46461. }
  46462. if (this._positions32[idx + 2] < this._minimum.z) {
  46463. this._minimum.z = this._positions32[idx + 2];
  46464. }
  46465. if (this._positions32[idx + 2] > this._maximum.z) {
  46466. this._maximum.z = this._positions32[idx + 2];
  46467. }
  46468. }
  46469. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46470. if (!this._computeParticleVertex) {
  46471. this._normal.x = this._fixedNormal32[idx];
  46472. this._normal.y = this._fixedNormal32[idx + 1];
  46473. this._normal.z = this._fixedNormal32[idx + 2];
  46474. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46475. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46476. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46477. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46478. 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;
  46479. 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;
  46480. }
  46481. if (this._computeParticleColor && this._particle.color) {
  46482. this._colors32[colidx] = this._particle.color.r;
  46483. this._colors32[colidx + 1] = this._particle.color.g;
  46484. this._colors32[colidx + 2] = this._particle.color.b;
  46485. this._colors32[colidx + 3] = this._particle.color.a;
  46486. }
  46487. if (this._computeParticleTexture) {
  46488. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46489. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46490. }
  46491. }
  46492. }
  46493. else {
  46494. this._particle._stillInvisible = true; // mark the particle as invisible
  46495. for (pt = 0; pt < this._shape.length; pt++) {
  46496. idx = index + pt * 3;
  46497. colidx = colorIndex + pt * 4;
  46498. uvidx = uvIndex + pt * 2;
  46499. this._positions32[idx] = 0.0;
  46500. this._positions32[idx + 1] = 0.0;
  46501. this._positions32[idx + 2] = 0.0;
  46502. this._normals32[idx] = 0.0;
  46503. this._normals32[idx + 1] = 0.0;
  46504. this._normals32[idx + 2] = 0.0;
  46505. if (this._computeParticleColor && this._particle.color) {
  46506. this._colors32[colidx] = this._particle.color.r;
  46507. this._colors32[colidx + 1] = this._particle.color.g;
  46508. this._colors32[colidx + 2] = this._particle.color.b;
  46509. this._colors32[colidx + 3] = this._particle.color.a;
  46510. }
  46511. if (this._computeParticleTexture) {
  46512. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46513. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46514. }
  46515. }
  46516. }
  46517. // if the particle intersections must be computed : update the bbInfo
  46518. if (this._particlesIntersect) {
  46519. var bInfo = this._particle._boundingInfo;
  46520. var bBox = bInfo.boundingBox;
  46521. var bSphere = bInfo.boundingSphere;
  46522. if (!this._bSphereOnly) {
  46523. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46524. for (var b = 0; b < bBox.vectors.length; b++) {
  46525. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46526. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46527. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46528. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46529. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46530. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46531. 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;
  46532. 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;
  46533. 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;
  46534. }
  46535. bBox._update(this.mesh._worldMatrix);
  46536. }
  46537. // place and scale the particle bouding sphere in the SPS local system, then update it
  46538. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46539. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46540. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46541. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46542. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46543. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46544. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46545. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46546. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46547. 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));
  46548. bSphere._update(this.mesh._worldMatrix);
  46549. }
  46550. // increment indexes for the next particle
  46551. index = idx + 3;
  46552. colorIndex = colidx + 4;
  46553. uvIndex = uvidx + 2;
  46554. }
  46555. // if the VBO must be updated
  46556. if (update) {
  46557. if (this._computeParticleColor) {
  46558. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46559. }
  46560. if (this._computeParticleTexture) {
  46561. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46562. }
  46563. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46564. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46565. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46566. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46567. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46568. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46569. for (var i = 0; i < this._normals32.length; i++) {
  46570. this._fixedNormal32[i] = this._normals32[i];
  46571. }
  46572. }
  46573. if (!this.mesh.areNormalsFrozen) {
  46574. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46575. }
  46576. }
  46577. if (this._depthSort && this._depthSortParticles) {
  46578. this.depthSortedParticles.sort(this._depthSortFunction);
  46579. var dspl = this.depthSortedParticles.length;
  46580. var sorted = 0;
  46581. var lind = 0;
  46582. var sind = 0;
  46583. var sid = 0;
  46584. for (sorted = 0; sorted < dspl; sorted++) {
  46585. lind = this.depthSortedParticles[sorted].indicesLength;
  46586. sind = this.depthSortedParticles[sorted].ind;
  46587. for (var i = 0; i < lind; i++) {
  46588. this._indices32[sid] = this._indices[sind + i];
  46589. sid++;
  46590. }
  46591. }
  46592. this.mesh.updateIndices(this._indices32);
  46593. }
  46594. }
  46595. if (this._computeBoundingBox) {
  46596. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46597. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46598. }
  46599. this.afterUpdateParticles(start, end, update);
  46600. return this;
  46601. };
  46602. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46603. this._halfroll = this._roll * 0.5;
  46604. this._halfpitch = this._pitch * 0.5;
  46605. this._halfyaw = this._yaw * 0.5;
  46606. this._sinRoll = Math.sin(this._halfroll);
  46607. this._cosRoll = Math.cos(this._halfroll);
  46608. this._sinPitch = Math.sin(this._halfpitch);
  46609. this._cosPitch = Math.cos(this._halfpitch);
  46610. this._sinYaw = Math.sin(this._halfyaw);
  46611. this._cosYaw = Math.cos(this._halfyaw);
  46612. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46613. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46614. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46615. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46616. };
  46617. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46618. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46619. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46620. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46621. this._rotMatrix.m[3] = 0;
  46622. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46623. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46624. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46625. this._rotMatrix.m[7] = 0;
  46626. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46627. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46628. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46629. this._rotMatrix.m[11] = 0;
  46630. this._rotMatrix.m[12] = 0;
  46631. this._rotMatrix.m[13] = 0;
  46632. this._rotMatrix.m[14] = 0;
  46633. this._rotMatrix.m[15] = 1.0;
  46634. };
  46635. /**
  46636. * Disposes the SPS.
  46637. * Returns nothing.
  46638. */
  46639. SolidParticleSystem.prototype.dispose = function () {
  46640. this.mesh.dispose();
  46641. this.vars = null;
  46642. // drop references to internal big arrays for the GC
  46643. this._positions = null;
  46644. this._indices = null;
  46645. this._normals = null;
  46646. this._uvs = null;
  46647. this._colors = null;
  46648. this._indices32 = null;
  46649. this._positions32 = null;
  46650. this._normals32 = null;
  46651. this._fixedNormal32 = null;
  46652. this._uvs32 = null;
  46653. this._colors32 = null;
  46654. this.pickedParticles = null;
  46655. };
  46656. /**
  46657. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46658. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46659. * Returns the SPS.
  46660. */
  46661. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46662. if (!this._isVisibilityBoxLocked) {
  46663. this.mesh.refreshBoundingInfo();
  46664. }
  46665. return this;
  46666. };
  46667. /**
  46668. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46669. * @param size the size (float) of the visibility box
  46670. * note : this doesn't lock the SPS mesh bounding box.
  46671. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46672. */
  46673. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46674. var vis = size / 2;
  46675. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46676. };
  46677. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46678. // getter and setter
  46679. get: function () {
  46680. return this._alwaysVisible;
  46681. },
  46682. /**
  46683. * Sets the SPS as always visible or not
  46684. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46685. */
  46686. set: function (val) {
  46687. this._alwaysVisible = val;
  46688. this.mesh.alwaysSelectAsActiveMesh = val;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46694. get: function () {
  46695. return this._isVisibilityBoxLocked;
  46696. },
  46697. /**
  46698. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46699. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46700. */
  46701. set: function (val) {
  46702. this._isVisibilityBoxLocked = val;
  46703. var boundingInfo = this.mesh.getBoundingInfo();
  46704. boundingInfo.isLocked = val;
  46705. },
  46706. enumerable: true,
  46707. configurable: true
  46708. });
  46709. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46710. // getters
  46711. get: function () {
  46712. return this._computeParticleRotation;
  46713. },
  46714. // Optimizer setters
  46715. /**
  46716. * Tells to `setParticles()` to compute the particle rotations or not.
  46717. * Default value : true. The SPS is faster when it's set to false.
  46718. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46719. */
  46720. set: function (val) {
  46721. this._computeParticleRotation = val;
  46722. },
  46723. enumerable: true,
  46724. configurable: true
  46725. });
  46726. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46727. get: function () {
  46728. return this._computeParticleColor;
  46729. },
  46730. /**
  46731. * Tells to `setParticles()` to compute the particle colors or not.
  46732. * Default value : true. The SPS is faster when it's set to false.
  46733. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46734. */
  46735. set: function (val) {
  46736. this._computeParticleColor = val;
  46737. },
  46738. enumerable: true,
  46739. configurable: true
  46740. });
  46741. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46742. get: function () {
  46743. return this._computeParticleTexture;
  46744. },
  46745. /**
  46746. * Tells to `setParticles()` to compute the particle textures or not.
  46747. * Default value : true. The SPS is faster when it's set to false.
  46748. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46749. */
  46750. set: function (val) {
  46751. this._computeParticleTexture = val;
  46752. },
  46753. enumerable: true,
  46754. configurable: true
  46755. });
  46756. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46757. get: function () {
  46758. return this._computeParticleVertex;
  46759. },
  46760. /**
  46761. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46762. * Default value : false. The SPS is faster when it's set to false.
  46763. * Note : the particle custom vertex positions aren't stored values.
  46764. */
  46765. set: function (val) {
  46766. this._computeParticleVertex = val;
  46767. },
  46768. enumerable: true,
  46769. configurable: true
  46770. });
  46771. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46772. get: function () {
  46773. return this._computeBoundingBox;
  46774. },
  46775. /**
  46776. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46777. */
  46778. set: function (val) {
  46779. this._computeBoundingBox = val;
  46780. },
  46781. enumerable: true,
  46782. configurable: true
  46783. });
  46784. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46785. get: function () {
  46786. return this._depthSortParticles;
  46787. },
  46788. /**
  46789. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46790. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46791. * Default : `true`
  46792. */
  46793. set: function (val) {
  46794. this._depthSortParticles = val;
  46795. },
  46796. enumerable: true,
  46797. configurable: true
  46798. });
  46799. // =======================================================================
  46800. // Particle behavior logic
  46801. // these following methods may be overwritten by the user to fit his needs
  46802. /**
  46803. * This function does nothing. It may be overwritten to set all the particle first values.
  46804. * The SPS doesn't call this function, you may have to call it by your own.
  46805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46806. */
  46807. SolidParticleSystem.prototype.initParticles = function () {
  46808. };
  46809. /**
  46810. * This function does nothing. It may be overwritten to recycle a particle.
  46811. * The SPS doesn't call this function, you may have to call it by your own.
  46812. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46813. */
  46814. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46815. return particle;
  46816. };
  46817. /**
  46818. * Updates a particle : this function should be overwritten by the user.
  46819. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46820. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46821. * ex : just set a particle position or velocity and recycle conditions
  46822. */
  46823. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46824. return particle;
  46825. };
  46826. /**
  46827. * Updates a vertex of a particle : it can be overwritten by the user.
  46828. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46829. * @param particle the current particle
  46830. * @param vertex the current index of the current particle
  46831. * @param pt the index of the current vertex in the particle shape
  46832. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46833. * ex : just set a vertex particle position
  46834. */
  46835. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46836. return vertex;
  46837. };
  46838. /**
  46839. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46840. * This does nothing and may be overwritten by the user.
  46841. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46842. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46843. * @param update the boolean update value actually passed to setParticles()
  46844. */
  46845. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46846. };
  46847. /**
  46848. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46849. * This will be passed three parameters.
  46850. * This does nothing and may be overwritten by the user.
  46851. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46852. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46853. * @param update the boolean update value actually passed to setParticles()
  46854. */
  46855. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46856. };
  46857. return SolidParticleSystem;
  46858. }());
  46859. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46860. })(BABYLON || (BABYLON = {}));
  46861. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46862. var BABYLON;
  46863. (function (BABYLON) {
  46864. var GroundMesh = /** @class */ (function (_super) {
  46865. __extends(GroundMesh, _super);
  46866. function GroundMesh(name, scene) {
  46867. var _this = _super.call(this, name, scene) || this;
  46868. _this.generateOctree = false;
  46869. return _this;
  46870. }
  46871. GroundMesh.prototype.getClassName = function () {
  46872. return "GroundMesh";
  46873. };
  46874. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46875. get: function () {
  46876. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46877. },
  46878. enumerable: true,
  46879. configurable: true
  46880. });
  46881. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46882. get: function () {
  46883. return this._subdivisionsX;
  46884. },
  46885. enumerable: true,
  46886. configurable: true
  46887. });
  46888. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46889. get: function () {
  46890. return this._subdivisionsY;
  46891. },
  46892. enumerable: true,
  46893. configurable: true
  46894. });
  46895. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46896. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46897. this._subdivisionsX = chunksCount;
  46898. this._subdivisionsY = chunksCount;
  46899. this.subdivide(chunksCount);
  46900. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46901. };
  46902. /**
  46903. * Returns a height (y) value in the Worl system :
  46904. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46905. * Returns the ground y position if (x, z) are outside the ground surface.
  46906. */
  46907. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46908. var world = this.getWorldMatrix();
  46909. var invMat = BABYLON.Tmp.Matrix[5];
  46910. world.invertToRef(invMat);
  46911. var tmpVect = BABYLON.Tmp.Vector3[8];
  46912. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46913. x = tmpVect.x;
  46914. z = tmpVect.z;
  46915. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46916. return this.position.y;
  46917. }
  46918. if (!this._heightQuads || this._heightQuads.length == 0) {
  46919. this._initHeightQuads();
  46920. this._computeHeightQuads();
  46921. }
  46922. var facet = this._getFacetAt(x, z);
  46923. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46924. // return y in the World system
  46925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46926. return tmpVect.y;
  46927. };
  46928. /**
  46929. * Returns a normalized vector (Vector3) orthogonal to the ground
  46930. * at the ground coordinates (x, z) expressed in the World system.
  46931. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46932. */
  46933. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46934. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46935. this.getNormalAtCoordinatesToRef(x, z, normal);
  46936. return normal;
  46937. };
  46938. /**
  46939. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46940. * at the ground coordinates (x, z) expressed in the World system.
  46941. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46942. * Returns the GroundMesh.
  46943. */
  46944. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46945. var world = this.getWorldMatrix();
  46946. var tmpMat = BABYLON.Tmp.Matrix[5];
  46947. world.invertToRef(tmpMat);
  46948. var tmpVect = BABYLON.Tmp.Vector3[8];
  46949. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46950. x = tmpVect.x;
  46951. z = tmpVect.z;
  46952. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46953. return this;
  46954. }
  46955. if (!this._heightQuads || this._heightQuads.length == 0) {
  46956. this._initHeightQuads();
  46957. this._computeHeightQuads();
  46958. }
  46959. var facet = this._getFacetAt(x, z);
  46960. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46961. return this;
  46962. };
  46963. /**
  46964. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46965. * if the ground has been updated.
  46966. * This can be used in the render loop.
  46967. * Returns the GroundMesh.
  46968. */
  46969. GroundMesh.prototype.updateCoordinateHeights = function () {
  46970. if (!this._heightQuads || this._heightQuads.length == 0) {
  46971. this._initHeightQuads();
  46972. }
  46973. this._computeHeightQuads();
  46974. return this;
  46975. };
  46976. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46977. GroundMesh.prototype._getFacetAt = function (x, z) {
  46978. // retrieve col and row from x, z coordinates in the ground local system
  46979. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46980. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46981. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46982. var facet;
  46983. if (z < quad.slope.x * x + quad.slope.y) {
  46984. facet = quad.facet1;
  46985. }
  46986. else {
  46987. facet = quad.facet2;
  46988. }
  46989. return facet;
  46990. };
  46991. // Creates and populates the heightMap array with "facet" elements :
  46992. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46993. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46994. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46995. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46996. // Returns the GroundMesh.
  46997. GroundMesh.prototype._initHeightQuads = function () {
  46998. var subdivisionsX = this._subdivisionsX;
  46999. var subdivisionsY = this._subdivisionsY;
  47000. this._heightQuads = new Array();
  47001. for (var row = 0; row < subdivisionsY; row++) {
  47002. for (var col = 0; col < subdivisionsX; col++) {
  47003. 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) };
  47004. this._heightQuads[row * subdivisionsX + col] = quad;
  47005. }
  47006. }
  47007. return this;
  47008. };
  47009. // Compute each quad element values and update the the heightMap array :
  47010. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47011. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47012. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47013. // Returns the GroundMesh.
  47014. GroundMesh.prototype._computeHeightQuads = function () {
  47015. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47016. if (!positions) {
  47017. return this;
  47018. }
  47019. var v1 = BABYLON.Tmp.Vector3[3];
  47020. var v2 = BABYLON.Tmp.Vector3[2];
  47021. var v3 = BABYLON.Tmp.Vector3[1];
  47022. var v4 = BABYLON.Tmp.Vector3[0];
  47023. var v1v2 = BABYLON.Tmp.Vector3[4];
  47024. var v1v3 = BABYLON.Tmp.Vector3[5];
  47025. var v1v4 = BABYLON.Tmp.Vector3[6];
  47026. var norm1 = BABYLON.Tmp.Vector3[7];
  47027. var norm2 = BABYLON.Tmp.Vector3[8];
  47028. var i = 0;
  47029. var j = 0;
  47030. var k = 0;
  47031. var cd = 0; // 2D slope coefficient : z = cd * x + h
  47032. var h = 0;
  47033. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  47034. var d2 = 0;
  47035. var subdivisionsX = this._subdivisionsX;
  47036. var subdivisionsY = this._subdivisionsY;
  47037. for (var row = 0; row < subdivisionsY; row++) {
  47038. for (var col = 0; col < subdivisionsX; col++) {
  47039. i = col * 3;
  47040. j = row * (subdivisionsX + 1) * 3;
  47041. k = (row + 1) * (subdivisionsX + 1) * 3;
  47042. v1.x = positions[j + i];
  47043. v1.y = positions[j + i + 1];
  47044. v1.z = positions[j + i + 2];
  47045. v2.x = positions[j + i + 3];
  47046. v2.y = positions[j + i + 4];
  47047. v2.z = positions[j + i + 5];
  47048. v3.x = positions[k + i];
  47049. v3.y = positions[k + i + 1];
  47050. v3.z = positions[k + i + 2];
  47051. v4.x = positions[k + i + 3];
  47052. v4.y = positions[k + i + 4];
  47053. v4.z = positions[k + i + 5];
  47054. // 2D slope V1V4
  47055. cd = (v4.z - v1.z) / (v4.x - v1.x);
  47056. h = v1.z - cd * v1.x; // v1 belongs to the slope
  47057. // facet equations :
  47058. // we compute each facet normal vector
  47059. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  47060. // we compute the value d by applying the equation to v1 which belongs to the plane
  47061. // then we store the facet equation in a Vector4
  47062. v2.subtractToRef(v1, v1v2);
  47063. v3.subtractToRef(v1, v1v3);
  47064. v4.subtractToRef(v1, v1v4);
  47065. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  47066. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  47067. norm1.normalize();
  47068. norm2.normalize();
  47069. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  47070. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  47071. var quad = this._heightQuads[row * subdivisionsX + col];
  47072. quad.slope.copyFromFloats(cd, h);
  47073. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  47074. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  47075. }
  47076. }
  47077. return this;
  47078. };
  47079. GroundMesh.prototype.serialize = function (serializationObject) {
  47080. _super.prototype.serialize.call(this, serializationObject);
  47081. serializationObject.subdivisionsX = this._subdivisionsX;
  47082. serializationObject.subdivisionsY = this._subdivisionsY;
  47083. serializationObject.minX = this._minX;
  47084. serializationObject.maxX = this._maxX;
  47085. serializationObject.minZ = this._minZ;
  47086. serializationObject.maxZ = this._maxZ;
  47087. serializationObject.width = this._width;
  47088. serializationObject.height = this._height;
  47089. };
  47090. GroundMesh.Parse = function (parsedMesh, scene) {
  47091. var result = new GroundMesh(parsedMesh.name, scene);
  47092. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  47093. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  47094. result._minX = parsedMesh.minX;
  47095. result._maxX = parsedMesh.maxX;
  47096. result._minZ = parsedMesh.minZ;
  47097. result._maxZ = parsedMesh.maxZ;
  47098. result._width = parsedMesh.width;
  47099. result._height = parsedMesh.height;
  47100. return result;
  47101. };
  47102. return GroundMesh;
  47103. }(BABYLON.Mesh));
  47104. BABYLON.GroundMesh = GroundMesh;
  47105. })(BABYLON || (BABYLON = {}));
  47106. //# sourceMappingURL=babylon.groundMesh.js.map
  47107. var BABYLON;
  47108. (function (BABYLON) {
  47109. /**
  47110. * Creates an instance based on a source mesh.
  47111. */
  47112. var InstancedMesh = /** @class */ (function (_super) {
  47113. __extends(InstancedMesh, _super);
  47114. function InstancedMesh(name, source) {
  47115. var _this = _super.call(this, name, source.getScene()) || this;
  47116. source.instances.push(_this);
  47117. _this._sourceMesh = source;
  47118. _this.position.copyFrom(source.position);
  47119. _this.rotation.copyFrom(source.rotation);
  47120. _this.scaling.copyFrom(source.scaling);
  47121. if (source.rotationQuaternion) {
  47122. _this.rotationQuaternion = source.rotationQuaternion.clone();
  47123. }
  47124. _this.infiniteDistance = source.infiniteDistance;
  47125. _this.setPivotMatrix(source.getPivotMatrix());
  47126. _this.refreshBoundingInfo();
  47127. _this._syncSubMeshes();
  47128. return _this;
  47129. }
  47130. /**
  47131. * Returns the string "InstancedMesh".
  47132. */
  47133. InstancedMesh.prototype.getClassName = function () {
  47134. return "InstancedMesh";
  47135. };
  47136. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  47137. // Methods
  47138. get: function () {
  47139. return this._sourceMesh.receiveShadows;
  47140. },
  47141. enumerable: true,
  47142. configurable: true
  47143. });
  47144. Object.defineProperty(InstancedMesh.prototype, "material", {
  47145. get: function () {
  47146. return this._sourceMesh.material;
  47147. },
  47148. enumerable: true,
  47149. configurable: true
  47150. });
  47151. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  47152. get: function () {
  47153. return this._sourceMesh.visibility;
  47154. },
  47155. enumerable: true,
  47156. configurable: true
  47157. });
  47158. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  47159. get: function () {
  47160. return this._sourceMesh.skeleton;
  47161. },
  47162. enumerable: true,
  47163. configurable: true
  47164. });
  47165. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  47166. get: function () {
  47167. return this._sourceMesh.renderingGroupId;
  47168. },
  47169. enumerable: true,
  47170. configurable: true
  47171. });
  47172. /**
  47173. * Returns the total number of vertices (integer).
  47174. */
  47175. InstancedMesh.prototype.getTotalVertices = function () {
  47176. return this._sourceMesh.getTotalVertices();
  47177. };
  47178. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  47179. get: function () {
  47180. return this._sourceMesh;
  47181. },
  47182. enumerable: true,
  47183. configurable: true
  47184. });
  47185. /**
  47186. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  47187. */
  47188. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  47189. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  47190. };
  47191. /**
  47192. * Sets the vertex data of the mesh geometry for the requested `kind`.
  47193. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  47194. * The `data` are either a numeric array either a Float32Array.
  47195. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  47196. * 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).
  47197. * Note that a new underlying VertexBuffer object is created each call.
  47198. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  47199. *
  47200. * Possible `kind` values :
  47201. * - BABYLON.VertexBuffer.PositionKind
  47202. * - BABYLON.VertexBuffer.UVKind
  47203. * - BABYLON.VertexBuffer.UV2Kind
  47204. * - BABYLON.VertexBuffer.UV3Kind
  47205. * - BABYLON.VertexBuffer.UV4Kind
  47206. * - BABYLON.VertexBuffer.UV5Kind
  47207. * - BABYLON.VertexBuffer.UV6Kind
  47208. * - BABYLON.VertexBuffer.ColorKind
  47209. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47210. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47211. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47212. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47213. *
  47214. * Returns the Mesh.
  47215. */
  47216. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  47217. if (this.sourceMesh) {
  47218. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  47219. }
  47220. return this.sourceMesh;
  47221. };
  47222. /**
  47223. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  47224. * If the mesh has no geometry, it is simply returned as it is.
  47225. * The `data` are either a numeric array either a Float32Array.
  47226. * No new underlying VertexBuffer object is created.
  47227. * 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.
  47228. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  47229. *
  47230. * Possible `kind` values :
  47231. * - BABYLON.VertexBuffer.PositionKind
  47232. * - BABYLON.VertexBuffer.UVKind
  47233. * - BABYLON.VertexBuffer.UV2Kind
  47234. * - BABYLON.VertexBuffer.UV3Kind
  47235. * - BABYLON.VertexBuffer.UV4Kind
  47236. * - BABYLON.VertexBuffer.UV5Kind
  47237. * - BABYLON.VertexBuffer.UV6Kind
  47238. * - BABYLON.VertexBuffer.ColorKind
  47239. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47240. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47241. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47242. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47243. *
  47244. * Returns the Mesh.
  47245. */
  47246. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  47247. if (this.sourceMesh) {
  47248. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  47249. }
  47250. return this.sourceMesh;
  47251. };
  47252. /**
  47253. * Sets the mesh indices.
  47254. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  47255. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  47256. * This method creates a new index buffer each call.
  47257. * Returns the Mesh.
  47258. */
  47259. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  47260. if (totalVertices === void 0) { totalVertices = null; }
  47261. if (this.sourceMesh) {
  47262. this.sourceMesh.setIndices(indices, totalVertices);
  47263. }
  47264. return this.sourceMesh;
  47265. };
  47266. /**
  47267. * Boolean : True if the mesh owns the requested kind of data.
  47268. */
  47269. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  47270. return this._sourceMesh.isVerticesDataPresent(kind);
  47271. };
  47272. /**
  47273. * Returns an array of indices (IndicesArray).
  47274. */
  47275. InstancedMesh.prototype.getIndices = function () {
  47276. return this._sourceMesh.getIndices();
  47277. };
  47278. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  47279. get: function () {
  47280. return this._sourceMesh._positions;
  47281. },
  47282. enumerable: true,
  47283. configurable: true
  47284. });
  47285. /**
  47286. * Sets a new updated BoundingInfo to the mesh.
  47287. * Returns the mesh.
  47288. */
  47289. InstancedMesh.prototype.refreshBoundingInfo = function () {
  47290. var meshBB = this._sourceMesh.getBoundingInfo();
  47291. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  47292. this._updateBoundingInfo();
  47293. return this;
  47294. };
  47295. InstancedMesh.prototype._preActivate = function () {
  47296. if (this._currentLOD) {
  47297. this._currentLOD._preActivate();
  47298. }
  47299. return this;
  47300. };
  47301. InstancedMesh.prototype._activate = function (renderId) {
  47302. if (this._currentLOD) {
  47303. this._currentLOD._registerInstanceForRenderId(this, renderId);
  47304. }
  47305. return this;
  47306. };
  47307. /**
  47308. * Returns the current associated LOD AbstractMesh.
  47309. */
  47310. InstancedMesh.prototype.getLOD = function (camera) {
  47311. if (!camera) {
  47312. return this;
  47313. }
  47314. var boundingInfo = this.getBoundingInfo();
  47315. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  47316. if (this._currentLOD === this.sourceMesh) {
  47317. return this;
  47318. }
  47319. return this._currentLOD;
  47320. };
  47321. InstancedMesh.prototype._syncSubMeshes = function () {
  47322. this.releaseSubMeshes();
  47323. if (this._sourceMesh.subMeshes) {
  47324. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  47325. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  47326. }
  47327. }
  47328. return this;
  47329. };
  47330. InstancedMesh.prototype._generatePointsArray = function () {
  47331. return this._sourceMesh._generatePointsArray();
  47332. };
  47333. /**
  47334. * Creates a new InstancedMesh from the current mesh.
  47335. * - name (string) : the cloned mesh name
  47336. * - newParent (optional Node) : the optional Node to parent the clone to.
  47337. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  47338. *
  47339. * Returns the clone.
  47340. */
  47341. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47342. var result = this._sourceMesh.createInstance(name);
  47343. // Deep copy
  47344. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  47345. // Bounding info
  47346. this.refreshBoundingInfo();
  47347. // Parent
  47348. if (newParent) {
  47349. result.parent = newParent;
  47350. }
  47351. if (!doNotCloneChildren) {
  47352. // Children
  47353. for (var index = 0; index < this.getScene().meshes.length; index++) {
  47354. var mesh = this.getScene().meshes[index];
  47355. if (mesh.parent === this) {
  47356. mesh.clone(mesh.name, result);
  47357. }
  47358. }
  47359. }
  47360. result.computeWorldMatrix(true);
  47361. return result;
  47362. };
  47363. /**
  47364. * Disposes the InstancedMesh.
  47365. * Returns nothing.
  47366. */
  47367. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  47368. // Remove from mesh
  47369. var index = this._sourceMesh.instances.indexOf(this);
  47370. this._sourceMesh.instances.splice(index, 1);
  47371. _super.prototype.dispose.call(this, doNotRecurse);
  47372. };
  47373. return InstancedMesh;
  47374. }(BABYLON.AbstractMesh));
  47375. BABYLON.InstancedMesh = InstancedMesh;
  47376. })(BABYLON || (BABYLON = {}));
  47377. //# sourceMappingURL=babylon.instancedMesh.js.map
  47378. var BABYLON;
  47379. (function (BABYLON) {
  47380. var LinesMesh = /** @class */ (function (_super) {
  47381. __extends(LinesMesh, _super);
  47382. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  47383. if (scene === void 0) { scene = null; }
  47384. if (parent === void 0) { parent = null; }
  47385. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  47386. _this.useVertexColor = useVertexColor;
  47387. _this.useVertexAlpha = useVertexAlpha;
  47388. _this.color = new BABYLON.Color3(1, 1, 1);
  47389. _this.alpha = 1;
  47390. if (source) {
  47391. _this.color = source.color.clone();
  47392. _this.alpha = source.alpha;
  47393. _this.useVertexColor = source.useVertexColor;
  47394. _this.useVertexAlpha = source.useVertexAlpha;
  47395. }
  47396. _this._intersectionThreshold = 0.1;
  47397. var defines = [];
  47398. var options = {
  47399. attributes: [BABYLON.VertexBuffer.PositionKind],
  47400. uniforms: ["world", "viewProjection"],
  47401. needAlphaBlending: true,
  47402. defines: defines
  47403. };
  47404. if (useVertexAlpha === false) {
  47405. options.needAlphaBlending = false;
  47406. }
  47407. if (!useVertexColor) {
  47408. options.uniforms.push("color");
  47409. }
  47410. else {
  47411. options.defines.push("#define VERTEXCOLOR");
  47412. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  47413. }
  47414. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  47415. return _this;
  47416. }
  47417. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  47418. /**
  47419. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47420. * This margin is expressed in world space coordinates, so its value may vary.
  47421. * Default value is 0.1
  47422. * @returns the intersection Threshold value.
  47423. */
  47424. get: function () {
  47425. return this._intersectionThreshold;
  47426. },
  47427. /**
  47428. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  47429. * This margin is expressed in world space coordinates, so its value may vary.
  47430. * @param value the new threshold to apply
  47431. */
  47432. set: function (value) {
  47433. if (this._intersectionThreshold === value) {
  47434. return;
  47435. }
  47436. this._intersectionThreshold = value;
  47437. if (this.geometry) {
  47438. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  47439. }
  47440. },
  47441. enumerable: true,
  47442. configurable: true
  47443. });
  47444. /**
  47445. * Returns the string "LineMesh"
  47446. */
  47447. LinesMesh.prototype.getClassName = function () {
  47448. return "LinesMesh";
  47449. };
  47450. Object.defineProperty(LinesMesh.prototype, "material", {
  47451. get: function () {
  47452. return this._colorShader;
  47453. },
  47454. set: function (value) {
  47455. // Do nothing
  47456. },
  47457. enumerable: true,
  47458. configurable: true
  47459. });
  47460. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47461. get: function () {
  47462. return false;
  47463. },
  47464. enumerable: true,
  47465. configurable: true
  47466. });
  47467. LinesMesh.prototype.createInstance = function (name) {
  47468. throw new Error("LinesMeshes do not support createInstance.");
  47469. };
  47470. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47471. if (!this._geometry) {
  47472. return this;
  47473. }
  47474. // VBOs
  47475. this._geometry._bind(this._colorShader.getEffect());
  47476. // Color
  47477. if (!this.useVertexColor) {
  47478. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47479. }
  47480. return this;
  47481. };
  47482. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47483. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47484. return this;
  47485. }
  47486. var engine = this.getScene().getEngine();
  47487. // Draw order
  47488. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  47489. return this;
  47490. };
  47491. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47492. this._colorShader.dispose();
  47493. _super.prototype.dispose.call(this, doNotRecurse);
  47494. };
  47495. /**
  47496. * Returns a new LineMesh object cloned from the current one.
  47497. */
  47498. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47499. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47500. };
  47501. return LinesMesh;
  47502. }(BABYLON.Mesh));
  47503. BABYLON.LinesMesh = LinesMesh;
  47504. })(BABYLON || (BABYLON = {}));
  47505. //# sourceMappingURL=babylon.linesMesh.js.map
  47506. var BABYLON;
  47507. (function (BABYLON) {
  47508. var ShaderMaterial = /** @class */ (function (_super) {
  47509. __extends(ShaderMaterial, _super);
  47510. function ShaderMaterial(name, scene, shaderPath, options) {
  47511. var _this = _super.call(this, name, scene) || this;
  47512. _this._textures = {};
  47513. _this._textureArrays = {};
  47514. _this._floats = {};
  47515. _this._floatsArrays = {};
  47516. _this._colors3 = {};
  47517. _this._colors3Arrays = {};
  47518. _this._colors4 = {};
  47519. _this._vectors2 = {};
  47520. _this._vectors3 = {};
  47521. _this._vectors4 = {};
  47522. _this._matrices = {};
  47523. _this._matrices3x3 = {};
  47524. _this._matrices2x2 = {};
  47525. _this._vectors2Arrays = {};
  47526. _this._vectors3Arrays = {};
  47527. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47528. _this._shaderPath = shaderPath;
  47529. options.needAlphaBlending = options.needAlphaBlending || false;
  47530. options.needAlphaTesting = options.needAlphaTesting || false;
  47531. options.attributes = options.attributes || ["position", "normal", "uv"];
  47532. options.uniforms = options.uniforms || ["worldViewProjection"];
  47533. options.uniformBuffers = options.uniformBuffers || [];
  47534. options.samplers = options.samplers || [];
  47535. options.defines = options.defines || [];
  47536. _this._options = options;
  47537. return _this;
  47538. }
  47539. ShaderMaterial.prototype.getClassName = function () {
  47540. return "ShaderMaterial";
  47541. };
  47542. ShaderMaterial.prototype.needAlphaBlending = function () {
  47543. return this._options.needAlphaBlending;
  47544. };
  47545. ShaderMaterial.prototype.needAlphaTesting = function () {
  47546. return this._options.needAlphaTesting;
  47547. };
  47548. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47549. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47550. this._options.uniforms.push(uniformName);
  47551. }
  47552. };
  47553. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47554. if (this._options.samplers.indexOf(name) === -1) {
  47555. this._options.samplers.push(name);
  47556. }
  47557. this._textures[name] = texture;
  47558. return this;
  47559. };
  47560. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47561. if (this._options.samplers.indexOf(name) === -1) {
  47562. this._options.samplers.push(name);
  47563. }
  47564. this._checkUniform(name);
  47565. this._textureArrays[name] = textures;
  47566. return this;
  47567. };
  47568. ShaderMaterial.prototype.setFloat = function (name, value) {
  47569. this._checkUniform(name);
  47570. this._floats[name] = value;
  47571. return this;
  47572. };
  47573. ShaderMaterial.prototype.setFloats = function (name, value) {
  47574. this._checkUniform(name);
  47575. this._floatsArrays[name] = value;
  47576. return this;
  47577. };
  47578. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47579. this._checkUniform(name);
  47580. this._colors3[name] = value;
  47581. return this;
  47582. };
  47583. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47584. this._checkUniform(name);
  47585. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47586. color.toArray(arr, arr.length);
  47587. return arr;
  47588. }, []);
  47589. return this;
  47590. };
  47591. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47592. this._checkUniform(name);
  47593. this._colors4[name] = value;
  47594. return this;
  47595. };
  47596. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47597. this._checkUniform(name);
  47598. this._vectors2[name] = value;
  47599. return this;
  47600. };
  47601. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47602. this._checkUniform(name);
  47603. this._vectors3[name] = value;
  47604. return this;
  47605. };
  47606. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47607. this._checkUniform(name);
  47608. this._vectors4[name] = value;
  47609. return this;
  47610. };
  47611. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47612. this._checkUniform(name);
  47613. this._matrices[name] = value;
  47614. return this;
  47615. };
  47616. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47617. this._checkUniform(name);
  47618. this._matrices3x3[name] = value;
  47619. return this;
  47620. };
  47621. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47622. this._checkUniform(name);
  47623. this._matrices2x2[name] = value;
  47624. return this;
  47625. };
  47626. ShaderMaterial.prototype.setArray2 = function (name, value) {
  47627. this._checkUniform(name);
  47628. this._vectors2Arrays[name] = value;
  47629. return this;
  47630. };
  47631. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47632. this._checkUniform(name);
  47633. this._vectors3Arrays[name] = value;
  47634. return this;
  47635. };
  47636. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47637. if (!mesh) {
  47638. return true;
  47639. }
  47640. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47641. return false;
  47642. }
  47643. return false;
  47644. };
  47645. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47646. var scene = this.getScene();
  47647. var engine = scene.getEngine();
  47648. if (!this.checkReadyOnEveryCall) {
  47649. if (this._renderId === scene.getRenderId()) {
  47650. if (this._checkCache(scene, mesh, useInstances)) {
  47651. return true;
  47652. }
  47653. }
  47654. }
  47655. // Instances
  47656. var defines = [];
  47657. var attribs = [];
  47658. var fallbacks = new BABYLON.EffectFallbacks();
  47659. if (useInstances) {
  47660. defines.push("#define INSTANCES");
  47661. }
  47662. for (var index = 0; index < this._options.defines.length; index++) {
  47663. defines.push(this._options.defines[index]);
  47664. }
  47665. for (var index = 0; index < this._options.attributes.length; index++) {
  47666. attribs.push(this._options.attributes[index]);
  47667. }
  47668. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47669. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47670. defines.push("#define VERTEXCOLOR");
  47671. }
  47672. // Bones
  47673. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47674. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47675. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47676. if (mesh.numBoneInfluencers > 4) {
  47677. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47678. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47679. }
  47680. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47681. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47682. fallbacks.addCPUSkinningFallback(0, mesh);
  47683. if (this._options.uniforms.indexOf("mBones") === -1) {
  47684. this._options.uniforms.push("mBones");
  47685. }
  47686. }
  47687. else {
  47688. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47689. }
  47690. // Textures
  47691. for (var name in this._textures) {
  47692. if (!this._textures[name].isReady()) {
  47693. return false;
  47694. }
  47695. }
  47696. // Alpha test
  47697. if (engine.getAlphaTesting()) {
  47698. defines.push("#define ALPHATEST");
  47699. }
  47700. var previousEffect = this._effect;
  47701. var join = defines.join("\n");
  47702. this._effect = engine.createEffect(this._shaderPath, {
  47703. attributes: attribs,
  47704. uniformsNames: this._options.uniforms,
  47705. uniformBuffersNames: this._options.uniformBuffers,
  47706. samplers: this._options.samplers,
  47707. defines: join,
  47708. fallbacks: fallbacks,
  47709. onCompiled: this.onCompiled,
  47710. onError: this.onError
  47711. }, engine);
  47712. if (!this._effect.isReady()) {
  47713. return false;
  47714. }
  47715. if (previousEffect !== this._effect) {
  47716. scene.resetCachedMaterial();
  47717. }
  47718. this._renderId = scene.getRenderId();
  47719. return true;
  47720. };
  47721. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47722. var scene = this.getScene();
  47723. if (!this._effect) {
  47724. return;
  47725. }
  47726. if (this._options.uniforms.indexOf("world") !== -1) {
  47727. this._effect.setMatrix("world", world);
  47728. }
  47729. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47730. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47731. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47732. }
  47733. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47734. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47735. }
  47736. };
  47737. ShaderMaterial.prototype.bind = function (world, mesh) {
  47738. // Std values
  47739. this.bindOnlyWorldMatrix(world);
  47740. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47741. if (this._options.uniforms.indexOf("view") !== -1) {
  47742. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47743. }
  47744. if (this._options.uniforms.indexOf("projection") !== -1) {
  47745. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47746. }
  47747. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47748. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47749. }
  47750. // Bones
  47751. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47752. var name;
  47753. // Texture
  47754. for (name in this._textures) {
  47755. this._effect.setTexture(name, this._textures[name]);
  47756. }
  47757. // Texture arrays
  47758. for (name in this._textureArrays) {
  47759. this._effect.setTextureArray(name, this._textureArrays[name]);
  47760. }
  47761. // Float
  47762. for (name in this._floats) {
  47763. this._effect.setFloat(name, this._floats[name]);
  47764. }
  47765. // Float s
  47766. for (name in this._floatsArrays) {
  47767. this._effect.setArray(name, this._floatsArrays[name]);
  47768. }
  47769. // Color3
  47770. for (name in this._colors3) {
  47771. this._effect.setColor3(name, this._colors3[name]);
  47772. }
  47773. for (name in this._colors3Arrays) {
  47774. this._effect.setArray3(name, this._colors3Arrays[name]);
  47775. }
  47776. // Color4
  47777. for (name in this._colors4) {
  47778. var color = this._colors4[name];
  47779. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47780. }
  47781. // Vector2
  47782. for (name in this._vectors2) {
  47783. this._effect.setVector2(name, this._vectors2[name]);
  47784. }
  47785. // Vector3
  47786. for (name in this._vectors3) {
  47787. this._effect.setVector3(name, this._vectors3[name]);
  47788. }
  47789. // Vector4
  47790. for (name in this._vectors4) {
  47791. this._effect.setVector4(name, this._vectors4[name]);
  47792. }
  47793. // Matrix
  47794. for (name in this._matrices) {
  47795. this._effect.setMatrix(name, this._matrices[name]);
  47796. }
  47797. // Matrix 3x3
  47798. for (name in this._matrices3x3) {
  47799. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47800. }
  47801. // Matrix 2x2
  47802. for (name in this._matrices2x2) {
  47803. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47804. }
  47805. // Vector2Array
  47806. for (name in this._vectors2Arrays) {
  47807. this._effect.setArray2(name, this._vectors2Arrays[name]);
  47808. }
  47809. // Vector3Array
  47810. for (name in this._vectors3Arrays) {
  47811. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47812. }
  47813. }
  47814. this._afterBind(mesh);
  47815. };
  47816. ShaderMaterial.prototype.getActiveTextures = function () {
  47817. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47818. for (var name in this._textures) {
  47819. activeTextures.push(this._textures[name]);
  47820. }
  47821. for (var name in this._textureArrays) {
  47822. var array = this._textureArrays[name];
  47823. for (var index = 0; index < array.length; index++) {
  47824. activeTextures.push(array[index]);
  47825. }
  47826. }
  47827. return activeTextures;
  47828. };
  47829. ShaderMaterial.prototype.hasTexture = function (texture) {
  47830. if (_super.prototype.hasTexture.call(this, texture)) {
  47831. return true;
  47832. }
  47833. for (var name in this._textures) {
  47834. if (this._textures[name] === texture) {
  47835. return true;
  47836. }
  47837. }
  47838. for (var name in this._textureArrays) {
  47839. var array = this._textureArrays[name];
  47840. for (var index = 0; index < array.length; index++) {
  47841. if (array[index] === texture) {
  47842. return true;
  47843. }
  47844. }
  47845. }
  47846. return false;
  47847. };
  47848. ShaderMaterial.prototype.clone = function (name) {
  47849. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47850. return newShaderMaterial;
  47851. };
  47852. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47853. if (forceDisposeTextures) {
  47854. var name;
  47855. for (name in this._textures) {
  47856. this._textures[name].dispose();
  47857. }
  47858. for (name in this._textureArrays) {
  47859. var array = this._textureArrays[name];
  47860. for (var index = 0; index < array.length; index++) {
  47861. array[index].dispose();
  47862. }
  47863. }
  47864. }
  47865. this._textures = {};
  47866. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47867. };
  47868. ShaderMaterial.prototype.serialize = function () {
  47869. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47870. serializationObject.customType = "BABYLON.ShaderMaterial";
  47871. serializationObject.options = this._options;
  47872. serializationObject.shaderPath = this._shaderPath;
  47873. var name;
  47874. // Texture
  47875. serializationObject.textures = {};
  47876. for (name in this._textures) {
  47877. serializationObject.textures[name] = this._textures[name].serialize();
  47878. }
  47879. // Texture arrays
  47880. serializationObject.textureArrays = {};
  47881. for (name in this._textureArrays) {
  47882. serializationObject.textureArrays[name] = [];
  47883. var array = this._textureArrays[name];
  47884. for (var index = 0; index < array.length; index++) {
  47885. serializationObject.textureArrays[name].push(array[index].serialize());
  47886. }
  47887. }
  47888. // Float
  47889. serializationObject.floats = {};
  47890. for (name in this._floats) {
  47891. serializationObject.floats[name] = this._floats[name];
  47892. }
  47893. // Float s
  47894. serializationObject.FloatArrays = {};
  47895. for (name in this._floatsArrays) {
  47896. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47897. }
  47898. // Color3
  47899. serializationObject.colors3 = {};
  47900. for (name in this._colors3) {
  47901. serializationObject.colors3[name] = this._colors3[name].asArray();
  47902. }
  47903. // Color3 array
  47904. serializationObject.colors3Arrays = {};
  47905. for (name in this._colors3Arrays) {
  47906. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47907. }
  47908. // Color4
  47909. serializationObject.colors4 = {};
  47910. for (name in this._colors4) {
  47911. serializationObject.colors4[name] = this._colors4[name].asArray();
  47912. }
  47913. // Vector2
  47914. serializationObject.vectors2 = {};
  47915. for (name in this._vectors2) {
  47916. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47917. }
  47918. // Vector3
  47919. serializationObject.vectors3 = {};
  47920. for (name in this._vectors3) {
  47921. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47922. }
  47923. // Vector4
  47924. serializationObject.vectors4 = {};
  47925. for (name in this._vectors4) {
  47926. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47927. }
  47928. // Matrix
  47929. serializationObject.matrices = {};
  47930. for (name in this._matrices) {
  47931. serializationObject.matrices[name] = this._matrices[name].asArray();
  47932. }
  47933. // Matrix 3x3
  47934. serializationObject.matrices3x3 = {};
  47935. for (name in this._matrices3x3) {
  47936. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47937. }
  47938. // Matrix 2x2
  47939. serializationObject.matrices2x2 = {};
  47940. for (name in this._matrices2x2) {
  47941. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47942. }
  47943. // Vector2Array
  47944. serializationObject.vectors2Arrays = {};
  47945. for (name in this._vectors2Arrays) {
  47946. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  47947. }
  47948. // Vector3Array
  47949. serializationObject.vectors3Arrays = {};
  47950. for (name in this._vectors3Arrays) {
  47951. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47952. }
  47953. return serializationObject;
  47954. };
  47955. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47956. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47957. var name;
  47958. // Texture
  47959. for (name in source.textures) {
  47960. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47961. }
  47962. // Texture arrays
  47963. for (name in source.textureArrays) {
  47964. var array = source.textureArrays[name];
  47965. var textureArray = new Array();
  47966. for (var index = 0; index < array.length; index++) {
  47967. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47968. }
  47969. material.setTextureArray(name, textureArray);
  47970. }
  47971. // Float
  47972. for (name in source.floats) {
  47973. material.setFloat(name, source.floats[name]);
  47974. }
  47975. // Float s
  47976. for (name in source.floatsArrays) {
  47977. material.setFloats(name, source.floatsArrays[name]);
  47978. }
  47979. // Color3
  47980. for (name in source.colors3) {
  47981. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47982. }
  47983. // Color3 arrays
  47984. for (name in source.colors3Arrays) {
  47985. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47986. if (i % 3 === 0) {
  47987. arr.push([num]);
  47988. }
  47989. else {
  47990. arr[arr.length - 1].push(num);
  47991. }
  47992. return arr;
  47993. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47994. material.setColor3Array(name, colors);
  47995. }
  47996. // Color4
  47997. for (name in source.colors4) {
  47998. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47999. }
  48000. // Vector2
  48001. for (name in source.vectors2) {
  48002. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48003. }
  48004. // Vector3
  48005. for (name in source.vectors3) {
  48006. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48007. }
  48008. // Vector4
  48009. for (name in source.vectors4) {
  48010. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48011. }
  48012. // Matrix
  48013. for (name in source.matrices) {
  48014. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48015. }
  48016. // Matrix 3x3
  48017. for (name in source.matrices3x3) {
  48018. material.setMatrix3x3(name, source.matrices3x3[name]);
  48019. }
  48020. // Matrix 2x2
  48021. for (name in source.matrices2x2) {
  48022. material.setMatrix2x2(name, source.matrices2x2[name]);
  48023. }
  48024. // Vector2Array
  48025. for (name in source.vectors2Arrays) {
  48026. material.setArray2(name, source.vectors2Arrays[name]);
  48027. }
  48028. // Vector3Array
  48029. for (name in source.vectors3Arrays) {
  48030. material.setArray3(name, source.vectors3Arrays[name]);
  48031. }
  48032. return material;
  48033. };
  48034. return ShaderMaterial;
  48035. }(BABYLON.Material));
  48036. BABYLON.ShaderMaterial = ShaderMaterial;
  48037. })(BABYLON || (BABYLON = {}));
  48038. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48039. var BABYLON;
  48040. (function (BABYLON) {
  48041. var MeshBuilder = /** @class */ (function () {
  48042. function MeshBuilder() {
  48043. }
  48044. MeshBuilder.updateSideOrientation = function (orientation) {
  48045. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  48046. return BABYLON.Mesh.DOUBLESIDE;
  48047. }
  48048. if (orientation === undefined || orientation === null) {
  48049. return BABYLON.Mesh.FRONTSIDE;
  48050. }
  48051. return orientation;
  48052. };
  48053. /**
  48054. * Creates a box mesh.
  48055. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  48056. * The parameter `size` sets the size (float) of each box side (default 1).
  48057. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  48058. * 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).
  48059. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48061. * 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).
  48062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48064. */
  48065. MeshBuilder.CreateBox = function (name, options, scene) {
  48066. if (scene === void 0) { scene = null; }
  48067. var box = new BABYLON.Mesh(name, scene);
  48068. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48069. box._originalBuilderSideOrientation = options.sideOrientation;
  48070. var vertexData = BABYLON.VertexData.CreateBox(options);
  48071. vertexData.applyToMesh(box, options.updatable);
  48072. return box;
  48073. };
  48074. /**
  48075. * Creates a sphere mesh.
  48076. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  48077. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  48078. * 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`).
  48079. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  48080. * 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
  48081. * 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).
  48082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48083. * 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).
  48084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48086. */
  48087. MeshBuilder.CreateSphere = function (name, options, scene) {
  48088. var sphere = new BABYLON.Mesh(name, scene);
  48089. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48090. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48091. var vertexData = BABYLON.VertexData.CreateSphere(options);
  48092. vertexData.applyToMesh(sphere, options.updatable);
  48093. return sphere;
  48094. };
  48095. /**
  48096. * Creates a plane polygonal mesh. By default, this is a disc.
  48097. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  48098. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  48099. * 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.
  48100. * 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
  48101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48102. * 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).
  48103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48105. */
  48106. MeshBuilder.CreateDisc = function (name, options, scene) {
  48107. if (scene === void 0) { scene = null; }
  48108. var disc = new BABYLON.Mesh(name, scene);
  48109. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48110. disc._originalBuilderSideOrientation = options.sideOrientation;
  48111. var vertexData = BABYLON.VertexData.CreateDisc(options);
  48112. vertexData.applyToMesh(disc, options.updatable);
  48113. return disc;
  48114. };
  48115. /**
  48116. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  48117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  48118. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  48119. * 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`).
  48120. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  48121. * 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.
  48122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48123. * 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).
  48124. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48126. */
  48127. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  48128. var sphere = new BABYLON.Mesh(name, scene);
  48129. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48130. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48131. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  48132. vertexData.applyToMesh(sphere, options.updatable);
  48133. return sphere;
  48134. };
  48135. ;
  48136. /**
  48137. * Creates a ribbon mesh.
  48138. * 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.
  48139. *
  48140. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  48141. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  48142. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  48143. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  48144. * 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.
  48145. * 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.
  48146. * 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
  48147. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48148. * 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).
  48149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48150. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48151. * 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.
  48152. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  48153. * 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
  48154. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  48155. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  48156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48157. */
  48158. MeshBuilder.CreateRibbon = function (name, options, scene) {
  48159. if (scene === void 0) { scene = null; }
  48160. var pathArray = options.pathArray;
  48161. var closeArray = options.closeArray;
  48162. var closePath = options.closePath;
  48163. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48164. var instance = options.instance;
  48165. var updatable = options.updatable;
  48166. if (instance) {
  48167. // positionFunction : ribbon case
  48168. // only pathArray and sideOrientation parameters are taken into account for positions update
  48169. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  48170. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  48171. var positionFunction = function (positions) {
  48172. var minlg = pathArray[0].length;
  48173. var i = 0;
  48174. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  48175. for (var si = 1; si <= ns; si++) {
  48176. for (var p = 0; p < pathArray.length; p++) {
  48177. var path = pathArray[p];
  48178. var l = path.length;
  48179. minlg = (minlg < l) ? minlg : l;
  48180. var j = 0;
  48181. while (j < minlg) {
  48182. positions[i] = path[j].x;
  48183. positions[i + 1] = path[j].y;
  48184. positions[i + 2] = path[j].z;
  48185. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  48186. BABYLON.Tmp.Vector3[0].x = path[j].x;
  48187. }
  48188. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  48189. BABYLON.Tmp.Vector3[1].x = path[j].x;
  48190. }
  48191. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  48192. BABYLON.Tmp.Vector3[0].y = path[j].y;
  48193. }
  48194. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  48195. BABYLON.Tmp.Vector3[1].y = path[j].y;
  48196. }
  48197. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  48198. BABYLON.Tmp.Vector3[0].z = path[j].z;
  48199. }
  48200. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  48201. BABYLON.Tmp.Vector3[1].z = path[j].z;
  48202. }
  48203. j++;
  48204. i += 3;
  48205. }
  48206. if (instance._closePath) {
  48207. positions[i] = path[0].x;
  48208. positions[i + 1] = path[0].y;
  48209. positions[i + 2] = path[0].z;
  48210. i += 3;
  48211. }
  48212. }
  48213. }
  48214. };
  48215. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48216. positionFunction(positions);
  48217. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  48218. instance._boundingInfo.update(instance._worldMatrix);
  48219. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48220. if (options.colors) {
  48221. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48222. for (var c = 0; c < options.colors.length; c++) {
  48223. colors[c * 4] = options.colors[c].r;
  48224. colors[c * 4 + 1] = options.colors[c].g;
  48225. colors[c * 4 + 2] = options.colors[c].b;
  48226. colors[c * 4 + 3] = options.colors[c].a;
  48227. }
  48228. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  48229. }
  48230. if (options.uvs) {
  48231. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48232. for (var i = 0; i < options.uvs.length; i++) {
  48233. uvs[i * 2] = options.uvs[i].x;
  48234. uvs[i * 2 + 1] = options.uvs[i].y;
  48235. }
  48236. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  48237. }
  48238. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  48239. var indices = instance.getIndices();
  48240. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48241. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  48242. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  48243. if (instance._closePath) {
  48244. var indexFirst = 0;
  48245. var indexLast = 0;
  48246. for (var p = 0; p < pathArray.length; p++) {
  48247. indexFirst = instance._idx[p] * 3;
  48248. if (p + 1 < pathArray.length) {
  48249. indexLast = (instance._idx[p + 1] - 1) * 3;
  48250. }
  48251. else {
  48252. indexLast = normals.length - 3;
  48253. }
  48254. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  48255. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  48256. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  48257. normals[indexLast] = normals[indexFirst];
  48258. normals[indexLast + 1] = normals[indexFirst + 1];
  48259. normals[indexLast + 2] = normals[indexFirst + 2];
  48260. }
  48261. }
  48262. if (!(instance.areNormalsFrozen)) {
  48263. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  48264. }
  48265. }
  48266. return instance;
  48267. }
  48268. else {
  48269. var ribbon = new BABYLON.Mesh(name, scene);
  48270. ribbon._originalBuilderSideOrientation = sideOrientation;
  48271. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  48272. if (closePath) {
  48273. ribbon._idx = vertexData._idx;
  48274. }
  48275. ribbon._closePath = closePath;
  48276. ribbon._closeArray = closeArray;
  48277. vertexData.applyToMesh(ribbon, updatable);
  48278. return ribbon;
  48279. }
  48280. };
  48281. /**
  48282. * Creates a cylinder or a cone mesh.
  48283. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  48284. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  48285. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  48286. * 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.
  48287. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  48288. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  48289. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  48290. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  48291. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  48292. * 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).
  48293. * 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
  48294. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  48295. * 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
  48296. * 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.
  48297. * If `enclose` is false, a ring surface is one element.
  48298. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  48299. * 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
  48300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48301. * 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).
  48302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48304. */
  48305. MeshBuilder.CreateCylinder = function (name, options, scene) {
  48306. var cylinder = new BABYLON.Mesh(name, scene);
  48307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48308. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  48309. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  48310. vertexData.applyToMesh(cylinder, options.updatable);
  48311. return cylinder;
  48312. };
  48313. /**
  48314. * Creates a torus mesh.
  48315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  48316. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  48317. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  48318. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  48319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48320. * 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).
  48321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48323. */
  48324. MeshBuilder.CreateTorus = function (name, options, scene) {
  48325. var torus = new BABYLON.Mesh(name, scene);
  48326. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48327. torus._originalBuilderSideOrientation = options.sideOrientation;
  48328. var vertexData = BABYLON.VertexData.CreateTorus(options);
  48329. vertexData.applyToMesh(torus, options.updatable);
  48330. return torus;
  48331. };
  48332. /**
  48333. * Creates a torus knot mesh.
  48334. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  48335. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  48336. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  48337. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  48338. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  48339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48340. * 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).
  48341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48342. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48343. */
  48344. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  48345. var torusKnot = new BABYLON.Mesh(name, scene);
  48346. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48347. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  48348. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  48349. vertexData.applyToMesh(torusKnot, options.updatable);
  48350. return torusKnot;
  48351. };
  48352. /**
  48353. * Creates a line system mesh.
  48354. * A line system is a pool of many lines gathered in a single mesh.
  48355. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  48356. * 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.
  48357. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  48358. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  48359. * 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
  48360. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  48361. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  48362. * 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
  48363. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  48364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48365. */
  48366. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  48367. var instance = options.instance;
  48368. var lines = options.lines;
  48369. var colors = options.colors;
  48370. if (instance) {
  48371. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48372. var vertexColor;
  48373. var lineColors;
  48374. if (colors) {
  48375. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48376. }
  48377. var i = 0;
  48378. var c = 0;
  48379. for (var l = 0; l < lines.length; l++) {
  48380. var points = lines[l];
  48381. for (var p = 0; p < points.length; p++) {
  48382. positions[i] = points[p].x;
  48383. positions[i + 1] = points[p].y;
  48384. positions[i + 2] = points[p].z;
  48385. if (colors && vertexColor) {
  48386. lineColors = colors[l];
  48387. vertexColor[c] = lineColors[p].r;
  48388. vertexColor[c + 1] = lineColors[p].g;
  48389. vertexColor[c + 2] = lineColors[p].b;
  48390. vertexColor[c + 3] = lineColors[p].a;
  48391. c += 4;
  48392. }
  48393. i += 3;
  48394. }
  48395. }
  48396. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48397. if (colors && vertexColor) {
  48398. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  48399. }
  48400. return instance;
  48401. }
  48402. // line system creation
  48403. var useVertexColor = (colors) ? true : false;
  48404. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  48405. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  48406. vertexData.applyToMesh(lineSystem, options.updatable);
  48407. return lineSystem;
  48408. };
  48409. /**
  48410. * Creates a line mesh.
  48411. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  48412. * 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.
  48413. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48414. * The parameter `points` is an array successive Vector3.
  48415. * 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
  48416. * The optional parameter `colors` is an array of successive Color4, one per line point.
  48417. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  48418. * When updating an instance, remember that only point positions can change, not the number of points.
  48419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48420. */
  48421. MeshBuilder.CreateLines = function (name, options, scene) {
  48422. if (scene === void 0) { scene = null; }
  48423. var colors = (options.colors) ? [options.colors] : null;
  48424. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  48425. return lines;
  48426. };
  48427. /**
  48428. * Creates a dashed line mesh.
  48429. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  48430. * 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.
  48431. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  48432. * The parameter `points` is an array successive Vector3.
  48433. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  48434. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  48435. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  48436. * 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
  48437. * When updating an instance, remember that only point positions can change, not the number of points.
  48438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48439. */
  48440. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  48441. if (scene === void 0) { scene = null; }
  48442. var points = options.points;
  48443. var instance = options.instance;
  48444. var gapSize = options.gapSize || 1;
  48445. var dashSize = options.dashSize || 3;
  48446. if (instance) {
  48447. var positionFunction = function (positions) {
  48448. var curvect = BABYLON.Vector3.Zero();
  48449. var nbSeg = positions.length / 6;
  48450. var lg = 0;
  48451. var nb = 0;
  48452. var shft = 0;
  48453. var dashshft = 0;
  48454. var curshft = 0;
  48455. var p = 0;
  48456. var i = 0;
  48457. var j = 0;
  48458. for (i = 0; i < points.length - 1; i++) {
  48459. points[i + 1].subtractToRef(points[i], curvect);
  48460. lg += curvect.length();
  48461. }
  48462. shft = lg / nbSeg;
  48463. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  48464. for (i = 0; i < points.length - 1; i++) {
  48465. points[i + 1].subtractToRef(points[i], curvect);
  48466. nb = Math.floor(curvect.length() / shft);
  48467. curvect.normalize();
  48468. j = 0;
  48469. while (j < nb && p < positions.length) {
  48470. curshft = shft * j;
  48471. positions[p] = points[i].x + curshft * curvect.x;
  48472. positions[p + 1] = points[i].y + curshft * curvect.y;
  48473. positions[p + 2] = points[i].z + curshft * curvect.z;
  48474. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  48475. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  48476. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  48477. p += 6;
  48478. j++;
  48479. }
  48480. }
  48481. while (p < positions.length) {
  48482. positions[p] = points[i].x;
  48483. positions[p + 1] = points[i].y;
  48484. positions[p + 2] = points[i].z;
  48485. p += 3;
  48486. }
  48487. };
  48488. instance.updateMeshPositions(positionFunction, false);
  48489. return instance;
  48490. }
  48491. // dashed lines creation
  48492. var dashedLines = new BABYLON.LinesMesh(name, scene);
  48493. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  48494. vertexData.applyToMesh(dashedLines, options.updatable);
  48495. dashedLines.dashSize = dashSize;
  48496. dashedLines.gapSize = gapSize;
  48497. return dashedLines;
  48498. };
  48499. /**
  48500. * Creates an extruded shape mesh.
  48501. * 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.
  48502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48503. *
  48504. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48505. * 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
  48506. * extruded along the Z axis.
  48507. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48508. * 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.
  48509. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48510. * 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
  48511. * 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
  48512. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48514. * 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).
  48515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48516. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48518. */
  48519. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48520. if (scene === void 0) { scene = null; }
  48521. var path = options.path;
  48522. var shape = options.shape;
  48523. var scale = options.scale || 1;
  48524. var rotation = options.rotation || 0;
  48525. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48526. var updatable = options.updatable;
  48527. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48528. var instance = options.instance || null;
  48529. var invertUV = options.invertUV || false;
  48530. 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);
  48531. };
  48532. /**
  48533. * Creates an custom extruded shape mesh.
  48534. * 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.
  48535. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48536. *
  48537. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48538. * 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
  48539. * extruded along the Z axis.
  48540. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48541. * 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
  48542. * and the distance of this point from the begining of the path :
  48543. * ```javascript
  48544. * var rotationFunction = function(i, distance) {
  48545. * // do things
  48546. * return rotationValue; }
  48547. * ```
  48548. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48549. * 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
  48550. * and the distance of this point from the begining of the path :
  48551. * ```javascript
  48552. * var scaleFunction = function(i, distance) {
  48553. * // do things
  48554. * return scaleValue;}
  48555. * ```
  48556. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48557. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48558. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48559. * 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
  48560. * 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
  48561. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48563. * 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).
  48564. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48565. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48567. */
  48568. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48569. var path = options.path;
  48570. var shape = options.shape;
  48571. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48572. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48573. var ribbonCloseArray = options.ribbonCloseArray || false;
  48574. var ribbonClosePath = options.ribbonClosePath || false;
  48575. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48576. var updatable = options.updatable;
  48577. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48578. var instance = options.instance;
  48579. var invertUV = options.invertUV || false;
  48580. 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);
  48581. };
  48582. /**
  48583. * Creates lathe mesh.
  48584. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48585. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48586. *
  48587. * 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
  48588. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48589. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48590. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48591. * 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.
  48592. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48593. * 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
  48594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48595. * 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).
  48596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48597. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48599. */
  48600. MeshBuilder.CreateLathe = function (name, options, scene) {
  48601. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48602. var closed = (options.closed === undefined) ? true : options.closed;
  48603. var shape = options.shape;
  48604. var radius = options.radius || 1;
  48605. var tessellation = options.tessellation || 64;
  48606. var updatable = options.updatable;
  48607. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48608. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48609. var pi2 = Math.PI * 2;
  48610. var paths = new Array();
  48611. var invertUV = options.invertUV || false;
  48612. var i = 0;
  48613. var p = 0;
  48614. var step = pi2 / tessellation * arc;
  48615. var rotated;
  48616. var path = new Array();
  48617. ;
  48618. for (i = 0; i <= tessellation; i++) {
  48619. var path = [];
  48620. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48621. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48622. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48623. }
  48624. for (p = 0; p < shape.length; p++) {
  48625. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48626. path.push(rotated);
  48627. }
  48628. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48629. 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));
  48630. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48631. }
  48632. paths.push(path);
  48633. }
  48634. // lathe ribbon
  48635. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48636. return lathe;
  48637. };
  48638. /**
  48639. * Creates a plane mesh.
  48640. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48641. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48642. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48643. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48645. * 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).
  48646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48648. */
  48649. MeshBuilder.CreatePlane = function (name, options, scene) {
  48650. var plane = new BABYLON.Mesh(name, scene);
  48651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48652. plane._originalBuilderSideOrientation = options.sideOrientation;
  48653. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48654. vertexData.applyToMesh(plane, options.updatable);
  48655. if (options.sourcePlane) {
  48656. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48657. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48658. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48659. plane.rotate(vectorProduct, product);
  48660. }
  48661. return plane;
  48662. };
  48663. /**
  48664. * Creates a ground mesh.
  48665. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48666. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48667. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48669. */
  48670. MeshBuilder.CreateGround = function (name, options, scene) {
  48671. var ground = new BABYLON.GroundMesh(name, scene);
  48672. ground._setReady(false);
  48673. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48674. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48675. ground._width = options.width || 1;
  48676. ground._height = options.height || 1;
  48677. ground._maxX = ground._width / 2;
  48678. ground._maxZ = ground._height / 2;
  48679. ground._minX = -ground._maxX;
  48680. ground._minZ = -ground._maxZ;
  48681. var vertexData = BABYLON.VertexData.CreateGround(options);
  48682. vertexData.applyToMesh(ground, options.updatable);
  48683. ground._setReady(true);
  48684. return ground;
  48685. };
  48686. /**
  48687. * Creates a tiled ground mesh.
  48688. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48689. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48690. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48691. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48692. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48693. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48694. * numbers of subdivisions on the ground width and height of each tile.
  48695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48696. */
  48697. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48698. var tiledGround = new BABYLON.Mesh(name, scene);
  48699. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48700. vertexData.applyToMesh(tiledGround, options.updatable);
  48701. return tiledGround;
  48702. };
  48703. /**
  48704. * Creates a ground mesh from a height map.
  48705. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48706. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48707. * The parameter `url` sets the URL of the height map image resource.
  48708. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48709. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48710. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48711. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48712. * 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.
  48713. * 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).
  48714. * This function is passed the newly built mesh :
  48715. * ```javascript
  48716. * function(mesh) { // do things
  48717. * return; }
  48718. * ```
  48719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48720. */
  48721. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48722. var width = options.width || 10.0;
  48723. var height = options.height || 10.0;
  48724. var subdivisions = options.subdivisions || 1 | 0;
  48725. var minHeight = options.minHeight || 0.0;
  48726. var maxHeight = options.maxHeight || 1.0;
  48727. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48728. var updatable = options.updatable;
  48729. var onReady = options.onReady;
  48730. var ground = new BABYLON.GroundMesh(name, scene);
  48731. ground._subdivisionsX = subdivisions;
  48732. ground._subdivisionsY = subdivisions;
  48733. ground._width = width;
  48734. ground._height = height;
  48735. ground._maxX = ground._width / 2.0;
  48736. ground._maxZ = ground._height / 2.0;
  48737. ground._minX = -ground._maxX;
  48738. ground._minZ = -ground._maxZ;
  48739. ground._setReady(false);
  48740. var onload = function (img) {
  48741. // Getting height map data
  48742. var canvas = document.createElement("canvas");
  48743. var context = canvas.getContext("2d");
  48744. if (!context) {
  48745. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48746. }
  48747. var bufferWidth = img.width;
  48748. var bufferHeight = img.height;
  48749. canvas.width = bufferWidth;
  48750. canvas.height = bufferHeight;
  48751. context.drawImage(img, 0, 0);
  48752. // Create VertexData from map data
  48753. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48754. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48755. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48756. width: width, height: height,
  48757. subdivisions: subdivisions,
  48758. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48759. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48760. });
  48761. vertexData.applyToMesh(ground, updatable);
  48762. ground._setReady(true);
  48763. //execute ready callback, if set
  48764. if (onReady) {
  48765. onReady(ground);
  48766. }
  48767. };
  48768. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48769. return ground;
  48770. };
  48771. /**
  48772. * Creates a polygon mesh.
  48773. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48774. * 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.
  48775. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48777. * 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).
  48778. * Remember you can only change the shape positions, not their number when updating a polygon.
  48779. */
  48780. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48781. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48782. var shape = options.shape;
  48783. var holes = options.holes || [];
  48784. var depth = options.depth || 0;
  48785. var contours = [];
  48786. var hole = [];
  48787. for (var i = 0; i < shape.length; i++) {
  48788. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48789. }
  48790. var epsilon = 0.00000001;
  48791. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48792. contours.pop();
  48793. }
  48794. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48795. for (var hNb = 0; hNb < holes.length; hNb++) {
  48796. hole = [];
  48797. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48798. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48799. }
  48800. polygonTriangulation.addHole(hole);
  48801. }
  48802. var polygon = polygonTriangulation.build(options.updatable, depth);
  48803. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48804. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48805. vertexData.applyToMesh(polygon, options.updatable);
  48806. return polygon;
  48807. };
  48808. ;
  48809. /**
  48810. * Creates an extruded polygon mesh, with depth in the Y direction.
  48811. * 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).
  48812. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48813. */
  48814. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48815. return MeshBuilder.CreatePolygon(name, options, scene);
  48816. };
  48817. ;
  48818. /**
  48819. * Creates a tube mesh.
  48820. * 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.
  48821. *
  48822. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48823. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48824. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48825. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48826. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48827. * 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.
  48828. * It must return a radius value (positive float) :
  48829. * ```javascript
  48830. * var radiusFunction = function(i, distance) {
  48831. * // do things
  48832. * return radius; }
  48833. * ```
  48834. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48835. * 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
  48836. * 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
  48837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48838. * 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).
  48839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48840. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48841. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48842. */
  48843. MeshBuilder.CreateTube = function (name, options, scene) {
  48844. var path = options.path;
  48845. var instance = options.instance;
  48846. var radius = 1.0;
  48847. if (instance) {
  48848. radius = instance.radius;
  48849. }
  48850. if (options.radius !== undefined) {
  48851. radius = options.radius;
  48852. }
  48853. ;
  48854. var tessellation = options.tessellation || 64 | 0;
  48855. var radiusFunction = options.radiusFunction || null;
  48856. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48857. var invertUV = options.invertUV || false;
  48858. var updatable = options.updatable;
  48859. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48860. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48861. // tube geometry
  48862. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48863. var tangents = path3D.getTangents();
  48864. var normals = path3D.getNormals();
  48865. var distances = path3D.getDistances();
  48866. var pi2 = Math.PI * 2;
  48867. var step = pi2 / tessellation * arc;
  48868. var returnRadius = function () { return radius; };
  48869. var radiusFunctionFinal = radiusFunction || returnRadius;
  48870. var circlePath;
  48871. var rad;
  48872. var normal;
  48873. var rotated;
  48874. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48875. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48876. for (var i = 0; i < path.length; i++) {
  48877. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48878. circlePath = Array(); // current circle array
  48879. normal = normals[i]; // current normal
  48880. for (var t = 0; t < tessellation; t++) {
  48881. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48882. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48883. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48884. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48885. circlePath[t] = rotated;
  48886. }
  48887. circlePaths[index] = circlePath;
  48888. index++;
  48889. }
  48890. // cap
  48891. var capPath = function (nbPoints, pathIndex) {
  48892. var pointCap = Array();
  48893. for (var i = 0; i < nbPoints; i++) {
  48894. pointCap.push(path[pathIndex]);
  48895. }
  48896. return pointCap;
  48897. };
  48898. switch (cap) {
  48899. case BABYLON.Mesh.NO_CAP:
  48900. break;
  48901. case BABYLON.Mesh.CAP_START:
  48902. circlePaths[0] = capPath(tessellation, 0);
  48903. circlePaths[1] = circlePaths[2].slice(0);
  48904. break;
  48905. case BABYLON.Mesh.CAP_END:
  48906. circlePaths[index] = circlePaths[index - 1].slice(0);
  48907. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48908. break;
  48909. case BABYLON.Mesh.CAP_ALL:
  48910. circlePaths[0] = capPath(tessellation, 0);
  48911. circlePaths[1] = circlePaths[2].slice(0);
  48912. circlePaths[index] = circlePaths[index - 1].slice(0);
  48913. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48914. break;
  48915. default:
  48916. break;
  48917. }
  48918. return circlePaths;
  48919. };
  48920. var path3D;
  48921. var pathArray;
  48922. if (instance) {
  48923. var arc = options.arc || instance.arc;
  48924. path3D = (instance.path3D).update(path);
  48925. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48926. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48927. instance.path3D = path3D;
  48928. instance.pathArray = pathArray;
  48929. instance.arc = arc;
  48930. instance.radius = radius;
  48931. return instance;
  48932. }
  48933. // tube creation
  48934. path3D = new BABYLON.Path3D(path);
  48935. var newPathArray = new Array();
  48936. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48937. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48938. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48939. tube.pathArray = pathArray;
  48940. tube.path3D = path3D;
  48941. tube.tessellation = tessellation;
  48942. tube.cap = cap;
  48943. tube.arc = options.arc;
  48944. tube.radius = radius;
  48945. return tube;
  48946. };
  48947. /**
  48948. * Creates a polyhedron mesh.
  48949. *
  48950. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48951. * 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
  48952. * to choose the wanted type.
  48953. * The parameter `size` (positive float, default 1) sets the polygon size.
  48954. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48955. * 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`.
  48956. * 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
  48957. * 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)`).
  48958. * 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
  48959. * 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.
  48960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48961. * 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).
  48962. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48964. */
  48965. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48966. var polyhedron = new BABYLON.Mesh(name, scene);
  48967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48968. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48969. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48970. vertexData.applyToMesh(polyhedron, options.updatable);
  48971. return polyhedron;
  48972. };
  48973. /**
  48974. * Creates a decal mesh.
  48975. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48976. * 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.
  48977. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48978. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48979. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48980. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48981. */
  48982. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48983. var indices = sourceMesh.getIndices();
  48984. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48985. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48986. var position = options.position || BABYLON.Vector3.Zero();
  48987. var normal = options.normal || BABYLON.Vector3.Up();
  48988. var size = options.size || BABYLON.Vector3.One();
  48989. var angle = options.angle || 0;
  48990. // Getting correct rotation
  48991. if (!normal) {
  48992. var target = new BABYLON.Vector3(0, 0, 1);
  48993. var camera = sourceMesh.getScene().activeCamera;
  48994. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48995. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48996. }
  48997. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48998. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48999. var pitch = Math.atan2(normal.y, len);
  49000. // Matrix
  49001. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  49002. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  49003. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  49004. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  49005. var vertexData = new BABYLON.VertexData();
  49006. vertexData.indices = [];
  49007. vertexData.positions = [];
  49008. vertexData.normals = [];
  49009. vertexData.uvs = [];
  49010. var currentVertexDataIndex = 0;
  49011. var extractDecalVector3 = function (indexId) {
  49012. var result = new BABYLON.PositionNormalVertex();
  49013. if (!indices || !positions || !normals) {
  49014. return result;
  49015. }
  49016. var vertexId = indices[indexId];
  49017. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  49018. // Send vector to decal local world
  49019. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  49020. // Get normal
  49021. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  49022. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  49023. return result;
  49024. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  49025. var clip = function (vertices, axis) {
  49026. if (vertices.length === 0) {
  49027. return vertices;
  49028. }
  49029. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  49030. var clipVertices = function (v0, v1) {
  49031. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  49032. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  49033. };
  49034. var result = new Array();
  49035. for (var index = 0; index < vertices.length; index += 3) {
  49036. var v1Out;
  49037. var v2Out;
  49038. var v3Out;
  49039. var total = 0;
  49040. var nV1 = null;
  49041. var nV2 = null;
  49042. var nV3 = null;
  49043. var nV4 = null;
  49044. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  49045. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  49046. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  49047. v1Out = d1 > 0;
  49048. v2Out = d2 > 0;
  49049. v3Out = d3 > 0;
  49050. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  49051. switch (total) {
  49052. case 0:
  49053. result.push(vertices[index]);
  49054. result.push(vertices[index + 1]);
  49055. result.push(vertices[index + 2]);
  49056. break;
  49057. case 1:
  49058. if (v1Out) {
  49059. nV1 = vertices[index + 1];
  49060. nV2 = vertices[index + 2];
  49061. nV3 = clipVertices(vertices[index], nV1);
  49062. nV4 = clipVertices(vertices[index], nV2);
  49063. }
  49064. if (v2Out) {
  49065. nV1 = vertices[index];
  49066. nV2 = vertices[index + 2];
  49067. nV3 = clipVertices(vertices[index + 1], nV1);
  49068. nV4 = clipVertices(vertices[index + 1], nV2);
  49069. result.push(nV3);
  49070. result.push(nV2.clone());
  49071. result.push(nV1.clone());
  49072. result.push(nV2.clone());
  49073. result.push(nV3.clone());
  49074. result.push(nV4);
  49075. break;
  49076. }
  49077. if (v3Out) {
  49078. nV1 = vertices[index];
  49079. nV2 = vertices[index + 1];
  49080. nV3 = clipVertices(vertices[index + 2], nV1);
  49081. nV4 = clipVertices(vertices[index + 2], nV2);
  49082. }
  49083. if (nV1 && nV2 && nV3 && nV4) {
  49084. result.push(nV1.clone());
  49085. result.push(nV2.clone());
  49086. result.push(nV3);
  49087. result.push(nV4);
  49088. result.push(nV3.clone());
  49089. result.push(nV2.clone());
  49090. }
  49091. break;
  49092. case 2:
  49093. if (!v1Out) {
  49094. nV1 = vertices[index].clone();
  49095. nV2 = clipVertices(nV1, vertices[index + 1]);
  49096. nV3 = clipVertices(nV1, vertices[index + 2]);
  49097. result.push(nV1);
  49098. result.push(nV2);
  49099. result.push(nV3);
  49100. }
  49101. if (!v2Out) {
  49102. nV1 = vertices[index + 1].clone();
  49103. nV2 = clipVertices(nV1, vertices[index + 2]);
  49104. nV3 = clipVertices(nV1, vertices[index]);
  49105. result.push(nV1);
  49106. result.push(nV2);
  49107. result.push(nV3);
  49108. }
  49109. if (!v3Out) {
  49110. nV1 = vertices[index + 2].clone();
  49111. nV2 = clipVertices(nV1, vertices[index]);
  49112. nV3 = clipVertices(nV1, vertices[index + 1]);
  49113. result.push(nV1);
  49114. result.push(nV2);
  49115. result.push(nV3);
  49116. }
  49117. break;
  49118. case 3:
  49119. break;
  49120. }
  49121. }
  49122. return result;
  49123. };
  49124. for (var index = 0; index < indices.length; index += 3) {
  49125. var faceVertices = new Array();
  49126. faceVertices.push(extractDecalVector3(index));
  49127. faceVertices.push(extractDecalVector3(index + 1));
  49128. faceVertices.push(extractDecalVector3(index + 2));
  49129. // Clip
  49130. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  49131. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  49132. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  49133. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  49134. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  49135. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  49136. if (faceVertices.length === 0) {
  49137. continue;
  49138. }
  49139. // Add UVs and get back to world
  49140. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  49141. var vertex = faceVertices[vIndex];
  49142. //TODO check for Int32Array | Uint32Array | Uint16Array
  49143. vertexData.indices.push(currentVertexDataIndex);
  49144. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  49145. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  49146. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  49147. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  49148. currentVertexDataIndex++;
  49149. }
  49150. }
  49151. // Return mesh
  49152. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  49153. vertexData.applyToMesh(decal);
  49154. decal.position = position.clone();
  49155. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  49156. return decal;
  49157. };
  49158. // Privates
  49159. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  49160. // extrusion geometry
  49161. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  49162. var tangents = path3D.getTangents();
  49163. var normals = path3D.getNormals();
  49164. var binormals = path3D.getBinormals();
  49165. var distances = path3D.getDistances();
  49166. var angle = 0;
  49167. var returnScale = function () { return scale !== null ? scale : 1; };
  49168. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  49169. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  49170. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  49171. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49172. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49173. for (var i = 0; i < curve.length; i++) {
  49174. var shapePath = new Array();
  49175. var angleStep = rotate(i, distances[i]);
  49176. var scaleRatio = scl(i, distances[i]);
  49177. for (var p = 0; p < shape.length; p++) {
  49178. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  49179. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  49180. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  49181. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  49182. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  49183. shapePath[p] = rotated;
  49184. }
  49185. shapePaths[index] = shapePath;
  49186. angle += angleStep;
  49187. index++;
  49188. }
  49189. // cap
  49190. var capPath = function (shapePath) {
  49191. var pointCap = Array();
  49192. var barycenter = BABYLON.Vector3.Zero();
  49193. var i;
  49194. for (i = 0; i < shapePath.length; i++) {
  49195. barycenter.addInPlace(shapePath[i]);
  49196. }
  49197. barycenter.scaleInPlace(1.0 / shapePath.length);
  49198. for (i = 0; i < shapePath.length; i++) {
  49199. pointCap.push(barycenter);
  49200. }
  49201. return pointCap;
  49202. };
  49203. switch (cap) {
  49204. case BABYLON.Mesh.NO_CAP:
  49205. break;
  49206. case BABYLON.Mesh.CAP_START:
  49207. shapePaths[0] = capPath(shapePaths[2]);
  49208. shapePaths[1] = shapePaths[2];
  49209. break;
  49210. case BABYLON.Mesh.CAP_END:
  49211. shapePaths[index] = shapePaths[index - 1];
  49212. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49213. break;
  49214. case BABYLON.Mesh.CAP_ALL:
  49215. shapePaths[0] = capPath(shapePaths[2]);
  49216. shapePaths[1] = shapePaths[2];
  49217. shapePaths[index] = shapePaths[index - 1];
  49218. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49219. break;
  49220. default:
  49221. break;
  49222. }
  49223. return shapePaths;
  49224. };
  49225. var path3D;
  49226. var pathArray;
  49227. if (instance) {
  49228. path3D = (instance.path3D).update(curve);
  49229. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  49230. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  49231. return instance;
  49232. }
  49233. // extruded shape creation
  49234. path3D = new BABYLON.Path3D(curve);
  49235. var newShapePaths = new Array();
  49236. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49237. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  49238. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  49239. extrudedGeneric.pathArray = pathArray;
  49240. extrudedGeneric.path3D = path3D;
  49241. extrudedGeneric.cap = cap;
  49242. return extrudedGeneric;
  49243. };
  49244. return MeshBuilder;
  49245. }());
  49246. BABYLON.MeshBuilder = MeshBuilder;
  49247. })(BABYLON || (BABYLON = {}));
  49248. //# sourceMappingURL=babylon.meshBuilder.js.map
  49249. var BABYLON;
  49250. (function (BABYLON) {
  49251. var AudioEngine = /** @class */ (function () {
  49252. function AudioEngine() {
  49253. this._audioContext = null;
  49254. this._audioContextInitialized = false;
  49255. this.canUseWebAudio = false;
  49256. this.WarnedWebAudioUnsupported = false;
  49257. this.unlocked = false;
  49258. this.isMP3supported = false;
  49259. this.isOGGsupported = false;
  49260. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  49261. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  49262. this.canUseWebAudio = true;
  49263. }
  49264. var audioElem = document.createElement('audio');
  49265. try {
  49266. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  49267. this.isMP3supported = true;
  49268. }
  49269. }
  49270. catch (e) {
  49271. // protect error during capability check.
  49272. }
  49273. try {
  49274. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  49275. this.isOGGsupported = true;
  49276. }
  49277. }
  49278. catch (e) {
  49279. // protect error during capability check.
  49280. }
  49281. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  49282. this._unlockiOSaudio();
  49283. }
  49284. else {
  49285. this.unlocked = true;
  49286. }
  49287. }
  49288. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  49289. get: function () {
  49290. if (!this._audioContextInitialized) {
  49291. this._initializeAudioContext();
  49292. }
  49293. return this._audioContext;
  49294. },
  49295. enumerable: true,
  49296. configurable: true
  49297. });
  49298. AudioEngine.prototype._unlockiOSaudio = function () {
  49299. var _this = this;
  49300. var unlockaudio = function () {
  49301. if (!_this.audioContext) {
  49302. return;
  49303. }
  49304. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  49305. var source = _this.audioContext.createBufferSource();
  49306. source.buffer = buffer;
  49307. source.connect(_this.audioContext.destination);
  49308. source.start(0);
  49309. setTimeout(function () {
  49310. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  49311. _this.unlocked = true;
  49312. window.removeEventListener('touchend', unlockaudio, false);
  49313. if (_this.onAudioUnlocked) {
  49314. _this.onAudioUnlocked();
  49315. }
  49316. }
  49317. }, 0);
  49318. };
  49319. window.addEventListener('touchend', unlockaudio, false);
  49320. };
  49321. AudioEngine.prototype._initializeAudioContext = function () {
  49322. try {
  49323. if (this.canUseWebAudio) {
  49324. this._audioContext = new AudioContext();
  49325. // create a global volume gain node
  49326. this.masterGain = this._audioContext.createGain();
  49327. this.masterGain.gain.value = 1;
  49328. this.masterGain.connect(this._audioContext.destination);
  49329. this._audioContextInitialized = true;
  49330. }
  49331. }
  49332. catch (e) {
  49333. this.canUseWebAudio = false;
  49334. BABYLON.Tools.Error("Web Audio: " + e.message);
  49335. }
  49336. };
  49337. AudioEngine.prototype.dispose = function () {
  49338. if (this.canUseWebAudio && this._audioContextInitialized) {
  49339. if (this._connectedAnalyser && this._audioContext) {
  49340. this._connectedAnalyser.stopDebugCanvas();
  49341. this._connectedAnalyser.dispose();
  49342. this.masterGain.disconnect();
  49343. this.masterGain.connect(this._audioContext.destination);
  49344. this._connectedAnalyser = null;
  49345. }
  49346. this.masterGain.gain.value = 1;
  49347. }
  49348. this.WarnedWebAudioUnsupported = false;
  49349. };
  49350. AudioEngine.prototype.getGlobalVolume = function () {
  49351. if (this.canUseWebAudio && this._audioContextInitialized) {
  49352. return this.masterGain.gain.value;
  49353. }
  49354. else {
  49355. return -1;
  49356. }
  49357. };
  49358. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  49359. if (this.canUseWebAudio && this._audioContextInitialized) {
  49360. this.masterGain.gain.value = newVolume;
  49361. }
  49362. };
  49363. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  49364. if (this._connectedAnalyser) {
  49365. this._connectedAnalyser.stopDebugCanvas();
  49366. }
  49367. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  49368. this._connectedAnalyser = analyser;
  49369. this.masterGain.disconnect();
  49370. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  49371. }
  49372. };
  49373. return AudioEngine;
  49374. }());
  49375. BABYLON.AudioEngine = AudioEngine;
  49376. })(BABYLON || (BABYLON = {}));
  49377. //# sourceMappingURL=babylon.audioEngine.js.map
  49378. var BABYLON;
  49379. (function (BABYLON) {
  49380. var Sound = /** @class */ (function () {
  49381. /**
  49382. * Create a sound and attach it to a scene
  49383. * @param name Name of your sound
  49384. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  49385. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  49386. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  49387. */
  49388. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  49389. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  49390. var _this = this;
  49391. this.autoplay = false;
  49392. this.loop = false;
  49393. this.useCustomAttenuation = false;
  49394. this.spatialSound = false;
  49395. this.refDistance = 1;
  49396. this.rolloffFactor = 1;
  49397. this.maxDistance = 100;
  49398. this.distanceModel = "linear";
  49399. this._panningModel = "equalpower";
  49400. this._playbackRate = 1;
  49401. this._streaming = false;
  49402. this._startTime = 0;
  49403. this._startOffset = 0;
  49404. this._position = BABYLON.Vector3.Zero();
  49405. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  49406. this._volume = 1;
  49407. this._isReadyToPlay = false;
  49408. this.isPlaying = false;
  49409. this.isPaused = false;
  49410. this._isDirectional = false;
  49411. // Used if you'd like to create a directional sound.
  49412. // If not set, the sound will be omnidirectional
  49413. this._coneInnerAngle = 360;
  49414. this._coneOuterAngle = 360;
  49415. this._coneOuterGain = 0;
  49416. this._isOutputConnected = false;
  49417. this._urlType = "Unknown";
  49418. this.name = name;
  49419. this._scene = scene;
  49420. this._readyToPlayCallback = readyToPlayCallback;
  49421. // Default custom attenuation function is a linear attenuation
  49422. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  49423. if (currentDistance < maxDistance) {
  49424. return currentVolume * (1 - currentDistance / maxDistance);
  49425. }
  49426. else {
  49427. return 0;
  49428. }
  49429. };
  49430. if (options) {
  49431. this.autoplay = options.autoplay || false;
  49432. this.loop = options.loop || false;
  49433. // if volume === 0, we need another way to check this option
  49434. if (options.volume !== undefined) {
  49435. this._volume = options.volume;
  49436. }
  49437. this.spatialSound = options.spatialSound || false;
  49438. this.maxDistance = options.maxDistance || 100;
  49439. this.useCustomAttenuation = options.useCustomAttenuation || false;
  49440. this.rolloffFactor = options.rolloffFactor || 1;
  49441. this.refDistance = options.refDistance || 1;
  49442. this.distanceModel = options.distanceModel || "linear";
  49443. this._playbackRate = options.playbackRate || 1;
  49444. this._streaming = options.streaming || false;
  49445. }
  49446. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49447. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  49448. this._soundGain.gain.value = this._volume;
  49449. this._inputAudioNode = this._soundGain;
  49450. this._ouputAudioNode = this._soundGain;
  49451. if (this.spatialSound) {
  49452. this._createSpatialParameters();
  49453. }
  49454. this._scene.mainSoundTrack.AddSound(this);
  49455. var validParameter = true;
  49456. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  49457. if (urlOrArrayBuffer) {
  49458. if (typeof (urlOrArrayBuffer) === "string")
  49459. this._urlType = "String";
  49460. if (Array.isArray(urlOrArrayBuffer))
  49461. this._urlType = "Array";
  49462. if (urlOrArrayBuffer instanceof ArrayBuffer)
  49463. this._urlType = "ArrayBuffer";
  49464. var urls = [];
  49465. var codecSupportedFound = false;
  49466. switch (this._urlType) {
  49467. case "ArrayBuffer":
  49468. if (urlOrArrayBuffer.byteLength > 0) {
  49469. codecSupportedFound = true;
  49470. this._soundLoaded(urlOrArrayBuffer);
  49471. }
  49472. break;
  49473. case "String":
  49474. urls.push(urlOrArrayBuffer);
  49475. case "Array":
  49476. if (urls.length === 0)
  49477. urls = urlOrArrayBuffer;
  49478. // If we found a supported format, we load it immediately and stop the loop
  49479. for (var i = 0; i < urls.length; i++) {
  49480. var url = urls[i];
  49481. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  49482. codecSupportedFound = true;
  49483. }
  49484. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  49485. codecSupportedFound = true;
  49486. }
  49487. if (url.indexOf(".wav", url.length - 4) !== -1) {
  49488. codecSupportedFound = true;
  49489. }
  49490. if (url.indexOf("blob:") !== -1) {
  49491. codecSupportedFound = true;
  49492. }
  49493. if (codecSupportedFound) {
  49494. // Loading sound using XHR2
  49495. if (!this._streaming) {
  49496. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  49497. }
  49498. else {
  49499. this._htmlAudioElement = new Audio(url);
  49500. this._htmlAudioElement.controls = false;
  49501. this._htmlAudioElement.loop = this.loop;
  49502. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  49503. this._htmlAudioElement.preload = "auto";
  49504. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49505. _this._isReadyToPlay = true;
  49506. if (_this.autoplay) {
  49507. _this.play();
  49508. }
  49509. if (_this._readyToPlayCallback) {
  49510. _this._readyToPlayCallback();
  49511. }
  49512. });
  49513. document.body.appendChild(this._htmlAudioElement);
  49514. }
  49515. break;
  49516. }
  49517. }
  49518. break;
  49519. default:
  49520. validParameter = false;
  49521. break;
  49522. }
  49523. if (!validParameter) {
  49524. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49525. }
  49526. else {
  49527. if (!codecSupportedFound) {
  49528. this._isReadyToPlay = true;
  49529. // Simulating a ready to play event to avoid breaking code path
  49530. if (this._readyToPlayCallback) {
  49531. window.setTimeout(function () {
  49532. if (_this._readyToPlayCallback) {
  49533. _this._readyToPlayCallback();
  49534. }
  49535. }, 1000);
  49536. }
  49537. }
  49538. }
  49539. }
  49540. }
  49541. else {
  49542. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49543. this._scene.mainSoundTrack.AddSound(this);
  49544. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49545. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49546. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49547. }
  49548. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49549. if (this._readyToPlayCallback) {
  49550. window.setTimeout(function () {
  49551. if (_this._readyToPlayCallback) {
  49552. _this._readyToPlayCallback();
  49553. }
  49554. }, 1000);
  49555. }
  49556. }
  49557. }
  49558. Sound.prototype.dispose = function () {
  49559. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49560. if (this.isPlaying) {
  49561. this.stop();
  49562. }
  49563. this._isReadyToPlay = false;
  49564. if (this.soundTrackId === -1) {
  49565. this._scene.mainSoundTrack.RemoveSound(this);
  49566. }
  49567. else {
  49568. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49569. }
  49570. if (this._soundGain) {
  49571. this._soundGain.disconnect();
  49572. this._soundGain = null;
  49573. }
  49574. if (this._soundPanner) {
  49575. this._soundPanner.disconnect();
  49576. this._soundPanner = null;
  49577. }
  49578. if (this._soundSource) {
  49579. this._soundSource.disconnect();
  49580. this._soundSource = null;
  49581. }
  49582. this._audioBuffer = null;
  49583. if (this._htmlAudioElement) {
  49584. this._htmlAudioElement.pause();
  49585. this._htmlAudioElement.src = "";
  49586. document.body.removeChild(this._htmlAudioElement);
  49587. }
  49588. if (this._connectedMesh && this._registerFunc) {
  49589. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49590. this._connectedMesh = null;
  49591. }
  49592. }
  49593. };
  49594. Sound.prototype.isReady = function () {
  49595. return this._isReadyToPlay;
  49596. };
  49597. Sound.prototype._soundLoaded = function (audioData) {
  49598. var _this = this;
  49599. if (!BABYLON.Engine.audioEngine.audioContext) {
  49600. return;
  49601. }
  49602. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49603. _this._audioBuffer = buffer;
  49604. _this._isReadyToPlay = true;
  49605. if (_this.autoplay) {
  49606. _this.play();
  49607. }
  49608. if (_this._readyToPlayCallback) {
  49609. _this._readyToPlayCallback();
  49610. }
  49611. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49612. };
  49613. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49614. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49615. this._audioBuffer = audioBuffer;
  49616. this._isReadyToPlay = true;
  49617. }
  49618. };
  49619. Sound.prototype.updateOptions = function (options) {
  49620. if (options) {
  49621. this.loop = options.loop || this.loop;
  49622. this.maxDistance = options.maxDistance || this.maxDistance;
  49623. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49624. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49625. this.refDistance = options.refDistance || this.refDistance;
  49626. this.distanceModel = options.distanceModel || this.distanceModel;
  49627. this._playbackRate = options.playbackRate || this._playbackRate;
  49628. this._updateSpatialParameters();
  49629. if (this.isPlaying) {
  49630. if (this._streaming) {
  49631. this._htmlAudioElement.playbackRate = this._playbackRate;
  49632. }
  49633. else {
  49634. if (this._soundSource) {
  49635. this._soundSource.playbackRate.value = this._playbackRate;
  49636. }
  49637. }
  49638. }
  49639. }
  49640. };
  49641. Sound.prototype._createSpatialParameters = function () {
  49642. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49643. if (this._scene.headphone) {
  49644. this._panningModel = "HRTF";
  49645. }
  49646. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49647. this._updateSpatialParameters();
  49648. this._soundPanner.connect(this._ouputAudioNode);
  49649. this._inputAudioNode = this._soundPanner;
  49650. }
  49651. };
  49652. Sound.prototype._updateSpatialParameters = function () {
  49653. if (this.spatialSound && this._soundPanner) {
  49654. if (this.useCustomAttenuation) {
  49655. // Tricks to disable in a way embedded Web Audio attenuation
  49656. this._soundPanner.distanceModel = "linear";
  49657. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49658. this._soundPanner.refDistance = 1;
  49659. this._soundPanner.rolloffFactor = 1;
  49660. this._soundPanner.panningModel = this._panningModel;
  49661. }
  49662. else {
  49663. this._soundPanner.distanceModel = this.distanceModel;
  49664. this._soundPanner.maxDistance = this.maxDistance;
  49665. this._soundPanner.refDistance = this.refDistance;
  49666. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49667. this._soundPanner.panningModel = this._panningModel;
  49668. }
  49669. }
  49670. };
  49671. Sound.prototype.switchPanningModelToHRTF = function () {
  49672. this._panningModel = "HRTF";
  49673. this._switchPanningModel();
  49674. };
  49675. Sound.prototype.switchPanningModelToEqualPower = function () {
  49676. this._panningModel = "equalpower";
  49677. this._switchPanningModel();
  49678. };
  49679. Sound.prototype._switchPanningModel = function () {
  49680. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49681. this._soundPanner.panningModel = this._panningModel;
  49682. }
  49683. };
  49684. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49686. if (this._isOutputConnected) {
  49687. this._ouputAudioNode.disconnect();
  49688. }
  49689. this._ouputAudioNode.connect(soundTrackAudioNode);
  49690. this._isOutputConnected = true;
  49691. }
  49692. };
  49693. /**
  49694. * Transform this sound into a directional source
  49695. * @param coneInnerAngle Size of the inner cone in degree
  49696. * @param coneOuterAngle Size of the outer cone in degree
  49697. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49698. */
  49699. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49700. if (coneOuterAngle < coneInnerAngle) {
  49701. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49702. return;
  49703. }
  49704. this._coneInnerAngle = coneInnerAngle;
  49705. this._coneOuterAngle = coneOuterAngle;
  49706. this._coneOuterGain = coneOuterGain;
  49707. this._isDirectional = true;
  49708. if (this.isPlaying && this.loop) {
  49709. this.stop();
  49710. this.play();
  49711. }
  49712. };
  49713. Sound.prototype.setPosition = function (newPosition) {
  49714. this._position = newPosition;
  49715. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49716. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49717. }
  49718. };
  49719. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49720. this._localDirection = newLocalDirection;
  49721. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49722. this._updateDirection();
  49723. }
  49724. };
  49725. Sound.prototype._updateDirection = function () {
  49726. if (!this._connectedMesh || !this._soundPanner) {
  49727. return;
  49728. }
  49729. var mat = this._connectedMesh.getWorldMatrix();
  49730. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49731. direction.normalize();
  49732. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49733. };
  49734. Sound.prototype.updateDistanceFromListener = function () {
  49735. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49736. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49737. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49738. }
  49739. };
  49740. Sound.prototype.setAttenuationFunction = function (callback) {
  49741. this._customAttenuationFunction = callback;
  49742. };
  49743. /**
  49744. * Play the sound
  49745. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49746. * @param offset (optional) Start the sound setting it at a specific time
  49747. */
  49748. Sound.prototype.play = function (time, offset) {
  49749. var _this = this;
  49750. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49751. try {
  49752. if (this._startOffset < 0) {
  49753. time = -this._startOffset;
  49754. this._startOffset = 0;
  49755. }
  49756. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49757. if (!this._soundSource || !this._streamingSource) {
  49758. if (this.spatialSound && this._soundPanner) {
  49759. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49760. if (this._isDirectional) {
  49761. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49762. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49763. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49764. if (this._connectedMesh) {
  49765. this._updateDirection();
  49766. }
  49767. else {
  49768. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49769. }
  49770. }
  49771. }
  49772. }
  49773. if (this._streaming) {
  49774. if (!this._streamingSource) {
  49775. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49776. this._htmlAudioElement.onended = function () { _this._onended(); };
  49777. this._htmlAudioElement.playbackRate = this._playbackRate;
  49778. }
  49779. this._streamingSource.disconnect();
  49780. this._streamingSource.connect(this._inputAudioNode);
  49781. this._htmlAudioElement.play();
  49782. }
  49783. else {
  49784. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49785. this._soundSource.buffer = this._audioBuffer;
  49786. this._soundSource.connect(this._inputAudioNode);
  49787. this._soundSource.loop = this.loop;
  49788. this._soundSource.playbackRate.value = this._playbackRate;
  49789. this._soundSource.onended = function () { _this._onended(); };
  49790. if (this._soundSource.buffer) {
  49791. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49792. }
  49793. }
  49794. this._startTime = startTime;
  49795. this.isPlaying = true;
  49796. this.isPaused = false;
  49797. }
  49798. catch (ex) {
  49799. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49800. }
  49801. }
  49802. };
  49803. Sound.prototype._onended = function () {
  49804. this.isPlaying = false;
  49805. if (this.onended) {
  49806. this.onended();
  49807. }
  49808. };
  49809. /**
  49810. * Stop the sound
  49811. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49812. */
  49813. Sound.prototype.stop = function (time) {
  49814. if (this.isPlaying) {
  49815. if (this._streaming) {
  49816. this._htmlAudioElement.pause();
  49817. // Test needed for Firefox or it will generate an Invalid State Error
  49818. if (this._htmlAudioElement.currentTime > 0) {
  49819. this._htmlAudioElement.currentTime = 0;
  49820. }
  49821. }
  49822. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49823. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49824. this._soundSource.stop(stopTime);
  49825. this._soundSource.onended = function () { };
  49826. if (!this.isPaused) {
  49827. this._startOffset = 0;
  49828. }
  49829. }
  49830. this.isPlaying = false;
  49831. }
  49832. };
  49833. Sound.prototype.pause = function () {
  49834. if (this.isPlaying) {
  49835. this.isPaused = true;
  49836. if (this._streaming) {
  49837. this._htmlAudioElement.pause();
  49838. }
  49839. else if (BABYLON.Engine.audioEngine.audioContext) {
  49840. this.stop(0);
  49841. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49842. }
  49843. }
  49844. };
  49845. Sound.prototype.setVolume = function (newVolume, time) {
  49846. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49847. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49848. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49849. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49850. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49851. }
  49852. else {
  49853. this._soundGain.gain.value = newVolume;
  49854. }
  49855. }
  49856. this._volume = newVolume;
  49857. };
  49858. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49859. this._playbackRate = newPlaybackRate;
  49860. if (this.isPlaying) {
  49861. if (this._streaming) {
  49862. this._htmlAudioElement.playbackRate = this._playbackRate;
  49863. }
  49864. else if (this._soundSource) {
  49865. this._soundSource.playbackRate.value = this._playbackRate;
  49866. }
  49867. }
  49868. };
  49869. Sound.prototype.getVolume = function () {
  49870. return this._volume;
  49871. };
  49872. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49873. var _this = this;
  49874. if (this._connectedMesh && this._registerFunc) {
  49875. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49876. this._registerFunc = null;
  49877. }
  49878. this._connectedMesh = meshToConnectTo;
  49879. if (!this.spatialSound) {
  49880. this.spatialSound = true;
  49881. this._createSpatialParameters();
  49882. if (this.isPlaying && this.loop) {
  49883. this.stop();
  49884. this.play();
  49885. }
  49886. }
  49887. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49888. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49889. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49890. };
  49891. Sound.prototype.detachFromMesh = function () {
  49892. if (this._connectedMesh && this._registerFunc) {
  49893. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49894. this._registerFunc = null;
  49895. this._connectedMesh = null;
  49896. }
  49897. };
  49898. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  49899. if (!node.getBoundingInfo) {
  49900. return;
  49901. }
  49902. var mesh = node;
  49903. var boundingInfo = mesh.getBoundingInfo();
  49904. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49905. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49906. this._updateDirection();
  49907. }
  49908. };
  49909. Sound.prototype.clone = function () {
  49910. var _this = this;
  49911. if (!this._streaming) {
  49912. var setBufferAndRun = function () {
  49913. if (_this._isReadyToPlay) {
  49914. clonedSound._audioBuffer = _this.getAudioBuffer();
  49915. clonedSound._isReadyToPlay = true;
  49916. if (clonedSound.autoplay) {
  49917. clonedSound.play();
  49918. }
  49919. }
  49920. else {
  49921. window.setTimeout(setBufferAndRun, 300);
  49922. }
  49923. };
  49924. var currentOptions = {
  49925. autoplay: this.autoplay, loop: this.loop,
  49926. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49927. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49928. refDistance: this.refDistance, distanceModel: this.distanceModel
  49929. };
  49930. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49931. if (this.useCustomAttenuation) {
  49932. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49933. }
  49934. clonedSound.setPosition(this._position);
  49935. clonedSound.setPlaybackRate(this._playbackRate);
  49936. setBufferAndRun();
  49937. return clonedSound;
  49938. }
  49939. else {
  49940. return null;
  49941. }
  49942. };
  49943. Sound.prototype.getAudioBuffer = function () {
  49944. return this._audioBuffer;
  49945. };
  49946. Sound.prototype.serialize = function () {
  49947. var serializationObject = {
  49948. name: this.name,
  49949. url: this.name,
  49950. autoplay: this.autoplay,
  49951. loop: this.loop,
  49952. volume: this._volume,
  49953. spatialSound: this.spatialSound,
  49954. maxDistance: this.maxDistance,
  49955. rolloffFactor: this.rolloffFactor,
  49956. refDistance: this.refDistance,
  49957. distanceModel: this.distanceModel,
  49958. playbackRate: this._playbackRate,
  49959. panningModel: this._panningModel,
  49960. soundTrackId: this.soundTrackId
  49961. };
  49962. if (this.spatialSound) {
  49963. if (this._connectedMesh)
  49964. serializationObject.connectedMeshId = this._connectedMesh.id;
  49965. serializationObject.position = this._position.asArray();
  49966. serializationObject.refDistance = this.refDistance;
  49967. serializationObject.distanceModel = this.distanceModel;
  49968. serializationObject.isDirectional = this._isDirectional;
  49969. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49970. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49971. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49972. serializationObject.coneOuterGain = this._coneOuterGain;
  49973. }
  49974. return serializationObject;
  49975. };
  49976. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49977. var soundName = parsedSound.name;
  49978. var soundUrl;
  49979. if (parsedSound.url) {
  49980. soundUrl = rootUrl + parsedSound.url;
  49981. }
  49982. else {
  49983. soundUrl = rootUrl + soundName;
  49984. }
  49985. var options = {
  49986. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49987. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49988. rolloffFactor: parsedSound.rolloffFactor,
  49989. refDistance: parsedSound.refDistance,
  49990. distanceModel: parsedSound.distanceModel,
  49991. playbackRate: parsedSound.playbackRate
  49992. };
  49993. var newSound;
  49994. if (!sourceSound) {
  49995. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49996. scene._addPendingData(newSound);
  49997. }
  49998. else {
  49999. var setBufferAndRun = function () {
  50000. if (sourceSound._isReadyToPlay) {
  50001. newSound._audioBuffer = sourceSound.getAudioBuffer();
  50002. newSound._isReadyToPlay = true;
  50003. if (newSound.autoplay) {
  50004. newSound.play();
  50005. }
  50006. }
  50007. else {
  50008. window.setTimeout(setBufferAndRun, 300);
  50009. }
  50010. };
  50011. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  50012. setBufferAndRun();
  50013. }
  50014. if (parsedSound.position) {
  50015. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  50016. newSound.setPosition(soundPosition);
  50017. }
  50018. if (parsedSound.isDirectional) {
  50019. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  50020. if (parsedSound.localDirectionToMesh) {
  50021. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  50022. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  50023. }
  50024. }
  50025. if (parsedSound.connectedMeshId) {
  50026. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  50027. if (connectedMesh) {
  50028. newSound.attachToMesh(connectedMesh);
  50029. }
  50030. }
  50031. return newSound;
  50032. };
  50033. return Sound;
  50034. }());
  50035. BABYLON.Sound = Sound;
  50036. })(BABYLON || (BABYLON = {}));
  50037. //# sourceMappingURL=babylon.sound.js.map
  50038. var BABYLON;
  50039. (function (BABYLON) {
  50040. var SoundTrack = /** @class */ (function () {
  50041. function SoundTrack(scene, options) {
  50042. this.id = -1;
  50043. this._isMainTrack = false;
  50044. this._isInitialized = false;
  50045. this._scene = scene;
  50046. this.soundCollection = new Array();
  50047. this._options = options;
  50048. if (!this._isMainTrack) {
  50049. this._scene.soundTracks.push(this);
  50050. this.id = this._scene.soundTracks.length - 1;
  50051. }
  50052. }
  50053. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  50054. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50055. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  50056. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  50057. if (this._options) {
  50058. if (this._options.volume) {
  50059. this._outputAudioNode.gain.value = this._options.volume;
  50060. }
  50061. if (this._options.mainTrack) {
  50062. this._isMainTrack = this._options.mainTrack;
  50063. }
  50064. }
  50065. this._isInitialized = true;
  50066. }
  50067. };
  50068. SoundTrack.prototype.dispose = function () {
  50069. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50070. if (this._connectedAnalyser) {
  50071. this._connectedAnalyser.stopDebugCanvas();
  50072. }
  50073. while (this.soundCollection.length) {
  50074. this.soundCollection[0].dispose();
  50075. }
  50076. if (this._outputAudioNode) {
  50077. this._outputAudioNode.disconnect();
  50078. }
  50079. this._outputAudioNode = null;
  50080. }
  50081. };
  50082. SoundTrack.prototype.AddSound = function (sound) {
  50083. if (!this._isInitialized) {
  50084. this._initializeSoundTrackAudioGraph();
  50085. }
  50086. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50087. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  50088. }
  50089. if (sound.soundTrackId) {
  50090. if (sound.soundTrackId === -1) {
  50091. this._scene.mainSoundTrack.RemoveSound(sound);
  50092. }
  50093. else {
  50094. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  50095. }
  50096. }
  50097. this.soundCollection.push(sound);
  50098. sound.soundTrackId = this.id;
  50099. };
  50100. SoundTrack.prototype.RemoveSound = function (sound) {
  50101. var index = this.soundCollection.indexOf(sound);
  50102. if (index !== -1) {
  50103. this.soundCollection.splice(index, 1);
  50104. }
  50105. };
  50106. SoundTrack.prototype.setVolume = function (newVolume) {
  50107. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50108. this._outputAudioNode.gain.value = newVolume;
  50109. }
  50110. };
  50111. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  50112. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50113. for (var i = 0; i < this.soundCollection.length; i++) {
  50114. this.soundCollection[i].switchPanningModelToHRTF();
  50115. }
  50116. }
  50117. };
  50118. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  50119. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50120. for (var i = 0; i < this.soundCollection.length; i++) {
  50121. this.soundCollection[i].switchPanningModelToEqualPower();
  50122. }
  50123. }
  50124. };
  50125. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  50126. if (this._connectedAnalyser) {
  50127. this._connectedAnalyser.stopDebugCanvas();
  50128. }
  50129. this._connectedAnalyser = analyser;
  50130. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50131. this._outputAudioNode.disconnect();
  50132. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  50133. }
  50134. };
  50135. return SoundTrack;
  50136. }());
  50137. BABYLON.SoundTrack = SoundTrack;
  50138. })(BABYLON || (BABYLON = {}));
  50139. //# sourceMappingURL=babylon.soundtrack.js.map
  50140. var BABYLON;
  50141. (function (BABYLON) {
  50142. var Analyser = /** @class */ (function () {
  50143. function Analyser(scene) {
  50144. this.SMOOTHING = 0.75;
  50145. this.FFT_SIZE = 512;
  50146. this.BARGRAPHAMPLITUDE = 256;
  50147. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50148. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50149. this._scene = scene;
  50150. this._audioEngine = BABYLON.Engine.audioEngine;
  50151. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  50152. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50153. this._webAudioAnalyser.minDecibels = -140;
  50154. this._webAudioAnalyser.maxDecibels = 0;
  50155. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50156. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50157. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50158. }
  50159. }
  50160. Analyser.prototype.getFrequencyBinCount = function () {
  50161. if (this._audioEngine.canUseWebAudio) {
  50162. return this._webAudioAnalyser.frequencyBinCount;
  50163. }
  50164. else {
  50165. return 0;
  50166. }
  50167. };
  50168. Analyser.prototype.getByteFrequencyData = function () {
  50169. if (this._audioEngine.canUseWebAudio) {
  50170. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50171. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50172. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50173. }
  50174. return this._byteFreqs;
  50175. };
  50176. Analyser.prototype.getByteTimeDomainData = function () {
  50177. if (this._audioEngine.canUseWebAudio) {
  50178. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50179. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50180. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50181. }
  50182. return this._byteTime;
  50183. };
  50184. Analyser.prototype.getFloatFrequencyData = function () {
  50185. if (this._audioEngine.canUseWebAudio) {
  50186. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50187. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50188. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50189. }
  50190. return this._floatFreqs;
  50191. };
  50192. Analyser.prototype.drawDebugCanvas = function () {
  50193. var _this = this;
  50194. if (this._audioEngine.canUseWebAudio) {
  50195. if (!this._debugCanvas) {
  50196. this._debugCanvas = document.createElement("canvas");
  50197. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50198. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50199. this._debugCanvas.style.position = "absolute";
  50200. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50201. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50202. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50203. document.body.appendChild(this._debugCanvas);
  50204. this._registerFunc = function () {
  50205. _this.drawDebugCanvas();
  50206. };
  50207. this._scene.registerBeforeRender(this._registerFunc);
  50208. }
  50209. if (this._registerFunc && this._debugCanvasContext) {
  50210. var workingArray = this.getByteFrequencyData();
  50211. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50212. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50213. // Draw the frequency domain chart.
  50214. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50215. var value = workingArray[i];
  50216. var percent = value / this.BARGRAPHAMPLITUDE;
  50217. var height = this.DEBUGCANVASSIZE.height * percent;
  50218. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50219. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50220. var hue = i / this.getFrequencyBinCount() * 360;
  50221. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50222. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50223. }
  50224. }
  50225. }
  50226. };
  50227. Analyser.prototype.stopDebugCanvas = function () {
  50228. if (this._debugCanvas) {
  50229. if (this._registerFunc) {
  50230. this._scene.unregisterBeforeRender(this._registerFunc);
  50231. this._registerFunc = null;
  50232. }
  50233. document.body.removeChild(this._debugCanvas);
  50234. this._debugCanvas = null;
  50235. this._debugCanvasContext = null;
  50236. }
  50237. };
  50238. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50239. if (this._audioEngine.canUseWebAudio) {
  50240. inputAudioNode.connect(this._webAudioAnalyser);
  50241. this._webAudioAnalyser.connect(outputAudioNode);
  50242. }
  50243. };
  50244. Analyser.prototype.dispose = function () {
  50245. if (this._audioEngine.canUseWebAudio) {
  50246. this._webAudioAnalyser.disconnect();
  50247. }
  50248. };
  50249. return Analyser;
  50250. }());
  50251. BABYLON.Analyser = Analyser;
  50252. })(BABYLON || (BABYLON = {}));
  50253. //# sourceMappingURL=babylon.analyser.js.map
  50254. var BABYLON;
  50255. (function (BABYLON) {
  50256. var CubeTexture = /** @class */ (function (_super) {
  50257. __extends(CubeTexture, _super);
  50258. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  50259. if (extensions === void 0) { extensions = null; }
  50260. if (noMipmap === void 0) { noMipmap = false; }
  50261. if (files === void 0) { files = null; }
  50262. if (onLoad === void 0) { onLoad = null; }
  50263. if (onError === void 0) { onError = null; }
  50264. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50265. if (prefiltered === void 0) { prefiltered = false; }
  50266. if (forcedExtension === void 0) { forcedExtension = null; }
  50267. var _this = _super.call(this, scene) || this;
  50268. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  50269. _this.name = rootUrl;
  50270. _this.url = rootUrl;
  50271. _this._noMipmap = noMipmap;
  50272. _this.hasAlpha = false;
  50273. _this._format = format;
  50274. _this._prefiltered = prefiltered;
  50275. _this.isCube = true;
  50276. _this._textureMatrix = BABYLON.Matrix.Identity();
  50277. if (prefiltered) {
  50278. _this.gammaSpace = false;
  50279. }
  50280. if (!rootUrl && !files) {
  50281. return _this;
  50282. }
  50283. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  50284. var lastDot = rootUrl.lastIndexOf(".");
  50285. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  50286. var isDDS = (extension === ".dds");
  50287. if (!files) {
  50288. if (!isDDS && !extensions) {
  50289. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  50290. }
  50291. files = [];
  50292. if (extensions) {
  50293. for (var index = 0; index < extensions.length; index++) {
  50294. files.push(rootUrl + extensions[index]);
  50295. }
  50296. }
  50297. }
  50298. _this._files = files;
  50299. if (!_this._texture) {
  50300. if (!scene.useDelayedTextureLoading) {
  50301. if (prefiltered) {
  50302. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  50303. }
  50304. else {
  50305. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  50306. }
  50307. }
  50308. else {
  50309. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50310. }
  50311. }
  50312. else if (onLoad) {
  50313. if (_this._texture.isReady) {
  50314. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  50315. }
  50316. else {
  50317. _this._texture.onLoadedObservable.add(onLoad);
  50318. }
  50319. }
  50320. return _this;
  50321. }
  50322. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  50323. return new CubeTexture("", scene, null, noMipmap, files);
  50324. };
  50325. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  50326. if (forcedExtension === void 0) { forcedExtension = null; }
  50327. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  50328. };
  50329. // Methods
  50330. CubeTexture.prototype.delayLoad = function () {
  50331. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50332. return;
  50333. }
  50334. var scene = this.getScene();
  50335. if (!scene) {
  50336. return;
  50337. }
  50338. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50339. this._texture = this._getFromCache(this.url, this._noMipmap);
  50340. if (!this._texture) {
  50341. if (this._prefiltered) {
  50342. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  50343. }
  50344. else {
  50345. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  50346. }
  50347. }
  50348. };
  50349. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  50350. return this._textureMatrix;
  50351. };
  50352. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  50353. this._textureMatrix = value;
  50354. };
  50355. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50356. var texture = BABYLON.SerializationHelper.Parse(function () {
  50357. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  50358. }, parsedTexture, scene);
  50359. // Animations
  50360. if (parsedTexture.animations) {
  50361. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  50362. var parsedAnimation = parsedTexture.animations[animationIndex];
  50363. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50364. }
  50365. }
  50366. return texture;
  50367. };
  50368. CubeTexture.prototype.clone = function () {
  50369. var _this = this;
  50370. return BABYLON.SerializationHelper.Clone(function () {
  50371. var scene = _this.getScene();
  50372. if (!scene) {
  50373. return _this;
  50374. }
  50375. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  50376. }, this);
  50377. };
  50378. return CubeTexture;
  50379. }(BABYLON.BaseTexture));
  50380. BABYLON.CubeTexture = CubeTexture;
  50381. })(BABYLON || (BABYLON = {}));
  50382. //# sourceMappingURL=babylon.cubeTexture.js.map
  50383. var BABYLON;
  50384. (function (BABYLON) {
  50385. var RenderTargetTexture = /** @class */ (function (_super) {
  50386. __extends(RenderTargetTexture, _super);
  50387. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  50388. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  50389. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50390. if (isCube === void 0) { isCube = false; }
  50391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50392. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50393. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  50394. if (isMulti === void 0) { isMulti = false; }
  50395. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50396. _this.isCube = isCube;
  50397. /**
  50398. * Use this list to define the list of mesh you want to render.
  50399. */
  50400. _this.renderList = new Array();
  50401. _this.renderParticles = true;
  50402. _this.renderSprites = false;
  50403. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  50404. _this.ignoreCameraViewport = false;
  50405. // Events
  50406. /**
  50407. * An event triggered when the texture is unbind.
  50408. * @type {BABYLON.Observable}
  50409. */
  50410. _this.onBeforeBindObservable = new BABYLON.Observable();
  50411. /**
  50412. * An event triggered when the texture is unbind.
  50413. * @type {BABYLON.Observable}
  50414. */
  50415. _this.onAfterUnbindObservable = new BABYLON.Observable();
  50416. /**
  50417. * An event triggered before rendering the texture
  50418. * @type {BABYLON.Observable}
  50419. */
  50420. _this.onBeforeRenderObservable = new BABYLON.Observable();
  50421. /**
  50422. * An event triggered after rendering the texture
  50423. * @type {BABYLON.Observable}
  50424. */
  50425. _this.onAfterRenderObservable = new BABYLON.Observable();
  50426. /**
  50427. * An event triggered after the texture clear
  50428. * @type {BABYLON.Observable}
  50429. */
  50430. _this.onClearObservable = new BABYLON.Observable();
  50431. _this._currentRefreshId = -1;
  50432. _this._refreshRate = 1;
  50433. _this._samples = 1;
  50434. scene = _this.getScene();
  50435. if (!scene) {
  50436. return _this;
  50437. }
  50438. _this._engine = scene.getEngine();
  50439. _this.name = name;
  50440. _this.isRenderTarget = true;
  50441. _this._initialSizeParameter = size;
  50442. _this._processSizeParameter(size);
  50443. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  50444. });
  50445. _this._generateMipMaps = generateMipMaps ? true : false;
  50446. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  50447. // Rendering groups
  50448. _this._renderingManager = new BABYLON.RenderingManager(scene);
  50449. if (isMulti) {
  50450. return _this;
  50451. }
  50452. _this._renderTargetOptions = {
  50453. generateMipMaps: generateMipMaps,
  50454. type: type,
  50455. samplingMode: samplingMode,
  50456. generateDepthBuffer: generateDepthBuffer,
  50457. generateStencilBuffer: generateStencilBuffer
  50458. };
  50459. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  50460. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50461. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50462. }
  50463. if (isCube) {
  50464. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  50465. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  50466. _this._textureMatrix = BABYLON.Matrix.Identity();
  50467. }
  50468. else {
  50469. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  50470. }
  50471. return _this;
  50472. }
  50473. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  50474. get: function () {
  50475. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  50476. },
  50477. enumerable: true,
  50478. configurable: true
  50479. });
  50480. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  50481. get: function () {
  50482. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  50483. },
  50484. enumerable: true,
  50485. configurable: true
  50486. });
  50487. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  50488. get: function () {
  50489. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  50490. },
  50491. enumerable: true,
  50492. configurable: true
  50493. });
  50494. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  50495. set: function (callback) {
  50496. if (this._onAfterUnbindObserver) {
  50497. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  50498. }
  50499. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  50500. },
  50501. enumerable: true,
  50502. configurable: true
  50503. });
  50504. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50505. set: function (callback) {
  50506. if (this._onBeforeRenderObserver) {
  50507. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50508. }
  50509. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50510. },
  50511. enumerable: true,
  50512. configurable: true
  50513. });
  50514. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50515. set: function (callback) {
  50516. if (this._onAfterRenderObserver) {
  50517. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50518. }
  50519. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50520. },
  50521. enumerable: true,
  50522. configurable: true
  50523. });
  50524. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50525. set: function (callback) {
  50526. if (this._onClearObserver) {
  50527. this.onClearObservable.remove(this._onClearObserver);
  50528. }
  50529. this._onClearObserver = this.onClearObservable.add(callback);
  50530. },
  50531. enumerable: true,
  50532. configurable: true
  50533. });
  50534. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50535. get: function () {
  50536. return this._renderTargetOptions;
  50537. },
  50538. enumerable: true,
  50539. configurable: true
  50540. });
  50541. RenderTargetTexture.prototype._onRatioRescale = function () {
  50542. if (this._sizeRatio) {
  50543. this.resize(this._initialSizeParameter);
  50544. }
  50545. };
  50546. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50547. if (size.ratio) {
  50548. this._sizeRatio = size.ratio;
  50549. this._size = {
  50550. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50551. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50552. };
  50553. }
  50554. else {
  50555. this._size = size;
  50556. }
  50557. };
  50558. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50559. get: function () {
  50560. return this._samples;
  50561. },
  50562. set: function (value) {
  50563. if (this._samples === value) {
  50564. return;
  50565. }
  50566. var scene = this.getScene();
  50567. if (!scene) {
  50568. return;
  50569. }
  50570. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50571. },
  50572. enumerable: true,
  50573. configurable: true
  50574. });
  50575. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50576. this._currentRefreshId = -1;
  50577. };
  50578. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50579. get: function () {
  50580. return this._refreshRate;
  50581. },
  50582. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50583. set: function (value) {
  50584. this._refreshRate = value;
  50585. this.resetRefreshCounter();
  50586. },
  50587. enumerable: true,
  50588. configurable: true
  50589. });
  50590. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50591. if (!this._postProcessManager) {
  50592. var scene = this.getScene();
  50593. if (!scene) {
  50594. return;
  50595. }
  50596. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50597. this._postProcesses = new Array();
  50598. }
  50599. this._postProcesses.push(postProcess);
  50600. this._postProcesses[0].autoClear = false;
  50601. };
  50602. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50603. if (!this._postProcesses) {
  50604. return;
  50605. }
  50606. if (dispose) {
  50607. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50608. var postProcess = _a[_i];
  50609. postProcess.dispose();
  50610. }
  50611. }
  50612. this._postProcesses = [];
  50613. };
  50614. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50615. if (!this._postProcesses) {
  50616. return;
  50617. }
  50618. var index = this._postProcesses.indexOf(postProcess);
  50619. if (index === -1) {
  50620. return;
  50621. }
  50622. this._postProcesses.splice(index, 1);
  50623. if (this._postProcesses.length > 0) {
  50624. this._postProcesses[0].autoClear = false;
  50625. }
  50626. };
  50627. RenderTargetTexture.prototype._shouldRender = function () {
  50628. if (this._currentRefreshId === -1) {
  50629. this._currentRefreshId = 1;
  50630. return true;
  50631. }
  50632. if (this.refreshRate === this._currentRefreshId) {
  50633. this._currentRefreshId = 1;
  50634. return true;
  50635. }
  50636. this._currentRefreshId++;
  50637. return false;
  50638. };
  50639. RenderTargetTexture.prototype.getRenderSize = function () {
  50640. if (this._size.width) {
  50641. return this._size.width;
  50642. }
  50643. return this._size;
  50644. };
  50645. RenderTargetTexture.prototype.getRenderWidth = function () {
  50646. if (this._size.width) {
  50647. return this._size.width;
  50648. }
  50649. return this._size;
  50650. };
  50651. RenderTargetTexture.prototype.getRenderHeight = function () {
  50652. if (this._size.width) {
  50653. return this._size.height;
  50654. }
  50655. return this._size;
  50656. };
  50657. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50658. get: function () {
  50659. return true;
  50660. },
  50661. enumerable: true,
  50662. configurable: true
  50663. });
  50664. RenderTargetTexture.prototype.scale = function (ratio) {
  50665. var newSize = this.getRenderSize() * ratio;
  50666. this.resize(newSize);
  50667. };
  50668. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50669. if (this.isCube) {
  50670. return this._textureMatrix;
  50671. }
  50672. return _super.prototype.getReflectionTextureMatrix.call(this);
  50673. };
  50674. RenderTargetTexture.prototype.resize = function (size) {
  50675. this.releaseInternalTexture();
  50676. var scene = this.getScene();
  50677. if (!scene) {
  50678. return;
  50679. }
  50680. this._processSizeParameter(size);
  50681. if (this.isCube) {
  50682. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50683. }
  50684. else {
  50685. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50686. }
  50687. };
  50688. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50689. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50690. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50691. var scene = this.getScene();
  50692. if (!scene) {
  50693. return;
  50694. }
  50695. var engine = scene.getEngine();
  50696. if (this.useCameraPostProcesses !== undefined) {
  50697. useCameraPostProcess = this.useCameraPostProcesses;
  50698. }
  50699. if (this._waitingRenderList) {
  50700. this.renderList = [];
  50701. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50702. var id = this._waitingRenderList[index];
  50703. var mesh_1 = scene.getMeshByID(id);
  50704. if (mesh_1) {
  50705. this.renderList.push(mesh_1);
  50706. }
  50707. }
  50708. delete this._waitingRenderList;
  50709. }
  50710. // Is predicate defined?
  50711. if (this.renderListPredicate) {
  50712. if (this.renderList) {
  50713. this.renderList.splice(0); // Clear previous renderList
  50714. }
  50715. else {
  50716. this.renderList = [];
  50717. }
  50718. var scene = this.getScene();
  50719. if (!scene) {
  50720. return;
  50721. }
  50722. var sceneMeshes = scene.meshes;
  50723. for (var index = 0; index < sceneMeshes.length; index++) {
  50724. var mesh = sceneMeshes[index];
  50725. if (this.renderListPredicate(mesh)) {
  50726. this.renderList.push(mesh);
  50727. }
  50728. }
  50729. }
  50730. this.onBeforeBindObservable.notifyObservers(this);
  50731. // Set custom projection.
  50732. // Needs to be before binding to prevent changing the aspect ratio.
  50733. var camera;
  50734. if (this.activeCamera) {
  50735. camera = this.activeCamera;
  50736. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50737. if (this.activeCamera !== scene.activeCamera) {
  50738. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50739. }
  50740. }
  50741. else {
  50742. camera = scene.activeCamera;
  50743. if (camera) {
  50744. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50745. }
  50746. }
  50747. // Prepare renderingManager
  50748. this._renderingManager.reset();
  50749. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50750. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50751. var sceneRenderId = scene.getRenderId();
  50752. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50753. var mesh = currentRenderList[meshIndex];
  50754. if (mesh) {
  50755. if (!mesh.isReady()) {
  50756. // Reset _currentRefreshId
  50757. this.resetRefreshCounter();
  50758. continue;
  50759. }
  50760. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50761. var isMasked = void 0;
  50762. if (!this.renderList && camera) {
  50763. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50764. }
  50765. else {
  50766. isMasked = false;
  50767. }
  50768. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50769. mesh._activate(sceneRenderId);
  50770. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50771. var subMesh = mesh.subMeshes[subIndex];
  50772. scene._activeIndices.addCount(subMesh.indexCount, false);
  50773. this._renderingManager.dispatch(subMesh);
  50774. }
  50775. }
  50776. }
  50777. }
  50778. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50779. var particleSystem = scene.particleSystems[particleIndex];
  50780. var emitter = particleSystem.emitter;
  50781. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50782. continue;
  50783. }
  50784. if (currentRenderList.indexOf(emitter) >= 0) {
  50785. this._renderingManager.dispatchParticles(particleSystem);
  50786. }
  50787. }
  50788. if (this.isCube) {
  50789. for (var face = 0; face < 6; face++) {
  50790. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50791. scene.incrementRenderId();
  50792. scene.resetCachedMaterial();
  50793. }
  50794. }
  50795. else {
  50796. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50797. }
  50798. this.onAfterUnbindObservable.notifyObservers(this);
  50799. if (scene.activeCamera) {
  50800. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50801. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50802. }
  50803. engine.setViewport(scene.activeCamera.viewport);
  50804. }
  50805. scene.resetCachedMaterial();
  50806. };
  50807. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50808. var minimum = 128;
  50809. var x = renderDimension * scale;
  50810. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50811. // Ensure we don't exceed the render dimension (while staying POT)
  50812. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50813. };
  50814. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50815. var _this = this;
  50816. var scene = this.getScene();
  50817. if (!scene) {
  50818. return;
  50819. }
  50820. var engine = scene.getEngine();
  50821. if (!this._texture) {
  50822. return;
  50823. }
  50824. // Bind
  50825. if (this._postProcessManager) {
  50826. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50827. }
  50828. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50829. if (this._texture) {
  50830. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50831. }
  50832. }
  50833. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50834. // Clear
  50835. if (this.onClearObservable.hasObservers()) {
  50836. this.onClearObservable.notifyObservers(engine);
  50837. }
  50838. else {
  50839. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50840. }
  50841. if (!this._doNotChangeAspectRatio) {
  50842. scene.updateTransformMatrix(true);
  50843. }
  50844. // Render
  50845. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50846. if (this._postProcessManager) {
  50847. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50848. }
  50849. else if (useCameraPostProcess) {
  50850. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50851. }
  50852. if (!this._doNotChangeAspectRatio) {
  50853. scene.updateTransformMatrix(true);
  50854. }
  50855. // Dump ?
  50856. if (dumpForDebug) {
  50857. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50858. }
  50859. // Unbind
  50860. if (!this.isCube || faceIndex === 5) {
  50861. if (this.isCube) {
  50862. if (faceIndex === 5) {
  50863. engine.generateMipMapsForCubemap(this._texture);
  50864. }
  50865. }
  50866. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50867. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50868. });
  50869. }
  50870. else {
  50871. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50872. }
  50873. };
  50874. /**
  50875. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50876. * This allowed control for front to back rendering or reversly depending of the special needs.
  50877. *
  50878. * @param renderingGroupId The rendering group id corresponding to its index
  50879. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50880. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50881. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50882. */
  50883. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50884. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50885. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50886. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50887. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50888. };
  50889. /**
  50890. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50891. *
  50892. * @param renderingGroupId The rendering group id corresponding to its index
  50893. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50894. */
  50895. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50896. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50897. };
  50898. RenderTargetTexture.prototype.clone = function () {
  50899. var textureSize = this.getSize();
  50900. 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);
  50901. // Base texture
  50902. newTexture.hasAlpha = this.hasAlpha;
  50903. newTexture.level = this.level;
  50904. // RenderTarget Texture
  50905. newTexture.coordinatesMode = this.coordinatesMode;
  50906. if (this.renderList) {
  50907. newTexture.renderList = this.renderList.slice(0);
  50908. }
  50909. return newTexture;
  50910. };
  50911. RenderTargetTexture.prototype.serialize = function () {
  50912. if (!this.name) {
  50913. return null;
  50914. }
  50915. var serializationObject = _super.prototype.serialize.call(this);
  50916. serializationObject.renderTargetSize = this.getRenderSize();
  50917. serializationObject.renderList = [];
  50918. if (this.renderList) {
  50919. for (var index = 0; index < this.renderList.length; index++) {
  50920. serializationObject.renderList.push(this.renderList[index].id);
  50921. }
  50922. }
  50923. return serializationObject;
  50924. };
  50925. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50926. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50927. var objBuffer = this.getInternalTexture();
  50928. var scene = this.getScene();
  50929. if (objBuffer && scene) {
  50930. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50931. }
  50932. };
  50933. RenderTargetTexture.prototype.dispose = function () {
  50934. if (this._postProcessManager) {
  50935. this._postProcessManager.dispose();
  50936. this._postProcessManager = null;
  50937. }
  50938. this.clearPostProcesses(true);
  50939. if (this._resizeObserver) {
  50940. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50941. this._resizeObserver = null;
  50942. }
  50943. this.renderList = null;
  50944. // Remove from custom render targets
  50945. var scene = this.getScene();
  50946. if (!scene) {
  50947. return;
  50948. }
  50949. var index = scene.customRenderTargets.indexOf(this);
  50950. if (index >= 0) {
  50951. scene.customRenderTargets.splice(index, 1);
  50952. }
  50953. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50954. var camera = _a[_i];
  50955. index = camera.customRenderTargets.indexOf(this);
  50956. if (index >= 0) {
  50957. camera.customRenderTargets.splice(index, 1);
  50958. }
  50959. }
  50960. _super.prototype.dispose.call(this);
  50961. };
  50962. RenderTargetTexture.prototype._rebuild = function () {
  50963. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50964. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50965. }
  50966. if (this._postProcessManager) {
  50967. this._postProcessManager._rebuild();
  50968. }
  50969. };
  50970. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50971. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50972. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50973. return RenderTargetTexture;
  50974. }(BABYLON.Texture));
  50975. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50976. })(BABYLON || (BABYLON = {}));
  50977. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50978. var BABYLON;
  50979. (function (BABYLON) {
  50980. ;
  50981. var MultiRenderTarget = /** @class */ (function (_super) {
  50982. __extends(MultiRenderTarget, _super);
  50983. function MultiRenderTarget(name, size, count, scene, options) {
  50984. var _this = this;
  50985. options = options || {};
  50986. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50987. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50988. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50989. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50990. _this._engine = scene.getEngine();
  50991. if (!_this.isSupported) {
  50992. _this.dispose();
  50993. return;
  50994. }
  50995. var types = [];
  50996. var samplingModes = [];
  50997. for (var i = 0; i < count; i++) {
  50998. if (options.types && options.types[i]) {
  50999. types.push(options.types[i]);
  51000. }
  51001. else {
  51002. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  51003. }
  51004. if (options.samplingModes && options.samplingModes[i]) {
  51005. samplingModes.push(options.samplingModes[i]);
  51006. }
  51007. else {
  51008. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51009. }
  51010. }
  51011. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  51012. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  51013. _this._size = size;
  51014. _this._multiRenderTargetOptions = {
  51015. samplingModes: samplingModes,
  51016. generateMipMaps: generateMipMaps,
  51017. generateDepthBuffer: generateDepthBuffer,
  51018. generateStencilBuffer: generateStencilBuffer,
  51019. generateDepthTexture: generateDepthTexture,
  51020. types: types,
  51021. textureCount: count
  51022. };
  51023. _this._createInternalTextures();
  51024. _this._createTextures();
  51025. return _this;
  51026. }
  51027. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  51028. get: function () {
  51029. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  51030. },
  51031. enumerable: true,
  51032. configurable: true
  51033. });
  51034. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  51035. get: function () {
  51036. return this._textures;
  51037. },
  51038. enumerable: true,
  51039. configurable: true
  51040. });
  51041. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  51042. get: function () {
  51043. return this._textures[this._textures.length - 1];
  51044. },
  51045. enumerable: true,
  51046. configurable: true
  51047. });
  51048. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  51049. set: function (wrap) {
  51050. if (this._textures) {
  51051. for (var i = 0; i < this._textures.length; i++) {
  51052. this._textures[i].wrapU = wrap;
  51053. }
  51054. }
  51055. },
  51056. enumerable: true,
  51057. configurable: true
  51058. });
  51059. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  51060. set: function (wrap) {
  51061. if (this._textures) {
  51062. for (var i = 0; i < this._textures.length; i++) {
  51063. this._textures[i].wrapV = wrap;
  51064. }
  51065. }
  51066. },
  51067. enumerable: true,
  51068. configurable: true
  51069. });
  51070. MultiRenderTarget.prototype._rebuild = function () {
  51071. this.releaseInternalTextures();
  51072. this._createInternalTextures();
  51073. for (var i = 0; i < this._internalTextures.length; i++) {
  51074. var texture = this._textures[i];
  51075. texture._texture = this._internalTextures[i];
  51076. }
  51077. // Keeps references to frame buffer and stencil/depth buffer
  51078. this._texture = this._internalTextures[0];
  51079. };
  51080. MultiRenderTarget.prototype._createInternalTextures = function () {
  51081. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  51082. };
  51083. MultiRenderTarget.prototype._createTextures = function () {
  51084. this._textures = [];
  51085. for (var i = 0; i < this._internalTextures.length; i++) {
  51086. var texture = new BABYLON.Texture(null, this.getScene());
  51087. texture._texture = this._internalTextures[i];
  51088. this._textures.push(texture);
  51089. }
  51090. // Keeps references to frame buffer and stencil/depth buffer
  51091. this._texture = this._internalTextures[0];
  51092. };
  51093. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  51094. get: function () {
  51095. return this._samples;
  51096. },
  51097. set: function (value) {
  51098. if (this._samples === value) {
  51099. return;
  51100. }
  51101. for (var i = 0; i < this._internalTextures.length; i++) {
  51102. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  51103. }
  51104. },
  51105. enumerable: true,
  51106. configurable: true
  51107. });
  51108. MultiRenderTarget.prototype.resize = function (size) {
  51109. this.releaseInternalTextures();
  51110. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  51111. this._createInternalTextures();
  51112. };
  51113. MultiRenderTarget.prototype.dispose = function () {
  51114. this.releaseInternalTextures();
  51115. _super.prototype.dispose.call(this);
  51116. };
  51117. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  51118. if (!this._internalTextures) {
  51119. return;
  51120. }
  51121. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  51122. if (this._internalTextures[i] !== undefined) {
  51123. this._internalTextures[i].dispose();
  51124. this._internalTextures.splice(i, 1);
  51125. }
  51126. }
  51127. };
  51128. return MultiRenderTarget;
  51129. }(BABYLON.RenderTargetTexture));
  51130. BABYLON.MultiRenderTarget = MultiRenderTarget;
  51131. })(BABYLON || (BABYLON = {}));
  51132. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  51133. var BABYLON;
  51134. (function (BABYLON) {
  51135. var MirrorTexture = /** @class */ (function (_super) {
  51136. __extends(MirrorTexture, _super);
  51137. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  51138. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51140. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51141. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  51142. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  51143. _this._transformMatrix = BABYLON.Matrix.Zero();
  51144. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  51145. _this._adaptiveBlurKernel = 0;
  51146. _this._blurKernelX = 0;
  51147. _this._blurKernelY = 0;
  51148. _this._blurRatio = 1.0;
  51149. _this.ignoreCameraViewport = true;
  51150. _this.onBeforeRenderObservable.add(function () {
  51151. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  51152. _this._savedViewMatrix = scene.getViewMatrix();
  51153. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  51154. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  51155. scene.clipPlane = _this.mirrorPlane;
  51156. scene.getEngine().cullBackFaces = false;
  51157. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  51158. });
  51159. _this.onAfterRenderObservable.add(function () {
  51160. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  51161. scene.getEngine().cullBackFaces = true;
  51162. scene._mirroredCameraPosition = null;
  51163. delete scene.clipPlane;
  51164. });
  51165. return _this;
  51166. }
  51167. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  51168. get: function () {
  51169. return this._blurRatio;
  51170. },
  51171. set: function (value) {
  51172. if (this._blurRatio === value) {
  51173. return;
  51174. }
  51175. this._blurRatio = value;
  51176. this._preparePostProcesses();
  51177. },
  51178. enumerable: true,
  51179. configurable: true
  51180. });
  51181. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  51182. set: function (value) {
  51183. this._adaptiveBlurKernel = value;
  51184. this._autoComputeBlurKernel();
  51185. },
  51186. enumerable: true,
  51187. configurable: true
  51188. });
  51189. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  51190. set: function (value) {
  51191. this.blurKernelX = value;
  51192. this.blurKernelY = value;
  51193. },
  51194. enumerable: true,
  51195. configurable: true
  51196. });
  51197. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  51198. get: function () {
  51199. return this._blurKernelX;
  51200. },
  51201. set: function (value) {
  51202. if (this._blurKernelX === value) {
  51203. return;
  51204. }
  51205. this._blurKernelX = value;
  51206. this._preparePostProcesses();
  51207. },
  51208. enumerable: true,
  51209. configurable: true
  51210. });
  51211. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  51212. get: function () {
  51213. return this._blurKernelY;
  51214. },
  51215. set: function (value) {
  51216. if (this._blurKernelY === value) {
  51217. return;
  51218. }
  51219. this._blurKernelY = value;
  51220. this._preparePostProcesses();
  51221. },
  51222. enumerable: true,
  51223. configurable: true
  51224. });
  51225. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  51226. var engine = this.getScene().getEngine();
  51227. var dw = this.getRenderWidth() / engine.getRenderWidth();
  51228. var dh = this.getRenderHeight() / engine.getRenderHeight();
  51229. this.blurKernelX = this._adaptiveBlurKernel * dw;
  51230. this.blurKernelY = this._adaptiveBlurKernel * dh;
  51231. };
  51232. MirrorTexture.prototype._onRatioRescale = function () {
  51233. if (this._sizeRatio) {
  51234. this.resize(this._initialSizeParameter);
  51235. if (!this._adaptiveBlurKernel) {
  51236. this._preparePostProcesses();
  51237. }
  51238. }
  51239. if (this._adaptiveBlurKernel) {
  51240. this._autoComputeBlurKernel();
  51241. }
  51242. };
  51243. MirrorTexture.prototype._preparePostProcesses = function () {
  51244. this.clearPostProcesses(true);
  51245. if (this._blurKernelX && this._blurKernelY) {
  51246. var engine = this.getScene().getEngine();
  51247. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51248. 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);
  51249. this._blurX.autoClear = false;
  51250. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  51251. this._blurX.outputTexture = this._texture;
  51252. }
  51253. else {
  51254. this._blurX.alwaysForcePOT = true;
  51255. }
  51256. 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);
  51257. this._blurY.autoClear = false;
  51258. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  51259. this.addPostProcess(this._blurX);
  51260. this.addPostProcess(this._blurY);
  51261. }
  51262. else {
  51263. if (this._blurY) {
  51264. this.removePostProcess(this._blurY);
  51265. this._blurY.dispose();
  51266. this._blurY = null;
  51267. }
  51268. if (this._blurX) {
  51269. this.removePostProcess(this._blurX);
  51270. this._blurX.dispose();
  51271. this._blurX = null;
  51272. }
  51273. }
  51274. };
  51275. MirrorTexture.prototype.clone = function () {
  51276. var scene = this.getScene();
  51277. if (!scene) {
  51278. return this;
  51279. }
  51280. var textureSize = this.getSize();
  51281. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  51282. // Base texture
  51283. newTexture.hasAlpha = this.hasAlpha;
  51284. newTexture.level = this.level;
  51285. // Mirror Texture
  51286. newTexture.mirrorPlane = this.mirrorPlane.clone();
  51287. if (this.renderList) {
  51288. newTexture.renderList = this.renderList.slice(0);
  51289. }
  51290. return newTexture;
  51291. };
  51292. MirrorTexture.prototype.serialize = function () {
  51293. if (!this.name) {
  51294. return null;
  51295. }
  51296. var serializationObject = _super.prototype.serialize.call(this);
  51297. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  51298. return serializationObject;
  51299. };
  51300. return MirrorTexture;
  51301. }(BABYLON.RenderTargetTexture));
  51302. BABYLON.MirrorTexture = MirrorTexture;
  51303. })(BABYLON || (BABYLON = {}));
  51304. //# sourceMappingURL=babylon.mirrorTexture.js.map
  51305. var BABYLON;
  51306. (function (BABYLON) {
  51307. /**
  51308. * Creates a refraction texture used by refraction channel of the standard material.
  51309. * @param name the texture name
  51310. * @param size size of the underlying texture
  51311. * @param scene root scene
  51312. */
  51313. var RefractionTexture = /** @class */ (function (_super) {
  51314. __extends(RefractionTexture, _super);
  51315. function RefractionTexture(name, size, scene, generateMipMaps) {
  51316. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  51317. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  51318. _this.depth = 2.0;
  51319. _this.onBeforeRenderObservable.add(function () {
  51320. scene.clipPlane = _this.refractionPlane;
  51321. });
  51322. _this.onAfterRenderObservable.add(function () {
  51323. delete scene.clipPlane;
  51324. });
  51325. return _this;
  51326. }
  51327. RefractionTexture.prototype.clone = function () {
  51328. var scene = this.getScene();
  51329. if (!scene) {
  51330. return this;
  51331. }
  51332. var textureSize = this.getSize();
  51333. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  51334. // Base texture
  51335. newTexture.hasAlpha = this.hasAlpha;
  51336. newTexture.level = this.level;
  51337. // Refraction Texture
  51338. newTexture.refractionPlane = this.refractionPlane.clone();
  51339. if (this.renderList) {
  51340. newTexture.renderList = this.renderList.slice(0);
  51341. }
  51342. newTexture.depth = this.depth;
  51343. return newTexture;
  51344. };
  51345. RefractionTexture.prototype.serialize = function () {
  51346. if (!this.name) {
  51347. return null;
  51348. }
  51349. var serializationObject = _super.prototype.serialize.call(this);
  51350. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  51351. serializationObject.depth = this.depth;
  51352. return serializationObject;
  51353. };
  51354. return RefractionTexture;
  51355. }(BABYLON.RenderTargetTexture));
  51356. BABYLON.RefractionTexture = RefractionTexture;
  51357. })(BABYLON || (BABYLON = {}));
  51358. //# sourceMappingURL=babylon.refractionTexture.js.map
  51359. var BABYLON;
  51360. (function (BABYLON) {
  51361. var DynamicTexture = /** @class */ (function (_super) {
  51362. __extends(DynamicTexture, _super);
  51363. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  51364. if (scene === void 0) { scene = null; }
  51365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51366. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51367. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  51368. _this.name = name;
  51369. _this._engine = _this.getScene().getEngine();
  51370. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51371. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51372. _this._generateMipMaps = generateMipMaps;
  51373. if (options.getContext) {
  51374. _this._canvas = options;
  51375. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51376. }
  51377. else {
  51378. _this._canvas = document.createElement("canvas");
  51379. if (options.width) {
  51380. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  51381. }
  51382. else {
  51383. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  51384. }
  51385. }
  51386. var textureSize = _this.getSize();
  51387. _this._canvas.width = textureSize.width;
  51388. _this._canvas.height = textureSize.height;
  51389. _this._context = _this._canvas.getContext("2d");
  51390. return _this;
  51391. }
  51392. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  51393. get: function () {
  51394. return true;
  51395. },
  51396. enumerable: true,
  51397. configurable: true
  51398. });
  51399. DynamicTexture.prototype._recreate = function (textureSize) {
  51400. this._canvas.width = textureSize.width;
  51401. this._canvas.height = textureSize.height;
  51402. this.releaseInternalTexture();
  51403. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  51404. };
  51405. DynamicTexture.prototype.scale = function (ratio) {
  51406. var textureSize = this.getSize();
  51407. textureSize.width *= ratio;
  51408. textureSize.height *= ratio;
  51409. this._recreate(textureSize);
  51410. };
  51411. DynamicTexture.prototype.scaleTo = function (width, height) {
  51412. var textureSize = this.getSize();
  51413. textureSize.width = width;
  51414. textureSize.height = height;
  51415. this._recreate(textureSize);
  51416. };
  51417. DynamicTexture.prototype.getContext = function () {
  51418. return this._context;
  51419. };
  51420. DynamicTexture.prototype.clear = function () {
  51421. var size = this.getSize();
  51422. this._context.fillRect(0, 0, size.width, size.height);
  51423. };
  51424. DynamicTexture.prototype.update = function (invertY) {
  51425. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  51426. };
  51427. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  51428. if (update === void 0) { update = true; }
  51429. var size = this.getSize();
  51430. if (clearColor) {
  51431. this._context.fillStyle = clearColor;
  51432. this._context.fillRect(0, 0, size.width, size.height);
  51433. }
  51434. this._context.font = font;
  51435. if (x === null || x === undefined) {
  51436. var textSize = this._context.measureText(text);
  51437. x = (size.width - textSize.width) / 2;
  51438. }
  51439. if (y === null || y === undefined) {
  51440. var fontSize = parseInt((font.replace(/\D/g, '')));
  51441. ;
  51442. y = (size.height / 2) + (fontSize / 3.65);
  51443. }
  51444. this._context.fillStyle = color;
  51445. this._context.fillText(text, x, y);
  51446. if (update) {
  51447. this.update(invertY);
  51448. }
  51449. };
  51450. DynamicTexture.prototype.clone = function () {
  51451. var scene = this.getScene();
  51452. if (!scene) {
  51453. return this;
  51454. }
  51455. var textureSize = this.getSize();
  51456. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  51457. // Base texture
  51458. newTexture.hasAlpha = this.hasAlpha;
  51459. newTexture.level = this.level;
  51460. // Dynamic Texture
  51461. newTexture.wrapU = this.wrapU;
  51462. newTexture.wrapV = this.wrapV;
  51463. return newTexture;
  51464. };
  51465. DynamicTexture.prototype._rebuild = function () {
  51466. this.update();
  51467. };
  51468. return DynamicTexture;
  51469. }(BABYLON.Texture));
  51470. BABYLON.DynamicTexture = DynamicTexture;
  51471. })(BABYLON || (BABYLON = {}));
  51472. //# sourceMappingURL=babylon.dynamicTexture.js.map
  51473. var BABYLON;
  51474. (function (BABYLON) {
  51475. var VideoTexture = /** @class */ (function (_super) {
  51476. __extends(VideoTexture, _super);
  51477. /**
  51478. * Creates a video texture.
  51479. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  51480. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  51481. * @param {BABYLON.Scene} scene is obviously the current scene.
  51482. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  51483. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  51484. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  51485. */
  51486. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  51487. if (generateMipMaps === void 0) { generateMipMaps = false; }
  51488. if (invertY === void 0) { invertY = false; }
  51489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51490. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51491. _this._autoLaunch = true;
  51492. var urls = null;
  51493. _this.name = name;
  51494. if (urlsOrVideo instanceof HTMLVideoElement) {
  51495. _this.video = urlsOrVideo;
  51496. }
  51497. else {
  51498. urls = urlsOrVideo;
  51499. _this.video = document.createElement("video");
  51500. _this.video.autoplay = false;
  51501. _this.video.loop = true;
  51502. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  51503. }
  51504. _this._engine = _this.getScene().getEngine();
  51505. _this._generateMipMaps = generateMipMaps;
  51506. _this._samplingMode = samplingMode;
  51507. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51508. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51509. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51510. }
  51511. else {
  51512. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51513. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51514. _this._generateMipMaps = false;
  51515. }
  51516. if (urls) {
  51517. _this.video.addEventListener("canplay", function () {
  51518. _this._createTexture();
  51519. });
  51520. urls.forEach(function (url) {
  51521. var source = document.createElement("source");
  51522. source.src = url;
  51523. _this.video.appendChild(source);
  51524. });
  51525. }
  51526. else {
  51527. _this._createTexture();
  51528. }
  51529. _this._lastUpdate = BABYLON.Tools.Now;
  51530. return _this;
  51531. }
  51532. VideoTexture.prototype.__setTextureReady = function () {
  51533. if (this._texture) {
  51534. this._texture.isReady = true;
  51535. }
  51536. };
  51537. VideoTexture.prototype._createTexture = function () {
  51538. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51539. if (this._autoLaunch) {
  51540. this._autoLaunch = false;
  51541. this.video.play();
  51542. }
  51543. this._setTextureReady = this.__setTextureReady.bind(this);
  51544. this.video.addEventListener("playing", this._setTextureReady);
  51545. };
  51546. VideoTexture.prototype._rebuild = function () {
  51547. this.update();
  51548. };
  51549. VideoTexture.prototype.update = function () {
  51550. var now = BABYLON.Tools.Now;
  51551. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51552. return false;
  51553. }
  51554. this._lastUpdate = now;
  51555. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51556. return true;
  51557. };
  51558. VideoTexture.prototype.dispose = function () {
  51559. _super.prototype.dispose.call(this);
  51560. this.video.removeEventListener("playing", this._setTextureReady);
  51561. };
  51562. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51563. var video = document.createElement("video");
  51564. var constraintsDeviceId;
  51565. if (constraints && constraints.deviceId) {
  51566. constraintsDeviceId = {
  51567. exact: constraints.deviceId
  51568. };
  51569. }
  51570. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51571. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51572. if (navigator.getUserMedia) {
  51573. navigator.getUserMedia({
  51574. video: {
  51575. deviceId: constraintsDeviceId,
  51576. width: {
  51577. min: (constraints && constraints.minWidth) || 256,
  51578. max: (constraints && constraints.maxWidth) || 640
  51579. },
  51580. height: {
  51581. min: (constraints && constraints.minHeight) || 256,
  51582. max: (constraints && constraints.maxHeight) || 480
  51583. }
  51584. }
  51585. }, function (stream) {
  51586. if (video.mozSrcObject !== undefined) {
  51587. video.mozSrcObject = stream;
  51588. }
  51589. else {
  51590. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51591. }
  51592. video.play();
  51593. if (onReady) {
  51594. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51595. }
  51596. }, function (e) {
  51597. BABYLON.Tools.Error(e.name);
  51598. });
  51599. }
  51600. };
  51601. return VideoTexture;
  51602. }(BABYLON.Texture));
  51603. BABYLON.VideoTexture = VideoTexture;
  51604. })(BABYLON || (BABYLON = {}));
  51605. //# sourceMappingURL=babylon.videoTexture.js.map
  51606. var BABYLON;
  51607. (function (BABYLON) {
  51608. var RawTexture = /** @class */ (function (_super) {
  51609. __extends(RawTexture, _super);
  51610. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  51611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51612. if (invertY === void 0) { invertY = false; }
  51613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51614. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51615. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51616. _this.format = format;
  51617. _this._engine = scene.getEngine();
  51618. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  51619. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51620. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51621. return _this;
  51622. }
  51623. RawTexture.prototype.update = function (data) {
  51624. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  51625. };
  51626. // Statics
  51627. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51628. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51629. if (invertY === void 0) { invertY = false; }
  51630. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51631. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51632. };
  51633. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51634. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51635. if (invertY === void 0) { invertY = false; }
  51636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51637. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51638. };
  51639. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51640. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51641. if (invertY === void 0) { invertY = false; }
  51642. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51643. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51644. };
  51645. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51646. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51647. if (invertY === void 0) { invertY = false; }
  51648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51649. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51650. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  51651. };
  51652. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  51653. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51654. if (invertY === void 0) { invertY = false; }
  51655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51656. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51657. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  51658. };
  51659. return RawTexture;
  51660. }(BABYLON.Texture));
  51661. BABYLON.RawTexture = RawTexture;
  51662. })(BABYLON || (BABYLON = {}));
  51663. //# sourceMappingURL=babylon.rawTexture.js.map
  51664. var BABYLON;
  51665. (function (BABYLON) {
  51666. var PostProcess = /** @class */ (function () {
  51667. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51668. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51669. if (defines === void 0) { defines = null; }
  51670. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51671. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51672. if (blockCompilation === void 0) { blockCompilation = false; }
  51673. this.name = name;
  51674. this.width = -1;
  51675. this.height = -1;
  51676. this.autoClear = true;
  51677. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51678. this.animations = new Array();
  51679. /*
  51680. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51681. Can only be used on a single postprocess or on the last one of a chain.
  51682. */
  51683. this.enablePixelPerfectMode = false;
  51684. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51685. this.alwaysForcePOT = false;
  51686. this.samples = 1;
  51687. this.adaptScaleToCurrentViewport = false;
  51688. this._reusable = false;
  51689. this._textures = new BABYLON.SmartArray(2);
  51690. this._currentRenderTextureInd = 0;
  51691. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51692. this._texelSize = BABYLON.Vector2.Zero();
  51693. // Events
  51694. /**
  51695. * An event triggered when the postprocess is activated.
  51696. * @type {BABYLON.Observable}
  51697. */
  51698. this.onActivateObservable = new BABYLON.Observable();
  51699. /**
  51700. * An event triggered when the postprocess changes its size.
  51701. * @type {BABYLON.Observable}
  51702. */
  51703. this.onSizeChangedObservable = new BABYLON.Observable();
  51704. /**
  51705. * An event triggered when the postprocess applies its effect.
  51706. * @type {BABYLON.Observable}
  51707. */
  51708. this.onApplyObservable = new BABYLON.Observable();
  51709. /**
  51710. * An event triggered before rendering the postprocess
  51711. * @type {BABYLON.Observable}
  51712. */
  51713. this.onBeforeRenderObservable = new BABYLON.Observable();
  51714. /**
  51715. * An event triggered after rendering the postprocess
  51716. * @type {BABYLON.Observable}
  51717. */
  51718. this.onAfterRenderObservable = new BABYLON.Observable();
  51719. if (camera != null) {
  51720. this._camera = camera;
  51721. this._scene = camera.getScene();
  51722. camera.attachPostProcess(this);
  51723. this._engine = this._scene.getEngine();
  51724. this._scene.postProcesses.push(this);
  51725. }
  51726. else if (engine) {
  51727. this._engine = engine;
  51728. this._engine.postProcesses.push(this);
  51729. }
  51730. this._options = options;
  51731. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51732. this._reusable = reusable || false;
  51733. this._textureType = textureType;
  51734. this._samplers = samplers || [];
  51735. this._samplers.push("textureSampler");
  51736. this._fragmentUrl = fragmentUrl;
  51737. this._vertexUrl = vertexUrl;
  51738. this._parameters = parameters || [];
  51739. this._parameters.push("scale");
  51740. this._indexParameters = indexParameters;
  51741. if (!blockCompilation) {
  51742. this.updateEffect(defines);
  51743. }
  51744. }
  51745. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51746. set: function (callback) {
  51747. if (this._onActivateObserver) {
  51748. this.onActivateObservable.remove(this._onActivateObserver);
  51749. }
  51750. if (callback) {
  51751. this._onActivateObserver = this.onActivateObservable.add(callback);
  51752. }
  51753. },
  51754. enumerable: true,
  51755. configurable: true
  51756. });
  51757. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51758. set: function (callback) {
  51759. if (this._onSizeChangedObserver) {
  51760. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51761. }
  51762. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51763. },
  51764. enumerable: true,
  51765. configurable: true
  51766. });
  51767. Object.defineProperty(PostProcess.prototype, "onApply", {
  51768. set: function (callback) {
  51769. if (this._onApplyObserver) {
  51770. this.onApplyObservable.remove(this._onApplyObserver);
  51771. }
  51772. this._onApplyObserver = this.onApplyObservable.add(callback);
  51773. },
  51774. enumerable: true,
  51775. configurable: true
  51776. });
  51777. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51778. set: function (callback) {
  51779. if (this._onBeforeRenderObserver) {
  51780. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51781. }
  51782. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51783. },
  51784. enumerable: true,
  51785. configurable: true
  51786. });
  51787. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51788. set: function (callback) {
  51789. if (this._onAfterRenderObserver) {
  51790. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51791. }
  51792. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51793. },
  51794. enumerable: true,
  51795. configurable: true
  51796. });
  51797. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51798. get: function () {
  51799. return this._textures.data[this._currentRenderTextureInd];
  51800. },
  51801. set: function (value) {
  51802. this._forcedOutputTexture = value;
  51803. },
  51804. enumerable: true,
  51805. configurable: true
  51806. });
  51807. PostProcess.prototype.getCamera = function () {
  51808. return this._camera;
  51809. };
  51810. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51811. get: function () {
  51812. if (this._shareOutputWithPostProcess) {
  51813. return this._shareOutputWithPostProcess.texelSize;
  51814. }
  51815. if (this._forcedOutputTexture) {
  51816. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51817. }
  51818. return this._texelSize;
  51819. },
  51820. enumerable: true,
  51821. configurable: true
  51822. });
  51823. PostProcess.prototype.getEngine = function () {
  51824. return this._engine;
  51825. };
  51826. PostProcess.prototype.getEffect = function () {
  51827. return this._effect;
  51828. };
  51829. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51830. this._disposeTextures();
  51831. this._shareOutputWithPostProcess = postProcess;
  51832. return this;
  51833. };
  51834. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51835. if (defines === void 0) { defines = null; }
  51836. if (uniforms === void 0) { uniforms = null; }
  51837. if (samplers === void 0) { samplers = null; }
  51838. 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);
  51839. };
  51840. PostProcess.prototype.isReusable = function () {
  51841. return this._reusable;
  51842. };
  51843. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51844. PostProcess.prototype.markTextureDirty = function () {
  51845. this.width = -1;
  51846. };
  51847. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51848. var _this = this;
  51849. if (sourceTexture === void 0) { sourceTexture = null; }
  51850. camera = camera || this._camera;
  51851. var scene = camera.getScene();
  51852. var engine = scene.getEngine();
  51853. var maxSize = engine.getCaps().maxTextureSize;
  51854. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51855. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51856. var desiredWidth = (this._options.width || requiredWidth);
  51857. var desiredHeight = this._options.height || requiredHeight;
  51858. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51859. if (this.adaptScaleToCurrentViewport) {
  51860. var currentViewport = engine.currentViewport;
  51861. if (currentViewport) {
  51862. desiredWidth *= currentViewport.width;
  51863. desiredHeight *= currentViewport.height;
  51864. }
  51865. }
  51866. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51867. if (!this._options.width) {
  51868. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51869. }
  51870. if (!this._options.height) {
  51871. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51872. }
  51873. }
  51874. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51875. if (this._textures.length > 0) {
  51876. for (var i = 0; i < this._textures.length; i++) {
  51877. this._engine._releaseTexture(this._textures.data[i]);
  51878. }
  51879. this._textures.reset();
  51880. }
  51881. this.width = desiredWidth;
  51882. this.height = desiredHeight;
  51883. var textureSize = { width: this.width, height: this.height };
  51884. var textureOptions = {
  51885. generateMipMaps: false,
  51886. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51887. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51888. samplingMode: this.renderTargetSamplingMode,
  51889. type: this._textureType
  51890. };
  51891. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51892. if (this._reusable) {
  51893. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51894. }
  51895. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51896. this.onSizeChangedObservable.notifyObservers(this);
  51897. }
  51898. this._textures.forEach(function (texture) {
  51899. if (texture.samples !== _this.samples) {
  51900. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51901. }
  51902. });
  51903. }
  51904. var target;
  51905. if (this._shareOutputWithPostProcess) {
  51906. target = this._shareOutputWithPostProcess.outputTexture;
  51907. }
  51908. else if (this._forcedOutputTexture) {
  51909. target = this._forcedOutputTexture;
  51910. this.width = this._forcedOutputTexture.width;
  51911. this.height = this._forcedOutputTexture.height;
  51912. }
  51913. else {
  51914. target = this.outputTexture;
  51915. }
  51916. if (this.enablePixelPerfectMode) {
  51917. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51918. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51919. }
  51920. else {
  51921. this._scaleRatio.copyFromFloats(1, 1);
  51922. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51923. }
  51924. this.onActivateObservable.notifyObservers(camera);
  51925. // Clear
  51926. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51927. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51928. }
  51929. if (this._reusable) {
  51930. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51931. }
  51932. };
  51933. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51934. get: function () {
  51935. return this._effect.isSupported;
  51936. },
  51937. enumerable: true,
  51938. configurable: true
  51939. });
  51940. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51941. get: function () {
  51942. if (this._shareOutputWithPostProcess) {
  51943. return this._shareOutputWithPostProcess.aspectRatio;
  51944. }
  51945. if (this._forcedOutputTexture) {
  51946. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51947. }
  51948. return this.width / this.height;
  51949. },
  51950. enumerable: true,
  51951. configurable: true
  51952. });
  51953. PostProcess.prototype.apply = function () {
  51954. // Check
  51955. if (!this._effect || !this._effect.isReady())
  51956. return null;
  51957. // States
  51958. this._engine.enableEffect(this._effect);
  51959. this._engine.setState(false);
  51960. this._engine.setDepthBuffer(false);
  51961. this._engine.setDepthWrite(false);
  51962. // Alpha
  51963. this._engine.setAlphaMode(this.alphaMode);
  51964. if (this.alphaConstants) {
  51965. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51966. }
  51967. // Texture
  51968. var source;
  51969. if (this._shareOutputWithPostProcess) {
  51970. source = this._shareOutputWithPostProcess.outputTexture;
  51971. }
  51972. else if (this._forcedOutputTexture) {
  51973. source = this._forcedOutputTexture;
  51974. }
  51975. else {
  51976. source = this.outputTexture;
  51977. }
  51978. this._effect._bindTexture("textureSampler", source);
  51979. // Parameters
  51980. this._effect.setVector2("scale", this._scaleRatio);
  51981. this.onApplyObservable.notifyObservers(this._effect);
  51982. return this._effect;
  51983. };
  51984. PostProcess.prototype._disposeTextures = function () {
  51985. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51986. return;
  51987. }
  51988. if (this._textures.length > 0) {
  51989. for (var i = 0; i < this._textures.length; i++) {
  51990. this._engine._releaseTexture(this._textures.data[i]);
  51991. }
  51992. }
  51993. this._textures.dispose();
  51994. };
  51995. PostProcess.prototype.dispose = function (camera) {
  51996. camera = camera || this._camera;
  51997. this._disposeTextures();
  51998. if (this._scene) {
  51999. var index_1 = this._scene.postProcesses.indexOf(this);
  52000. if (index_1 !== -1) {
  52001. this._scene.postProcesses.splice(index_1, 1);
  52002. }
  52003. }
  52004. else {
  52005. var index_2 = this._engine.postProcesses.indexOf(this);
  52006. if (index_2 !== -1) {
  52007. this._engine.postProcesses.splice(index_2, 1);
  52008. }
  52009. }
  52010. if (!camera) {
  52011. return;
  52012. }
  52013. camera.detachPostProcess(this);
  52014. var index = camera._postProcesses.indexOf(this);
  52015. if (index === 0 && camera._postProcesses.length > 0) {
  52016. this._camera._postProcesses[0].markTextureDirty();
  52017. }
  52018. this.onActivateObservable.clear();
  52019. this.onAfterRenderObservable.clear();
  52020. this.onApplyObservable.clear();
  52021. this.onBeforeRenderObservable.clear();
  52022. this.onSizeChangedObservable.clear();
  52023. };
  52024. return PostProcess;
  52025. }());
  52026. BABYLON.PostProcess = PostProcess;
  52027. })(BABYLON || (BABYLON = {}));
  52028. //# sourceMappingURL=babylon.postProcess.js.map
  52029. var BABYLON;
  52030. (function (BABYLON) {
  52031. var PassPostProcess = /** @class */ (function (_super) {
  52032. __extends(PassPostProcess, _super);
  52033. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52034. if (camera === void 0) { camera = null; }
  52035. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52036. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  52037. }
  52038. return PassPostProcess;
  52039. }(BABYLON.PostProcess));
  52040. BABYLON.PassPostProcess = PassPostProcess;
  52041. })(BABYLON || (BABYLON = {}));
  52042. //# sourceMappingURL=babylon.passPostProcess.js.map
  52043. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52044. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52045. s = arguments[i];
  52046. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52047. t[p] = s[p];
  52048. }
  52049. return t;
  52050. };
  52051. var BABYLON;
  52052. (function (BABYLON) {
  52053. var ShadowGenerator = /** @class */ (function () {
  52054. /**
  52055. * Creates a ShadowGenerator object.
  52056. * A ShadowGenerator is the required tool to use the shadows.
  52057. * Each light casting shadows needs to use its own ShadowGenerator.
  52058. * Required parameters :
  52059. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  52060. * - `light`: the light object generating the shadows.
  52061. * - `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.
  52062. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  52063. */
  52064. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  52065. // Members
  52066. this._bias = 0.00005;
  52067. this._blurBoxOffset = 1;
  52068. this._blurScale = 2;
  52069. this._blurKernel = 1;
  52070. this._useKernelBlur = false;
  52071. this._filter = ShadowGenerator.FILTER_NONE;
  52072. this._darkness = 0;
  52073. this._transparencyShadow = false;
  52074. /**
  52075. * Controls the extent to which the shadows fade out at the edge of the frustum
  52076. * Used only by directionals and spots
  52077. */
  52078. this.frustumEdgeFalloff = 0;
  52079. this.forceBackFacesOnly = false;
  52080. this._lightDirection = BABYLON.Vector3.Zero();
  52081. this._viewMatrix = BABYLON.Matrix.Zero();
  52082. this._projectionMatrix = BABYLON.Matrix.Zero();
  52083. this._transformMatrix = BABYLON.Matrix.Zero();
  52084. this._currentFaceIndex = 0;
  52085. this._currentFaceIndexCache = 0;
  52086. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  52087. this._mapSize = mapSize;
  52088. this._light = light;
  52089. this._scene = light.getScene();
  52090. light._shadowGenerator = this;
  52091. // Texture type fallback from float to int if not supported.
  52092. var caps = this._scene.getEngine().getCaps();
  52093. if (!useFullFloatFirst) {
  52094. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52095. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52096. }
  52097. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52098. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52099. }
  52100. else {
  52101. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52102. }
  52103. }
  52104. else {
  52105. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52106. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52107. }
  52108. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52109. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52110. }
  52111. else {
  52112. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52113. }
  52114. }
  52115. this._initializeGenerator();
  52116. }
  52117. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  52118. // Static
  52119. get: function () {
  52120. return ShadowGenerator._FILTER_NONE;
  52121. },
  52122. enumerable: true,
  52123. configurable: true
  52124. });
  52125. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  52126. get: function () {
  52127. return ShadowGenerator._FILTER_POISSONSAMPLING;
  52128. },
  52129. enumerable: true,
  52130. configurable: true
  52131. });
  52132. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  52133. get: function () {
  52134. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  52135. },
  52136. enumerable: true,
  52137. configurable: true
  52138. });
  52139. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  52140. get: function () {
  52141. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  52142. },
  52143. enumerable: true,
  52144. configurable: true
  52145. });
  52146. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  52147. get: function () {
  52148. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52149. },
  52150. enumerable: true,
  52151. configurable: true
  52152. });
  52153. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  52154. get: function () {
  52155. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52156. },
  52157. enumerable: true,
  52158. configurable: true
  52159. });
  52160. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  52161. get: function () {
  52162. return this._bias;
  52163. },
  52164. set: function (bias) {
  52165. this._bias = bias;
  52166. },
  52167. enumerable: true,
  52168. configurable: true
  52169. });
  52170. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  52171. get: function () {
  52172. return this._blurBoxOffset;
  52173. },
  52174. set: function (value) {
  52175. if (this._blurBoxOffset === value) {
  52176. return;
  52177. }
  52178. this._blurBoxOffset = value;
  52179. this._disposeBlurPostProcesses();
  52180. },
  52181. enumerable: true,
  52182. configurable: true
  52183. });
  52184. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  52185. get: function () {
  52186. return this._blurScale;
  52187. },
  52188. set: function (value) {
  52189. if (this._blurScale === value) {
  52190. return;
  52191. }
  52192. this._blurScale = value;
  52193. this._disposeBlurPostProcesses();
  52194. },
  52195. enumerable: true,
  52196. configurable: true
  52197. });
  52198. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  52199. get: function () {
  52200. return this._blurKernel;
  52201. },
  52202. set: function (value) {
  52203. if (this._blurKernel === value) {
  52204. return;
  52205. }
  52206. this._blurKernel = value;
  52207. this._disposeBlurPostProcesses();
  52208. },
  52209. enumerable: true,
  52210. configurable: true
  52211. });
  52212. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  52213. get: function () {
  52214. return this._useKernelBlur;
  52215. },
  52216. set: function (value) {
  52217. if (this._useKernelBlur === value) {
  52218. return;
  52219. }
  52220. this._useKernelBlur = value;
  52221. this._disposeBlurPostProcesses();
  52222. },
  52223. enumerable: true,
  52224. configurable: true
  52225. });
  52226. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  52227. get: function () {
  52228. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  52229. },
  52230. set: function (value) {
  52231. this._depthScale = value;
  52232. },
  52233. enumerable: true,
  52234. configurable: true
  52235. });
  52236. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  52237. get: function () {
  52238. return this._filter;
  52239. },
  52240. set: function (value) {
  52241. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  52242. if (this._light.needCube()) {
  52243. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52244. this.useExponentialShadowMap = true;
  52245. return;
  52246. }
  52247. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52248. this.useCloseExponentialShadowMap = true;
  52249. return;
  52250. }
  52251. }
  52252. if (this._filter === value) {
  52253. return;
  52254. }
  52255. this._filter = value;
  52256. this._disposeBlurPostProcesses();
  52257. this._applyFilterValues();
  52258. this._light._markMeshesAsLightDirty();
  52259. },
  52260. enumerable: true,
  52261. configurable: true
  52262. });
  52263. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  52264. get: function () {
  52265. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  52266. },
  52267. set: function (value) {
  52268. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  52269. return;
  52270. }
  52271. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  52272. },
  52273. enumerable: true,
  52274. configurable: true
  52275. });
  52276. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  52277. get: function () {
  52278. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52279. return this.useExponentialShadowMap;
  52280. },
  52281. set: function (value) {
  52282. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  52283. this.useExponentialShadowMap = value;
  52284. },
  52285. enumerable: true,
  52286. configurable: true
  52287. });
  52288. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  52289. get: function () {
  52290. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52291. return this.useBlurExponentialShadowMap;
  52292. },
  52293. set: function (value) {
  52294. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  52295. this.useBlurExponentialShadowMap = value;
  52296. },
  52297. enumerable: true,
  52298. configurable: true
  52299. });
  52300. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  52301. get: function () {
  52302. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  52303. },
  52304. set: function (value) {
  52305. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  52306. return;
  52307. }
  52308. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52309. },
  52310. enumerable: true,
  52311. configurable: true
  52312. });
  52313. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  52314. get: function () {
  52315. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  52316. },
  52317. set: function (value) {
  52318. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  52319. return;
  52320. }
  52321. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52322. },
  52323. enumerable: true,
  52324. configurable: true
  52325. });
  52326. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  52327. get: function () {
  52328. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52329. },
  52330. set: function (value) {
  52331. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  52332. return;
  52333. }
  52334. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52335. },
  52336. enumerable: true,
  52337. configurable: true
  52338. });
  52339. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  52340. get: function () {
  52341. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52342. },
  52343. set: function (value) {
  52344. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  52345. return;
  52346. }
  52347. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  52348. },
  52349. enumerable: true,
  52350. configurable: true
  52351. });
  52352. /**
  52353. * Returns the darkness value (float).
  52354. */
  52355. ShadowGenerator.prototype.getDarkness = function () {
  52356. return this._darkness;
  52357. };
  52358. /**
  52359. * Sets the ShadowGenerator darkness value (float <= 1.0).
  52360. * Returns the ShadowGenerator.
  52361. */
  52362. ShadowGenerator.prototype.setDarkness = function (darkness) {
  52363. if (darkness >= 1.0)
  52364. this._darkness = 1.0;
  52365. else if (darkness <= 0.0)
  52366. this._darkness = 0.0;
  52367. else
  52368. this._darkness = darkness;
  52369. return this;
  52370. };
  52371. /**
  52372. * Sets the ability to have transparent shadow (boolean).
  52373. * Returns the ShadowGenerator.
  52374. */
  52375. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  52376. this._transparencyShadow = hasShadow;
  52377. return this;
  52378. };
  52379. /**
  52380. * Returns a RenderTargetTexture object : the shadow map texture.
  52381. */
  52382. ShadowGenerator.prototype.getShadowMap = function () {
  52383. return this._shadowMap;
  52384. };
  52385. /**
  52386. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  52387. */
  52388. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  52389. if (this._shadowMap2) {
  52390. return this._shadowMap2;
  52391. }
  52392. return this._shadowMap;
  52393. };
  52394. /**
  52395. * Helper function to add a mesh and its descendants to the list of shadow casters
  52396. * @param mesh Mesh to add
  52397. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  52398. */
  52399. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  52400. if (includeDescendants === void 0) { includeDescendants = true; }
  52401. if (!this._shadowMap) {
  52402. return this;
  52403. }
  52404. if (!this._shadowMap.renderList) {
  52405. this._shadowMap.renderList = [];
  52406. }
  52407. this._shadowMap.renderList.push(mesh);
  52408. if (includeDescendants) {
  52409. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  52410. }
  52411. return this;
  52412. var _a;
  52413. };
  52414. /**
  52415. * Helper function to remove a mesh and its descendants from the list of shadow casters
  52416. * @param mesh Mesh to remove
  52417. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  52418. */
  52419. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  52420. if (includeDescendants === void 0) { includeDescendants = true; }
  52421. if (!this._shadowMap || !this._shadowMap.renderList) {
  52422. return this;
  52423. }
  52424. var index = this._shadowMap.renderList.indexOf(mesh);
  52425. if (index !== -1) {
  52426. this._shadowMap.renderList.splice(index, 1);
  52427. }
  52428. if (includeDescendants) {
  52429. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  52430. var child = _a[_i];
  52431. this.removeShadowCaster(child);
  52432. }
  52433. }
  52434. return this;
  52435. };
  52436. /**
  52437. * Returns the associated light object.
  52438. */
  52439. ShadowGenerator.prototype.getLight = function () {
  52440. return this._light;
  52441. };
  52442. ShadowGenerator.prototype._initializeGenerator = function () {
  52443. this._light._markMeshesAsLightDirty();
  52444. this._initializeShadowMap();
  52445. };
  52446. ShadowGenerator.prototype._initializeShadowMap = function () {
  52447. var _this = this;
  52448. // Render target
  52449. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  52450. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52451. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52452. this._shadowMap.anisotropicFilteringLevel = 1;
  52453. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52454. this._shadowMap.renderParticles = false;
  52455. this._shadowMap.ignoreCameraViewport = true;
  52456. // Record Face Index before render.
  52457. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  52458. _this._currentFaceIndex = faceIndex;
  52459. });
  52460. // Custom render function.
  52461. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  52462. // Blur if required afer render.
  52463. this._shadowMap.onAfterUnbindObservable.add(function () {
  52464. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  52465. return;
  52466. }
  52467. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  52468. _this._initializeBlurRTTAndPostProcesses();
  52469. }
  52470. var shadowMap = _this.getShadowMapForRendering();
  52471. if (shadowMap) {
  52472. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  52473. }
  52474. });
  52475. // Clear according to the chosen filter.
  52476. this._shadowMap.onClearObservable.add(function (engine) {
  52477. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  52478. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  52479. }
  52480. else {
  52481. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52482. }
  52483. });
  52484. };
  52485. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  52486. var _this = this;
  52487. var engine = this._scene.getEngine();
  52488. var targetSize = this._mapSize / this.blurScale;
  52489. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  52490. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  52491. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52492. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52493. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52494. }
  52495. if (this.useKernelBlur) {
  52496. 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);
  52497. this._kernelBlurXPostprocess.width = targetSize;
  52498. this._kernelBlurXPostprocess.height = targetSize;
  52499. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  52500. effect.setTexture("textureSampler", _this._shadowMap);
  52501. });
  52502. 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);
  52503. this._kernelBlurXPostprocess.autoClear = false;
  52504. this._kernelBlurYPostprocess.autoClear = false;
  52505. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52506. this._kernelBlurXPostprocess.packedFloat = true;
  52507. this._kernelBlurYPostprocess.packedFloat = true;
  52508. }
  52509. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  52510. }
  52511. else {
  52512. 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);
  52513. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  52514. effect.setFloat2("screenSize", targetSize, targetSize);
  52515. effect.setTexture("textureSampler", _this._shadowMap);
  52516. });
  52517. this._boxBlurPostprocess.autoClear = false;
  52518. this._blurPostProcesses = [this._boxBlurPostprocess];
  52519. }
  52520. };
  52521. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52522. var index;
  52523. var engine = this._scene.getEngine();
  52524. if (depthOnlySubMeshes.length) {
  52525. engine.setColorWrite(false);
  52526. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52527. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52528. }
  52529. engine.setColorWrite(true);
  52530. }
  52531. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52532. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52533. }
  52534. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52535. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52536. }
  52537. if (this._transparencyShadow) {
  52538. for (index = 0; index < transparentSubMeshes.length; index++) {
  52539. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52540. }
  52541. }
  52542. };
  52543. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52544. var _this = this;
  52545. var mesh = subMesh.getRenderingMesh();
  52546. var scene = this._scene;
  52547. var engine = scene.getEngine();
  52548. var material = subMesh.getMaterial();
  52549. if (!material) {
  52550. return;
  52551. }
  52552. // Culling
  52553. engine.setState(material.backFaceCulling);
  52554. // Managing instances
  52555. var batch = mesh._getInstancesRenderList(subMesh._id);
  52556. if (batch.mustReturn) {
  52557. return;
  52558. }
  52559. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52560. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52561. engine.enableEffect(this._effect);
  52562. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52563. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52564. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52565. this._effect.setVector3("lightPosition", this.getLight().position);
  52566. if (scene.activeCamera) {
  52567. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52568. }
  52569. // Alpha test
  52570. if (material && material.needAlphaTesting()) {
  52571. var alphaTexture = material.getAlphaTestTexture();
  52572. if (alphaTexture) {
  52573. this._effect.setTexture("diffuseSampler", alphaTexture);
  52574. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52575. }
  52576. }
  52577. // Bones
  52578. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52579. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52580. }
  52581. if (this.forceBackFacesOnly) {
  52582. engine.setState(true, 0, false, true);
  52583. }
  52584. // Draw
  52585. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52586. if (this.forceBackFacesOnly) {
  52587. engine.setState(true, 0, false, false);
  52588. }
  52589. }
  52590. else {
  52591. // Need to reset refresh rate of the shadowMap
  52592. if (this._shadowMap) {
  52593. this._shadowMap.resetRefreshCounter();
  52594. }
  52595. }
  52596. };
  52597. ShadowGenerator.prototype._applyFilterValues = function () {
  52598. if (!this._shadowMap) {
  52599. return;
  52600. }
  52601. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52602. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52603. }
  52604. else {
  52605. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52606. }
  52607. };
  52608. /**
  52609. * Force shader compilation including textures ready check
  52610. */
  52611. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52612. var _this = this;
  52613. var localOptions = __assign({ useInstances: false }, options);
  52614. var shadowMap = this.getShadowMap();
  52615. if (!shadowMap) {
  52616. if (onCompiled) {
  52617. onCompiled(this);
  52618. }
  52619. return;
  52620. }
  52621. var renderList = shadowMap.renderList;
  52622. if (!renderList) {
  52623. if (onCompiled) {
  52624. onCompiled(this);
  52625. }
  52626. return;
  52627. }
  52628. var subMeshes = new Array();
  52629. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52630. var mesh = renderList_1[_i];
  52631. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52632. }
  52633. if (subMeshes.length === 0) {
  52634. if (onCompiled) {
  52635. onCompiled(this);
  52636. }
  52637. return;
  52638. }
  52639. var currentIndex = 0;
  52640. var checkReady = function () {
  52641. if (!_this._scene || !_this._scene.getEngine()) {
  52642. return;
  52643. }
  52644. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  52645. currentIndex++;
  52646. if (currentIndex >= subMeshes.length) {
  52647. if (onCompiled) {
  52648. onCompiled(_this);
  52649. }
  52650. return;
  52651. }
  52652. }
  52653. setTimeout(checkReady, 16);
  52654. };
  52655. checkReady();
  52656. };
  52657. /**
  52658. * Boolean : true when the ShadowGenerator is finally computed.
  52659. */
  52660. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52661. var defines = [];
  52662. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52663. defines.push("#define FLOAT");
  52664. }
  52665. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52666. defines.push("#define ESM");
  52667. }
  52668. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52669. var mesh = subMesh.getMesh();
  52670. var material = subMesh.getMaterial();
  52671. // Alpha test
  52672. if (material && material.needAlphaTesting()) {
  52673. var alphaTexture = material.getAlphaTestTexture();
  52674. if (alphaTexture) {
  52675. defines.push("#define ALPHATEST");
  52676. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52677. attribs.push(BABYLON.VertexBuffer.UVKind);
  52678. defines.push("#define UV1");
  52679. }
  52680. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52681. if (alphaTexture.coordinatesIndex === 1) {
  52682. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52683. defines.push("#define UV2");
  52684. }
  52685. }
  52686. }
  52687. }
  52688. // Bones
  52689. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52690. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52691. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52692. if (mesh.numBoneInfluencers > 4) {
  52693. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52694. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52695. }
  52696. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52697. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52698. }
  52699. else {
  52700. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52701. }
  52702. // Instances
  52703. if (useInstances) {
  52704. defines.push("#define INSTANCES");
  52705. attribs.push("world0");
  52706. attribs.push("world1");
  52707. attribs.push("world2");
  52708. attribs.push("world3");
  52709. }
  52710. // Get correct effect
  52711. var join = defines.join("\n");
  52712. if (this._cachedDefines !== join) {
  52713. this._cachedDefines = join;
  52714. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52715. }
  52716. return this._effect.isReady();
  52717. };
  52718. /**
  52719. * This creates the defines related to the standard BJS materials.
  52720. */
  52721. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52722. var scene = this._scene;
  52723. var light = this._light;
  52724. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52725. return;
  52726. }
  52727. defines["SHADOW" + lightIndex] = true;
  52728. if (this.usePoissonSampling) {
  52729. defines["SHADOWPCF" + lightIndex] = true;
  52730. }
  52731. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52732. defines["SHADOWESM" + lightIndex] = true;
  52733. }
  52734. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52735. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52736. }
  52737. if (light.needCube()) {
  52738. defines["SHADOWCUBE" + lightIndex] = true;
  52739. }
  52740. };
  52741. /**
  52742. * This binds shadow lights related to the standard BJS materials.
  52743. * It implies the unifroms available on the materials are the standard BJS ones.
  52744. */
  52745. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52746. var light = this._light;
  52747. var scene = this._scene;
  52748. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52749. return;
  52750. }
  52751. var camera = scene.activeCamera;
  52752. if (!camera) {
  52753. return;
  52754. }
  52755. var shadowMap = this.getShadowMap();
  52756. if (!shadowMap) {
  52757. return;
  52758. }
  52759. if (!light.needCube()) {
  52760. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52761. }
  52762. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52763. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52764. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52765. };
  52766. // Methods
  52767. /**
  52768. * Returns a Matrix object : the updated transformation matrix.
  52769. */
  52770. ShadowGenerator.prototype.getTransformMatrix = function () {
  52771. var scene = this._scene;
  52772. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52773. return this._transformMatrix;
  52774. }
  52775. this._currentRenderID = scene.getRenderId();
  52776. this._currentFaceIndexCache = this._currentFaceIndex;
  52777. var lightPosition = this._light.position;
  52778. if (this._light.computeTransformedInformation()) {
  52779. lightPosition = this._light.transformedPosition;
  52780. }
  52781. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52782. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52783. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52784. }
  52785. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52786. this._cachedPosition = lightPosition.clone();
  52787. this._cachedDirection = this._lightDirection.clone();
  52788. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52789. var shadowMap = this.getShadowMap();
  52790. if (shadowMap) {
  52791. var renderList = shadowMap.renderList;
  52792. if (renderList) {
  52793. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52794. }
  52795. }
  52796. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52797. }
  52798. return this._transformMatrix;
  52799. };
  52800. ShadowGenerator.prototype.recreateShadowMap = function () {
  52801. var shadowMap = this._shadowMap;
  52802. if (!shadowMap) {
  52803. return;
  52804. }
  52805. // Track render list.
  52806. var renderList = shadowMap.renderList;
  52807. // Clean up existing data.
  52808. this._disposeRTTandPostProcesses();
  52809. // Reinitializes.
  52810. this._initializeGenerator();
  52811. // Reaffect the filter to ensure a correct fallback if necessary.
  52812. this.filter = this.filter;
  52813. // Reaffect the filter.
  52814. this._applyFilterValues();
  52815. // Reaffect Render List.
  52816. this._shadowMap.renderList = renderList;
  52817. };
  52818. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52819. if (this._shadowMap2) {
  52820. this._shadowMap2.dispose();
  52821. this._shadowMap2 = null;
  52822. }
  52823. if (this._downSamplePostprocess) {
  52824. this._downSamplePostprocess.dispose();
  52825. this._downSamplePostprocess = null;
  52826. }
  52827. if (this._boxBlurPostprocess) {
  52828. this._boxBlurPostprocess.dispose();
  52829. this._boxBlurPostprocess = null;
  52830. }
  52831. if (this._kernelBlurXPostprocess) {
  52832. this._kernelBlurXPostprocess.dispose();
  52833. this._kernelBlurXPostprocess = null;
  52834. }
  52835. if (this._kernelBlurYPostprocess) {
  52836. this._kernelBlurYPostprocess.dispose();
  52837. this._kernelBlurYPostprocess = null;
  52838. }
  52839. this._blurPostProcesses = [];
  52840. };
  52841. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52842. if (this._shadowMap) {
  52843. this._shadowMap.dispose();
  52844. this._shadowMap = null;
  52845. }
  52846. this._disposeBlurPostProcesses();
  52847. };
  52848. /**
  52849. * Disposes the ShadowGenerator.
  52850. * Returns nothing.
  52851. */
  52852. ShadowGenerator.prototype.dispose = function () {
  52853. this._disposeRTTandPostProcesses();
  52854. if (this._light) {
  52855. this._light._shadowGenerator = null;
  52856. this._light._markMeshesAsLightDirty();
  52857. }
  52858. };
  52859. /**
  52860. * Serializes the ShadowGenerator and returns a serializationObject.
  52861. */
  52862. ShadowGenerator.prototype.serialize = function () {
  52863. var serializationObject = {};
  52864. var shadowMap = this.getShadowMap();
  52865. if (!shadowMap) {
  52866. return serializationObject;
  52867. }
  52868. serializationObject.lightId = this._light.id;
  52869. serializationObject.mapSize = shadowMap.getRenderSize();
  52870. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52871. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52872. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52873. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52874. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52875. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52876. serializationObject.depthScale = this.depthScale;
  52877. serializationObject.darkness = this.getDarkness();
  52878. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52879. serializationObject.blurKernel = this.blurKernel;
  52880. serializationObject.blurScale = this.blurScale;
  52881. serializationObject.useKernelBlur = this.useKernelBlur;
  52882. serializationObject.transparencyShadow = this._transparencyShadow;
  52883. serializationObject.renderList = [];
  52884. if (shadowMap.renderList) {
  52885. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52886. var mesh = shadowMap.renderList[meshIndex];
  52887. serializationObject.renderList.push(mesh.id);
  52888. }
  52889. }
  52890. return serializationObject;
  52891. };
  52892. /**
  52893. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52894. */
  52895. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52896. //casting to point light, as light is missing the position attr and typescript complains.
  52897. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52898. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52899. var shadowMap = shadowGenerator.getShadowMap();
  52900. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52901. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52902. meshes.forEach(function (mesh) {
  52903. if (!shadowMap) {
  52904. return;
  52905. }
  52906. if (!shadowMap.renderList) {
  52907. shadowMap.renderList = [];
  52908. }
  52909. shadowMap.renderList.push(mesh);
  52910. });
  52911. }
  52912. if (parsedShadowGenerator.usePoissonSampling) {
  52913. shadowGenerator.usePoissonSampling = true;
  52914. }
  52915. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52916. shadowGenerator.useExponentialShadowMap = true;
  52917. }
  52918. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52919. shadowGenerator.useBlurExponentialShadowMap = true;
  52920. }
  52921. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52922. shadowGenerator.useCloseExponentialShadowMap = true;
  52923. }
  52924. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52925. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52926. }
  52927. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52928. shadowGenerator.useExponentialShadowMap = true;
  52929. }
  52930. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52931. shadowGenerator.useBlurExponentialShadowMap = true;
  52932. }
  52933. if (parsedShadowGenerator.depthScale) {
  52934. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52935. }
  52936. if (parsedShadowGenerator.blurScale) {
  52937. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52938. }
  52939. if (parsedShadowGenerator.blurBoxOffset) {
  52940. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52941. }
  52942. if (parsedShadowGenerator.useKernelBlur) {
  52943. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52944. }
  52945. if (parsedShadowGenerator.blurKernel) {
  52946. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52947. }
  52948. if (parsedShadowGenerator.bias !== undefined) {
  52949. shadowGenerator.bias = parsedShadowGenerator.bias;
  52950. }
  52951. if (parsedShadowGenerator.darkness) {
  52952. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52953. }
  52954. if (parsedShadowGenerator.transparencyShadow) {
  52955. shadowGenerator.setTransparencyShadow(true);
  52956. }
  52957. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52958. return shadowGenerator;
  52959. };
  52960. ShadowGenerator._FILTER_NONE = 0;
  52961. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52962. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52963. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52964. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52965. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52966. return ShadowGenerator;
  52967. }());
  52968. BABYLON.ShadowGenerator = ShadowGenerator;
  52969. })(BABYLON || (BABYLON = {}));
  52970. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52971. var BABYLON;
  52972. (function (BABYLON) {
  52973. var DefaultLoadingScreen = /** @class */ (function () {
  52974. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52975. if (_loadingText === void 0) { _loadingText = ""; }
  52976. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52977. var _this = this;
  52978. this._renderingCanvas = _renderingCanvas;
  52979. this._loadingText = _loadingText;
  52980. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52981. // Resize
  52982. this._resizeLoadingUI = function () {
  52983. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52984. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52985. if (!_this._loadingDiv) {
  52986. return;
  52987. }
  52988. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52989. _this._loadingDiv.style.left = canvasRect.left + "px";
  52990. _this._loadingDiv.style.top = canvasRect.top + "px";
  52991. _this._loadingDiv.style.width = canvasRect.width + "px";
  52992. _this._loadingDiv.style.height = canvasRect.height + "px";
  52993. };
  52994. }
  52995. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52996. if (this._loadingDiv) {
  52997. // Do not add a loading screen if there is already one
  52998. return;
  52999. }
  53000. this._loadingDiv = document.createElement("div");
  53001. this._loadingDiv.id = "babylonjsLoadingDiv";
  53002. this._loadingDiv.style.opacity = "0";
  53003. this._loadingDiv.style.transition = "opacity 1.5s ease";
  53004. this._loadingDiv.style.pointerEvents = "none";
  53005. // Loading text
  53006. this._loadingTextDiv = document.createElement("div");
  53007. this._loadingTextDiv.style.position = "absolute";
  53008. this._loadingTextDiv.style.left = "0";
  53009. this._loadingTextDiv.style.top = "50%";
  53010. this._loadingTextDiv.style.marginTop = "80px";
  53011. this._loadingTextDiv.style.width = "100%";
  53012. this._loadingTextDiv.style.height = "20px";
  53013. this._loadingTextDiv.style.fontFamily = "Arial";
  53014. this._loadingTextDiv.style.fontSize = "14px";
  53015. this._loadingTextDiv.style.color = "white";
  53016. this._loadingTextDiv.style.textAlign = "center";
  53017. this._loadingTextDiv.innerHTML = "Loading";
  53018. this._loadingDiv.appendChild(this._loadingTextDiv);
  53019. //set the predefined text
  53020. this._loadingTextDiv.innerHTML = this._loadingText;
  53021. // Generating keyframes
  53022. var style = document.createElement('style');
  53023. style.type = 'text/css';
  53024. 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 }";
  53025. style.innerHTML = keyFrames;
  53026. document.getElementsByTagName('head')[0].appendChild(style);
  53027. // Loading img
  53028. var imgBack = new Image();
  53029. 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";
  53030. imgBack.style.position = "absolute";
  53031. imgBack.style.left = "50%";
  53032. imgBack.style.top = "50%";
  53033. imgBack.style.marginLeft = "-60px";
  53034. imgBack.style.marginTop = "-60px";
  53035. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  53036. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  53037. imgBack.style.transformOrigin = "50% 50%";
  53038. imgBack.style.webkitTransformOrigin = "50% 50%";
  53039. this._loadingDiv.appendChild(imgBack);
  53040. this._resizeLoadingUI();
  53041. window.addEventListener("resize", this._resizeLoadingUI);
  53042. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53043. document.body.appendChild(this._loadingDiv);
  53044. this._loadingDiv.style.opacity = "1";
  53045. };
  53046. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  53047. var _this = this;
  53048. if (!this._loadingDiv) {
  53049. return;
  53050. }
  53051. var onTransitionEnd = function () {
  53052. if (!_this._loadingDiv) {
  53053. return;
  53054. }
  53055. document.body.removeChild(_this._loadingDiv);
  53056. window.removeEventListener("resize", _this._resizeLoadingUI);
  53057. _this._loadingDiv = null;
  53058. };
  53059. this._loadingDiv.style.opacity = "0";
  53060. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  53061. };
  53062. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  53063. set: function (text) {
  53064. this._loadingText = text;
  53065. if (this._loadingTextDiv) {
  53066. this._loadingTextDiv.innerHTML = this._loadingText;
  53067. }
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  53073. get: function () {
  53074. return this._loadingDivBackgroundColor;
  53075. },
  53076. set: function (color) {
  53077. this._loadingDivBackgroundColor = color;
  53078. if (!this._loadingDiv) {
  53079. return;
  53080. }
  53081. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53082. },
  53083. enumerable: true,
  53084. configurable: true
  53085. });
  53086. return DefaultLoadingScreen;
  53087. }());
  53088. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  53089. })(BABYLON || (BABYLON = {}));
  53090. //# sourceMappingURL=babylon.loadingScreen.js.map
  53091. var BABYLON;
  53092. (function (BABYLON) {
  53093. var SceneLoader = /** @class */ (function () {
  53094. function SceneLoader() {
  53095. }
  53096. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  53097. get: function () {
  53098. return 0;
  53099. },
  53100. enumerable: true,
  53101. configurable: true
  53102. });
  53103. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  53104. get: function () {
  53105. return 1;
  53106. },
  53107. enumerable: true,
  53108. configurable: true
  53109. });
  53110. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  53111. get: function () {
  53112. return 2;
  53113. },
  53114. enumerable: true,
  53115. configurable: true
  53116. });
  53117. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  53118. get: function () {
  53119. return 3;
  53120. },
  53121. enumerable: true,
  53122. configurable: true
  53123. });
  53124. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  53125. get: function () {
  53126. return SceneLoader._ForceFullSceneLoadingForIncremental;
  53127. },
  53128. set: function (value) {
  53129. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  53130. },
  53131. enumerable: true,
  53132. configurable: true
  53133. });
  53134. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  53135. get: function () {
  53136. return SceneLoader._ShowLoadingScreen;
  53137. },
  53138. set: function (value) {
  53139. SceneLoader._ShowLoadingScreen = value;
  53140. },
  53141. enumerable: true,
  53142. configurable: true
  53143. });
  53144. Object.defineProperty(SceneLoader, "loggingLevel", {
  53145. get: function () {
  53146. return SceneLoader._loggingLevel;
  53147. },
  53148. set: function (value) {
  53149. SceneLoader._loggingLevel = value;
  53150. },
  53151. enumerable: true,
  53152. configurable: true
  53153. });
  53154. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  53155. get: function () {
  53156. return SceneLoader._CleanBoneMatrixWeights;
  53157. },
  53158. set: function (value) {
  53159. SceneLoader._CleanBoneMatrixWeights = value;
  53160. },
  53161. enumerable: true,
  53162. configurable: true
  53163. });
  53164. SceneLoader._getDefaultPlugin = function () {
  53165. return SceneLoader._registeredPlugins[".babylon"];
  53166. };
  53167. SceneLoader._getPluginForExtension = function (extension) {
  53168. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  53169. if (registeredPlugin) {
  53170. return registeredPlugin;
  53171. }
  53172. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  53173. return SceneLoader._getDefaultPlugin();
  53174. };
  53175. SceneLoader._getPluginForDirectLoad = function (data) {
  53176. for (var extension in SceneLoader._registeredPlugins) {
  53177. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  53178. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  53179. return SceneLoader._registeredPlugins[extension];
  53180. }
  53181. }
  53182. return SceneLoader._getDefaultPlugin();
  53183. };
  53184. SceneLoader._getPluginForFilename = function (sceneFilename) {
  53185. if (sceneFilename.name) {
  53186. sceneFilename = sceneFilename.name;
  53187. }
  53188. var queryStringPosition = sceneFilename.indexOf("?");
  53189. if (queryStringPosition !== -1) {
  53190. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  53191. }
  53192. var dotPosition = sceneFilename.lastIndexOf(".");
  53193. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  53194. return SceneLoader._getPluginForExtension(extension);
  53195. };
  53196. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  53197. SceneLoader._getDirectLoad = function (sceneFilename) {
  53198. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  53199. return sceneFilename.substr(5);
  53200. }
  53201. return null;
  53202. };
  53203. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53204. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  53205. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  53206. var plugin;
  53207. if (registeredPlugin.plugin.createPlugin) {
  53208. plugin = registeredPlugin.plugin.createPlugin();
  53209. }
  53210. else {
  53211. plugin = registeredPlugin.plugin;
  53212. }
  53213. var useArrayBuffer = registeredPlugin.isBinary;
  53214. var database;
  53215. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  53216. var dataCallback = function (data, responseURL) {
  53217. if (scene.isDisposed) {
  53218. onError("Scene has been disposed");
  53219. return;
  53220. }
  53221. scene.database = database;
  53222. onSuccess(plugin, data, responseURL);
  53223. };
  53224. var manifestChecked = function (success) {
  53225. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request, exception) {
  53226. if (request) {
  53227. onError(request.status + " " + request.statusText, exception);
  53228. }
  53229. });
  53230. };
  53231. if (directLoad) {
  53232. dataCallback(directLoad);
  53233. return plugin;
  53234. }
  53235. if (rootUrl.indexOf("file:") === -1) {
  53236. if (scene.getEngine().enableOfflineSupport) {
  53237. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  53238. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  53239. }
  53240. else {
  53241. manifestChecked(true);
  53242. }
  53243. }
  53244. else {
  53245. var fileOrString = sceneFilename;
  53246. if (fileOrString.name) {
  53247. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  53248. }
  53249. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  53250. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  53251. }
  53252. else {
  53253. onError("Unable to find file named " + sceneFilename);
  53254. }
  53255. }
  53256. return plugin;
  53257. };
  53258. // Public functions
  53259. SceneLoader.GetPluginForExtension = function (extension) {
  53260. return SceneLoader._getPluginForExtension(extension).plugin;
  53261. };
  53262. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  53263. return !!SceneLoader._registeredPlugins[extension];
  53264. };
  53265. SceneLoader.RegisterPlugin = function (plugin) {
  53266. if (typeof plugin.extensions === "string") {
  53267. var extension = plugin.extensions;
  53268. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53269. plugin: plugin,
  53270. isBinary: false
  53271. };
  53272. }
  53273. else {
  53274. var extensions = plugin.extensions;
  53275. Object.keys(extensions).forEach(function (extension) {
  53276. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  53277. plugin: plugin,
  53278. isBinary: extensions[extension].isBinary
  53279. };
  53280. });
  53281. }
  53282. };
  53283. /**
  53284. * Import meshes into a scene
  53285. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  53286. * @param rootUrl a string that defines the root url for scene and resources
  53287. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53288. * @param scene the instance of BABYLON.Scene to append to
  53289. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  53290. * @param onProgress a callback with a progress event for each file being loaded
  53291. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53292. */
  53293. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53294. if (onSuccess === void 0) { onSuccess = null; }
  53295. if (onProgress === void 0) { onProgress = null; }
  53296. if (onError === void 0) { onError = null; }
  53297. if (pluginExtension === void 0) { pluginExtension = null; }
  53298. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53299. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53300. return null;
  53301. }
  53302. var loadingToken = {};
  53303. scene._addPendingData(loadingToken);
  53304. var errorHandler = function (message, exception) {
  53305. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  53306. if (onError) {
  53307. onError(scene, errorMessage, exception);
  53308. }
  53309. else {
  53310. BABYLON.Tools.Error(errorMessage);
  53311. // should the exception be thrown?
  53312. }
  53313. scene._removePendingData(loadingToken);
  53314. };
  53315. var progressHandler = onProgress ? function (event) {
  53316. try {
  53317. onProgress(event);
  53318. }
  53319. catch (e) {
  53320. errorHandler("Error in onProgress callback", e);
  53321. }
  53322. } : undefined;
  53323. var successHandler = function (meshes, particleSystems, skeletons) {
  53324. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  53325. if (onSuccess) {
  53326. try {
  53327. onSuccess(meshes, particleSystems, skeletons);
  53328. }
  53329. catch (e) {
  53330. errorHandler("Error in onSuccess callback", e);
  53331. }
  53332. }
  53333. scene._removePendingData(loadingToken);
  53334. };
  53335. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53336. if (plugin.rewriteRootURL) {
  53337. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  53338. }
  53339. if (plugin.importMesh) {
  53340. var syncedPlugin = plugin;
  53341. var meshes = new Array();
  53342. var particleSystems = new Array();
  53343. var skeletons = new Array();
  53344. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  53345. return;
  53346. }
  53347. scene.loadingPluginName = plugin.name;
  53348. successHandler(meshes, particleSystems, skeletons);
  53349. }
  53350. else {
  53351. var asyncedPlugin = plugin;
  53352. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  53353. scene.loadingPluginName = plugin.name;
  53354. successHandler(meshes, particleSystems, skeletons);
  53355. }, progressHandler, errorHandler);
  53356. }
  53357. }, progressHandler, errorHandler, pluginExtension);
  53358. };
  53359. /**
  53360. * Load a scene
  53361. * @param rootUrl a string that defines the root url for scene and resources
  53362. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53363. * @param engine is the instance of BABYLON.Engine to use to create the scene
  53364. * @param onSuccess a callback with the scene when import succeeds
  53365. * @param onProgress a callback with a progress event for each file being loaded
  53366. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53367. */
  53368. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  53369. if (onSuccess === void 0) { onSuccess = null; }
  53370. if (onProgress === void 0) { onProgress = null; }
  53371. if (onError === void 0) { onError = null; }
  53372. if (pluginExtension === void 0) { pluginExtension = null; }
  53373. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  53374. };
  53375. /**
  53376. * Append a scene
  53377. * @param rootUrl a string that defines the root url for scene and resources
  53378. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  53379. * @param scene is the instance of BABYLON.Scene to append to
  53380. * @param onSuccess a callback with the scene when import succeeds
  53381. * @param onProgress a callback with a progress event for each file being loaded
  53382. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  53383. */
  53384. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  53385. if (onSuccess === void 0) { onSuccess = null; }
  53386. if (onProgress === void 0) { onProgress = null; }
  53387. if (onError === void 0) { onError = null; }
  53388. if (pluginExtension === void 0) { pluginExtension = null; }
  53389. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  53390. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  53391. return null;
  53392. }
  53393. if (SceneLoader.ShowLoadingScreen) {
  53394. scene.getEngine().displayLoadingUI();
  53395. }
  53396. var loadingToken = {};
  53397. scene._addPendingData(loadingToken);
  53398. var errorHandler = function (message, exception) {
  53399. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  53400. if (onError) {
  53401. onError(scene, errorMessage, exception);
  53402. }
  53403. else {
  53404. BABYLON.Tools.Error(errorMessage);
  53405. // should the exception be thrown?
  53406. }
  53407. scene._removePendingData(loadingToken);
  53408. scene.getEngine().hideLoadingUI();
  53409. };
  53410. var progressHandler = onProgress ? function (event) {
  53411. try {
  53412. onProgress(event);
  53413. }
  53414. catch (e) {
  53415. errorHandler("Error in onProgress callback", e);
  53416. }
  53417. } : undefined;
  53418. var successHandler = function () {
  53419. if (onSuccess) {
  53420. try {
  53421. onSuccess(scene);
  53422. }
  53423. catch (e) {
  53424. errorHandler("Error in onSuccess callback", e);
  53425. }
  53426. }
  53427. scene._removePendingData(loadingToken);
  53428. };
  53429. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  53430. if (plugin.load) {
  53431. var syncedPlugin = plugin;
  53432. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  53433. return;
  53434. }
  53435. scene.loadingPluginName = plugin.name;
  53436. successHandler();
  53437. }
  53438. else {
  53439. var asyncedPlugin = plugin;
  53440. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  53441. scene.loadingPluginName = plugin.name;
  53442. successHandler();
  53443. }, progressHandler, errorHandler);
  53444. }
  53445. if (SceneLoader.ShowLoadingScreen) {
  53446. scene.executeWhenReady(function () {
  53447. scene.getEngine().hideLoadingUI();
  53448. });
  53449. }
  53450. }, progressHandler, errorHandler, pluginExtension);
  53451. };
  53452. // Flags
  53453. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  53454. SceneLoader._ShowLoadingScreen = true;
  53455. SceneLoader._CleanBoneMatrixWeights = false;
  53456. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  53457. // Members
  53458. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  53459. SceneLoader._registeredPlugins = {};
  53460. return SceneLoader;
  53461. }());
  53462. BABYLON.SceneLoader = SceneLoader;
  53463. ;
  53464. })(BABYLON || (BABYLON = {}));
  53465. //# sourceMappingURL=babylon.sceneLoader.js.map
  53466. var BABYLON;
  53467. (function (BABYLON) {
  53468. var Internals;
  53469. (function (Internals) {
  53470. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  53471. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53472. var parsedMaterial = parsedData.materials[index];
  53473. if (parsedMaterial.id === id) {
  53474. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53475. }
  53476. }
  53477. return null;
  53478. };
  53479. var isDescendantOf = function (mesh, names, hierarchyIds) {
  53480. for (var i in names) {
  53481. if (mesh.name === names[i]) {
  53482. hierarchyIds.push(mesh.id);
  53483. return true;
  53484. }
  53485. }
  53486. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  53487. hierarchyIds.push(mesh.id);
  53488. return true;
  53489. }
  53490. return false;
  53491. };
  53492. var logOperation = function (operation, producer) {
  53493. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  53494. };
  53495. BABYLON.SceneLoader.RegisterPlugin({
  53496. name: "babylon.js",
  53497. extensions: ".babylon",
  53498. canDirectLoad: function (data) {
  53499. if (data.indexOf("babylon") !== -1) {
  53500. return true;
  53501. }
  53502. return false;
  53503. },
  53504. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  53505. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53506. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53507. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53508. // and avoid problems with multiple concurrent .babylon loads.
  53509. var log = "importMesh has failed JSON parse";
  53510. try {
  53511. var parsedData = JSON.parse(data);
  53512. log = "";
  53513. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53514. if (!meshesNames) {
  53515. meshesNames = null;
  53516. }
  53517. else if (!Array.isArray(meshesNames)) {
  53518. meshesNames = [meshesNames];
  53519. }
  53520. var hierarchyIds = new Array();
  53521. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53522. var loadedSkeletonsIds = [];
  53523. var loadedMaterialsIds = [];
  53524. var index;
  53525. var cache;
  53526. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53527. var parsedMesh = parsedData.meshes[index];
  53528. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  53529. if (meshesNames !== null) {
  53530. // Remove found mesh name from list.
  53531. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  53532. }
  53533. //Geometry?
  53534. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53535. //does the file contain geometries?
  53536. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53537. //find the correct geometry and add it to the scene
  53538. var found = false;
  53539. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53540. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53541. return;
  53542. }
  53543. else {
  53544. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53545. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53546. switch (geometryType) {
  53547. case "boxes":
  53548. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53549. break;
  53550. case "spheres":
  53551. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53552. break;
  53553. case "cylinders":
  53554. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53555. break;
  53556. case "toruses":
  53557. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53558. break;
  53559. case "grounds":
  53560. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53561. break;
  53562. case "planes":
  53563. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53564. break;
  53565. case "torusKnots":
  53566. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53567. break;
  53568. case "vertexData":
  53569. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53570. break;
  53571. }
  53572. found = true;
  53573. }
  53574. });
  53575. }
  53576. });
  53577. if (found === false) {
  53578. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53579. }
  53580. }
  53581. }
  53582. // Material ?
  53583. if (parsedMesh.materialId) {
  53584. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53585. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53586. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53587. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53588. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53589. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53590. var subMatId = parsedMultiMaterial.materials[matIndex];
  53591. loadedMaterialsIds.push(subMatId);
  53592. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53593. log += "\n\tMaterial " + mat.toString(fullDetails);
  53594. }
  53595. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53596. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53597. materialFound = true;
  53598. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53599. break;
  53600. }
  53601. }
  53602. }
  53603. if (materialFound === false) {
  53604. loadedMaterialsIds.push(parsedMesh.materialId);
  53605. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53606. if (!mat) {
  53607. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53608. }
  53609. else {
  53610. log += "\n\tMaterial " + mat.toString(fullDetails);
  53611. }
  53612. }
  53613. }
  53614. // Skeleton ?
  53615. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53616. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53617. if (skeletonAlreadyLoaded === false) {
  53618. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53619. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53620. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53621. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53622. skeletons.push(skeleton);
  53623. loadedSkeletonsIds.push(parsedSkeleton.id);
  53624. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53625. }
  53626. }
  53627. }
  53628. }
  53629. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53630. meshes.push(mesh);
  53631. log += "\n\tMesh " + mesh.toString(fullDetails);
  53632. }
  53633. }
  53634. // Connecting parents
  53635. var currentMesh;
  53636. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53637. currentMesh = scene.meshes[index];
  53638. if (currentMesh._waitingParentId) {
  53639. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53640. currentMesh._waitingParentId = null;
  53641. }
  53642. }
  53643. // freeze and compute world matrix application
  53644. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53645. currentMesh = scene.meshes[index];
  53646. if (currentMesh._waitingFreezeWorldMatrix) {
  53647. currentMesh.freezeWorldMatrix();
  53648. currentMesh._waitingFreezeWorldMatrix = null;
  53649. }
  53650. else {
  53651. currentMesh.computeWorldMatrix(true);
  53652. }
  53653. }
  53654. }
  53655. // Particles
  53656. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53657. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53658. var parsedParticleSystem = parsedData.particleSystems[index];
  53659. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53660. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53661. }
  53662. }
  53663. }
  53664. return true;
  53665. }
  53666. catch (err) {
  53667. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53668. if (onError) {
  53669. onError(msg, err);
  53670. }
  53671. else {
  53672. BABYLON.Tools.Log(msg);
  53673. throw err;
  53674. }
  53675. }
  53676. finally {
  53677. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53678. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53679. }
  53680. }
  53681. return false;
  53682. },
  53683. load: function (scene, data, rootUrl, onError) {
  53684. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53685. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53686. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53687. // and avoid problems with multiple concurrent .babylon loads.
  53688. var log = "importScene has failed JSON parse";
  53689. try {
  53690. var parsedData = JSON.parse(data);
  53691. log = "";
  53692. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53693. // Scene
  53694. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53695. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53696. }
  53697. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53698. scene.autoClear = parsedData.autoClear;
  53699. }
  53700. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53701. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53702. }
  53703. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53704. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53705. }
  53706. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53707. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53708. }
  53709. // Fog
  53710. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53711. scene.fogMode = parsedData.fogMode;
  53712. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53713. scene.fogStart = parsedData.fogStart;
  53714. scene.fogEnd = parsedData.fogEnd;
  53715. scene.fogDensity = parsedData.fogDensity;
  53716. log += "\tFog mode for scene: ";
  53717. switch (scene.fogMode) {
  53718. // getters not compiling, so using hardcoded
  53719. case 1:
  53720. log += "exp\n";
  53721. break;
  53722. case 2:
  53723. log += "exp2\n";
  53724. break;
  53725. case 3:
  53726. log += "linear\n";
  53727. break;
  53728. }
  53729. }
  53730. //Physics
  53731. if (parsedData.physicsEnabled) {
  53732. var physicsPlugin;
  53733. if (parsedData.physicsEngine === "cannon") {
  53734. physicsPlugin = new BABYLON.CannonJSPlugin();
  53735. }
  53736. else if (parsedData.physicsEngine === "oimo") {
  53737. physicsPlugin = new BABYLON.OimoJSPlugin();
  53738. }
  53739. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53740. //else - default engine, which is currently oimo
  53741. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53742. scene.enablePhysics(physicsGravity, physicsPlugin);
  53743. }
  53744. // Metadata
  53745. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53746. scene.metadata = parsedData.metadata;
  53747. }
  53748. //collisions, if defined. otherwise, default is true
  53749. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53750. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53751. }
  53752. scene.workerCollisions = !!parsedData.workerCollisions;
  53753. var index;
  53754. var cache;
  53755. // Lights
  53756. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53757. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53758. var parsedLight = parsedData.lights[index];
  53759. var light = BABYLON.Light.Parse(parsedLight, scene);
  53760. if (light) {
  53761. log += (index === 0 ? "\n\tLights:" : "");
  53762. log += "\n\t\t" + light.toString(fullDetails);
  53763. }
  53764. }
  53765. }
  53766. // Animations
  53767. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53768. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53769. var parsedAnimation = parsedData.animations[index];
  53770. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53771. scene.animations.push(animation);
  53772. log += (index === 0 ? "\n\tAnimations:" : "");
  53773. log += "\n\t\t" + animation.toString(fullDetails);
  53774. }
  53775. }
  53776. if (parsedData.autoAnimate) {
  53777. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53778. }
  53779. // Materials
  53780. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53781. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53782. var parsedMaterial = parsedData.materials[index];
  53783. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53784. log += (index === 0 ? "\n\tMaterials:" : "");
  53785. log += "\n\t\t" + mat.toString(fullDetails);
  53786. }
  53787. }
  53788. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53789. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53790. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53791. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53792. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53793. log += "\n\t\t" + mmat.toString(fullDetails);
  53794. }
  53795. }
  53796. // Morph targets
  53797. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53798. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53799. var managerData = _a[_i];
  53800. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53801. }
  53802. }
  53803. // Skeletons
  53804. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53805. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53806. var parsedSkeleton = parsedData.skeletons[index];
  53807. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53808. log += (index === 0 ? "\n\tSkeletons:" : "");
  53809. log += "\n\t\t" + skeleton.toString(fullDetails);
  53810. }
  53811. }
  53812. // Geometries
  53813. var geometries = parsedData.geometries;
  53814. if (geometries !== undefined && geometries !== null) {
  53815. // Boxes
  53816. var boxes = geometries.boxes;
  53817. if (boxes !== undefined && boxes !== null) {
  53818. for (index = 0, cache = boxes.length; index < cache; index++) {
  53819. var parsedBox = boxes[index];
  53820. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53821. }
  53822. }
  53823. // Spheres
  53824. var spheres = geometries.spheres;
  53825. if (spheres !== undefined && spheres !== null) {
  53826. for (index = 0, cache = spheres.length; index < cache; index++) {
  53827. var parsedSphere = spheres[index];
  53828. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53829. }
  53830. }
  53831. // Cylinders
  53832. var cylinders = geometries.cylinders;
  53833. if (cylinders !== undefined && cylinders !== null) {
  53834. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53835. var parsedCylinder = cylinders[index];
  53836. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53837. }
  53838. }
  53839. // Toruses
  53840. var toruses = geometries.toruses;
  53841. if (toruses !== undefined && toruses !== null) {
  53842. for (index = 0, cache = toruses.length; index < cache; index++) {
  53843. var parsedTorus = toruses[index];
  53844. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53845. }
  53846. }
  53847. // Grounds
  53848. var grounds = geometries.grounds;
  53849. if (grounds !== undefined && grounds !== null) {
  53850. for (index = 0, cache = grounds.length; index < cache; index++) {
  53851. var parsedGround = grounds[index];
  53852. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53853. }
  53854. }
  53855. // Planes
  53856. var planes = geometries.planes;
  53857. if (planes !== undefined && planes !== null) {
  53858. for (index = 0, cache = planes.length; index < cache; index++) {
  53859. var parsedPlane = planes[index];
  53860. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53861. }
  53862. }
  53863. // TorusKnots
  53864. var torusKnots = geometries.torusKnots;
  53865. if (torusKnots !== undefined && torusKnots !== null) {
  53866. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53867. var parsedTorusKnot = torusKnots[index];
  53868. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53869. }
  53870. }
  53871. // VertexData
  53872. var vertexData = geometries.vertexData;
  53873. if (vertexData !== undefined && vertexData !== null) {
  53874. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53875. var parsedVertexData = vertexData[index];
  53876. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53877. }
  53878. }
  53879. }
  53880. // Transform nodes
  53881. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53882. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53883. var parsedTransformNode = parsedData.transformNodes[index];
  53884. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53885. }
  53886. }
  53887. // Meshes
  53888. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53889. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53890. var parsedMesh = parsedData.meshes[index];
  53891. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53892. log += (index === 0 ? "\n\tMeshes:" : "");
  53893. log += "\n\t\t" + mesh.toString(fullDetails);
  53894. }
  53895. }
  53896. // Cameras
  53897. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53898. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53899. var parsedCamera = parsedData.cameras[index];
  53900. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53901. log += (index === 0 ? "\n\tCameras:" : "");
  53902. log += "\n\t\t" + camera.toString(fullDetails);
  53903. }
  53904. }
  53905. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53906. scene.setActiveCameraByID(parsedData.activeCameraID);
  53907. }
  53908. // Browsing all the graph to connect the dots
  53909. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53910. var camera = scene.cameras[index];
  53911. if (camera._waitingParentId) {
  53912. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53913. camera._waitingParentId = null;
  53914. }
  53915. }
  53916. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53917. var light_1 = scene.lights[index];
  53918. if (light_1 && light_1._waitingParentId) {
  53919. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53920. light_1._waitingParentId = null;
  53921. }
  53922. }
  53923. // Sounds
  53924. var loadedSounds = [];
  53925. var loadedSound;
  53926. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53927. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53928. var parsedSound = parsedData.sounds[index];
  53929. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53930. if (!parsedSound.url)
  53931. parsedSound.url = parsedSound.name;
  53932. if (!loadedSounds[parsedSound.url]) {
  53933. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53934. loadedSounds[parsedSound.url] = loadedSound;
  53935. }
  53936. else {
  53937. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53938. }
  53939. }
  53940. else {
  53941. new BABYLON.Sound(parsedSound.name, null, scene);
  53942. }
  53943. }
  53944. }
  53945. loadedSounds = [];
  53946. // Connect parents & children and parse actions
  53947. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53948. var transformNode = scene.transformNodes[index];
  53949. if (transformNode._waitingParentId) {
  53950. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53951. transformNode._waitingParentId = null;
  53952. }
  53953. }
  53954. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53955. var mesh = scene.meshes[index];
  53956. if (mesh._waitingParentId) {
  53957. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53958. mesh._waitingParentId = null;
  53959. }
  53960. if (mesh._waitingActions) {
  53961. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53962. mesh._waitingActions = null;
  53963. }
  53964. }
  53965. // freeze world matrix application
  53966. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53967. var currentMesh = scene.meshes[index];
  53968. if (currentMesh._waitingFreezeWorldMatrix) {
  53969. currentMesh.freezeWorldMatrix();
  53970. currentMesh._waitingFreezeWorldMatrix = null;
  53971. }
  53972. else {
  53973. currentMesh.computeWorldMatrix(true);
  53974. }
  53975. }
  53976. // Particles Systems
  53977. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53978. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53979. var parsedParticleSystem = parsedData.particleSystems[index];
  53980. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53981. }
  53982. }
  53983. // Environment texture
  53984. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53985. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53986. if (parsedData.createDefaultSkybox === true) {
  53987. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53988. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53989. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53990. }
  53991. }
  53992. // Lens flares
  53993. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53994. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53995. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53996. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53997. }
  53998. }
  53999. // Shadows
  54000. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  54001. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  54002. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  54003. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  54004. }
  54005. }
  54006. // Lights exclusions / inclusions
  54007. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54008. var light_2 = scene.lights[index];
  54009. // Excluded check
  54010. if (light_2._excludedMeshesIds.length > 0) {
  54011. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  54012. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  54013. if (excludedMesh) {
  54014. light_2.excludedMeshes.push(excludedMesh);
  54015. }
  54016. }
  54017. light_2._excludedMeshesIds = [];
  54018. }
  54019. // Included check
  54020. if (light_2._includedOnlyMeshesIds.length > 0) {
  54021. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  54022. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  54023. if (includedOnlyMesh) {
  54024. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  54025. }
  54026. }
  54027. light_2._includedOnlyMeshesIds = [];
  54028. }
  54029. }
  54030. // Actions (scene)
  54031. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  54032. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  54033. }
  54034. // Finish
  54035. return true;
  54036. }
  54037. catch (err) {
  54038. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  54039. if (onError) {
  54040. onError(msg, err);
  54041. }
  54042. else {
  54043. BABYLON.Tools.Log(msg);
  54044. throw err;
  54045. }
  54046. }
  54047. finally {
  54048. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54049. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54050. }
  54051. }
  54052. return false;
  54053. }
  54054. });
  54055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54056. })(BABYLON || (BABYLON = {}));
  54057. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  54058. var BABYLON;
  54059. (function (BABYLON) {
  54060. var FilesInput = /** @class */ (function () {
  54061. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  54062. this.onProcessFileCallback = function () { return true; };
  54063. this._engine = engine;
  54064. this._currentScene = scene;
  54065. this._sceneLoadedCallback = sceneLoadedCallback;
  54066. this._progressCallback = progressCallback;
  54067. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  54068. this._textureLoadingCallback = textureLoadingCallback;
  54069. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  54070. this._onReloadCallback = onReloadCallback;
  54071. this._errorCallback = errorCallback;
  54072. }
  54073. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  54074. var _this = this;
  54075. if (elementToMonitor) {
  54076. this._elementToMonitor = elementToMonitor;
  54077. this._dragEnterHandler = function (e) { _this.drag(e); };
  54078. this._dragOverHandler = function (e) { _this.drag(e); };
  54079. this._dropHandler = function (e) { _this.drop(e); };
  54080. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  54081. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  54082. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  54083. }
  54084. };
  54085. FilesInput.prototype.dispose = function () {
  54086. if (!this._elementToMonitor) {
  54087. return;
  54088. }
  54089. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  54090. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  54091. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  54092. };
  54093. FilesInput.prototype.renderFunction = function () {
  54094. if (this._additionalRenderLoopLogicCallback) {
  54095. this._additionalRenderLoopLogicCallback();
  54096. }
  54097. if (this._currentScene) {
  54098. if (this._textureLoadingCallback) {
  54099. var remaining = this._currentScene.getWaitingItemsCount();
  54100. if (remaining > 0) {
  54101. this._textureLoadingCallback(remaining);
  54102. }
  54103. }
  54104. this._currentScene.render();
  54105. }
  54106. };
  54107. FilesInput.prototype.drag = function (e) {
  54108. e.stopPropagation();
  54109. e.preventDefault();
  54110. };
  54111. FilesInput.prototype.drop = function (eventDrop) {
  54112. eventDrop.stopPropagation();
  54113. eventDrop.preventDefault();
  54114. this.loadFiles(eventDrop);
  54115. };
  54116. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  54117. var _this = this;
  54118. var reader = folder.createReader();
  54119. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  54120. reader.readEntries(function (entries) {
  54121. remaining.count += entries.length;
  54122. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  54123. var entry = entries_1[_i];
  54124. if (entry.isFile) {
  54125. entry.file(function (file) {
  54126. file.correctName = relativePath + file.name;
  54127. files.push(file);
  54128. if (--remaining.count === 0) {
  54129. callback();
  54130. }
  54131. });
  54132. }
  54133. else if (entry.isDirectory) {
  54134. _this._traverseFolder(entry, files, remaining, callback);
  54135. }
  54136. }
  54137. if (--remaining.count) {
  54138. callback();
  54139. }
  54140. });
  54141. };
  54142. FilesInput.prototype._processFiles = function (files) {
  54143. var skippedFiles = 0;
  54144. for (var i = 0; i < files.length; i++) {
  54145. var name = files[i].correctName.toLowerCase();
  54146. var extension = name.split('.').pop();
  54147. if (!this.onProcessFileCallback(files[i], name, extension)) {
  54148. skippedFiles++;
  54149. continue;
  54150. }
  54151. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  54152. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  54153. this._sceneFileToLoad = files[i];
  54154. }
  54155. else {
  54156. FilesInput.FilesToLoad[name] = files[i];
  54157. }
  54158. }
  54159. if (this._onReloadCallback) {
  54160. this._onReloadCallback(this._sceneFileToLoad);
  54161. }
  54162. else if (skippedFiles < files.length) {
  54163. this.reload();
  54164. }
  54165. };
  54166. FilesInput.prototype.loadFiles = function (event) {
  54167. var _this = this;
  54168. if (this._startingProcessingFilesCallback)
  54169. this._startingProcessingFilesCallback();
  54170. // Handling data transfer via drag'n'drop
  54171. if (event && event.dataTransfer && event.dataTransfer.files) {
  54172. this._filesToLoad = event.dataTransfer.files;
  54173. }
  54174. // Handling files from input files
  54175. if (event && event.target && event.target.files) {
  54176. this._filesToLoad = event.target.files;
  54177. }
  54178. if (this._filesToLoad && this._filesToLoad.length > 0) {
  54179. var files_1 = new Array();
  54180. var folders = [];
  54181. var items = event.dataTransfer ? event.dataTransfer.items : null;
  54182. for (var i = 0; i < this._filesToLoad.length; i++) {
  54183. var fileToLoad = this._filesToLoad[i];
  54184. var name_1 = fileToLoad.name.toLowerCase();
  54185. var entry = void 0;
  54186. fileToLoad.correctName = name_1;
  54187. if (items) {
  54188. var item = items[i];
  54189. if (item.getAsEntry) {
  54190. entry = item.getAsEntry();
  54191. }
  54192. else if (item.webkitGetAsEntry) {
  54193. entry = item.webkitGetAsEntry();
  54194. }
  54195. }
  54196. if (!entry) {
  54197. files_1.push(fileToLoad);
  54198. }
  54199. else {
  54200. if (entry.isDirectory) {
  54201. folders.push(entry);
  54202. }
  54203. else {
  54204. files_1.push(fileToLoad);
  54205. }
  54206. }
  54207. }
  54208. if (folders.length === 0) {
  54209. this._processFiles(files_1);
  54210. }
  54211. else {
  54212. var remaining = { count: folders.length };
  54213. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  54214. var folder = folders_1[_i];
  54215. this._traverseFolder(folder, files_1, remaining, function () {
  54216. _this._processFiles(files_1);
  54217. });
  54218. }
  54219. }
  54220. }
  54221. };
  54222. FilesInput.prototype.reload = function () {
  54223. var _this = this;
  54224. // If a ".babylon" file has been provided
  54225. if (this._sceneFileToLoad) {
  54226. if (this._currentScene) {
  54227. if (BABYLON.Tools.errorsCount > 0) {
  54228. BABYLON.Tools.ClearLogCache();
  54229. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  54230. }
  54231. this._engine.stopRenderLoop();
  54232. this._currentScene.dispose();
  54233. }
  54234. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  54235. _this._currentScene = newScene;
  54236. if (_this._sceneLoadedCallback) {
  54237. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  54238. }
  54239. // Wait for textures and shaders to be ready
  54240. _this._currentScene.executeWhenReady(function () {
  54241. _this._engine.runRenderLoop(function () {
  54242. _this.renderFunction();
  54243. });
  54244. });
  54245. }, function (progress) {
  54246. if (_this._progressCallback) {
  54247. _this._progressCallback(progress);
  54248. }
  54249. }, function (scene, message) {
  54250. _this._currentScene = scene;
  54251. if (_this._errorCallback) {
  54252. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  54253. }
  54254. });
  54255. }
  54256. else {
  54257. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  54258. }
  54259. };
  54260. FilesInput.FilesToLoad = {};
  54261. return FilesInput;
  54262. }());
  54263. BABYLON.FilesInput = FilesInput;
  54264. })(BABYLON || (BABYLON = {}));
  54265. //# sourceMappingURL=babylon.filesInput.js.map
  54266. var BABYLON;
  54267. (function (BABYLON) {
  54268. /**
  54269. * This class implement a typical dictionary using a string as key and the generic type T as value.
  54270. * The underlying implementation relies on an associative array to ensure the best performances.
  54271. * The value can be anything including 'null' but except 'undefined'
  54272. */
  54273. var StringDictionary = /** @class */ (function () {
  54274. function StringDictionary() {
  54275. this._count = 0;
  54276. this._data = {};
  54277. }
  54278. /**
  54279. * This will clear this dictionary and copy the content from the 'source' one.
  54280. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  54281. * @param source the dictionary to take the content from and copy to this dictionary
  54282. */
  54283. StringDictionary.prototype.copyFrom = function (source) {
  54284. var _this = this;
  54285. this.clear();
  54286. source.forEach(function (t, v) { return _this.add(t, v); });
  54287. };
  54288. /**
  54289. * Get a value based from its key
  54290. * @param key the given key to get the matching value from
  54291. * @return the value if found, otherwise undefined is returned
  54292. */
  54293. StringDictionary.prototype.get = function (key) {
  54294. var val = this._data[key];
  54295. if (val !== undefined) {
  54296. return val;
  54297. }
  54298. return undefined;
  54299. };
  54300. /**
  54301. * Get a value from its key or add it if it doesn't exist.
  54302. * This method will ensure you that a given key/data will be present in the dictionary.
  54303. * @param key the given key to get the matching value from
  54304. * @param factory the factory that will create the value if the key is not present in the dictionary.
  54305. * The factory will only be invoked if there's no data for the given key.
  54306. * @return the value corresponding to the key.
  54307. */
  54308. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  54309. var val = this.get(key);
  54310. if (val !== undefined) {
  54311. return val;
  54312. }
  54313. val = factory(key);
  54314. if (val) {
  54315. this.add(key, val);
  54316. }
  54317. return val;
  54318. };
  54319. /**
  54320. * Get a value from its key if present in the dictionary otherwise add it
  54321. * @param key the key to get the value from
  54322. * @param val if there's no such key/value pair in the dictionary add it with this value
  54323. * @return the value corresponding to the key
  54324. */
  54325. StringDictionary.prototype.getOrAdd = function (key, val) {
  54326. var curVal = this.get(key);
  54327. if (curVal !== undefined) {
  54328. return curVal;
  54329. }
  54330. this.add(key, val);
  54331. return val;
  54332. };
  54333. /**
  54334. * Check if there's a given key in the dictionary
  54335. * @param key the key to check for
  54336. * @return true if the key is present, false otherwise
  54337. */
  54338. StringDictionary.prototype.contains = function (key) {
  54339. return this._data[key] !== undefined;
  54340. };
  54341. /**
  54342. * Add a new key and its corresponding value
  54343. * @param key the key to add
  54344. * @param value the value corresponding to the key
  54345. * @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
  54346. */
  54347. StringDictionary.prototype.add = function (key, value) {
  54348. if (this._data[key] !== undefined) {
  54349. return false;
  54350. }
  54351. this._data[key] = value;
  54352. ++this._count;
  54353. return true;
  54354. };
  54355. StringDictionary.prototype.set = function (key, value) {
  54356. if (this._data[key] === undefined) {
  54357. return false;
  54358. }
  54359. this._data[key] = value;
  54360. return true;
  54361. };
  54362. /**
  54363. * Get the element of the given key and remove it from the dictionary
  54364. * @param key
  54365. */
  54366. StringDictionary.prototype.getAndRemove = function (key) {
  54367. var val = this.get(key);
  54368. if (val !== undefined) {
  54369. delete this._data[key];
  54370. --this._count;
  54371. return val;
  54372. }
  54373. return null;
  54374. };
  54375. /**
  54376. * Remove a key/value from the dictionary.
  54377. * @param key the key to remove
  54378. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  54379. */
  54380. StringDictionary.prototype.remove = function (key) {
  54381. if (this.contains(key)) {
  54382. delete this._data[key];
  54383. --this._count;
  54384. return true;
  54385. }
  54386. return false;
  54387. };
  54388. /**
  54389. * Clear the whole content of the dictionary
  54390. */
  54391. StringDictionary.prototype.clear = function () {
  54392. this._data = {};
  54393. this._count = 0;
  54394. };
  54395. Object.defineProperty(StringDictionary.prototype, "count", {
  54396. get: function () {
  54397. return this._count;
  54398. },
  54399. enumerable: true,
  54400. configurable: true
  54401. });
  54402. /**
  54403. * Execute a callback on each key/val of the dictionary.
  54404. * Note that you can remove any element in this dictionary in the callback implementation
  54405. * @param callback the callback to execute on a given key/value pair
  54406. */
  54407. StringDictionary.prototype.forEach = function (callback) {
  54408. for (var cur in this._data) {
  54409. var val = this._data[cur];
  54410. callback(cur, val);
  54411. }
  54412. };
  54413. /**
  54414. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  54415. * If the callback returns null or undefined the method will iterate to the next key/value pair
  54416. * Note that you can remove any element in this dictionary in the callback implementation
  54417. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  54418. */
  54419. StringDictionary.prototype.first = function (callback) {
  54420. for (var cur in this._data) {
  54421. var val = this._data[cur];
  54422. var res = callback(cur, val);
  54423. if (res) {
  54424. return res;
  54425. }
  54426. }
  54427. return null;
  54428. };
  54429. return StringDictionary;
  54430. }());
  54431. BABYLON.StringDictionary = StringDictionary;
  54432. })(BABYLON || (BABYLON = {}));
  54433. //# sourceMappingURL=babylon.stringDictionary.js.map
  54434. var BABYLON;
  54435. (function (BABYLON) {
  54436. var Tags = /** @class */ (function () {
  54437. function Tags() {
  54438. }
  54439. Tags.EnableFor = function (obj) {
  54440. obj._tags = obj._tags || {};
  54441. obj.hasTags = function () {
  54442. return Tags.HasTags(obj);
  54443. };
  54444. obj.addTags = function (tagsString) {
  54445. return Tags.AddTagsTo(obj, tagsString);
  54446. };
  54447. obj.removeTags = function (tagsString) {
  54448. return Tags.RemoveTagsFrom(obj, tagsString);
  54449. };
  54450. obj.matchesTagsQuery = function (tagsQuery) {
  54451. return Tags.MatchesQuery(obj, tagsQuery);
  54452. };
  54453. };
  54454. Tags.DisableFor = function (obj) {
  54455. delete obj._tags;
  54456. delete obj.hasTags;
  54457. delete obj.addTags;
  54458. delete obj.removeTags;
  54459. delete obj.matchesTagsQuery;
  54460. };
  54461. Tags.HasTags = function (obj) {
  54462. if (!obj._tags) {
  54463. return false;
  54464. }
  54465. return !BABYLON.Tools.IsEmpty(obj._tags);
  54466. };
  54467. Tags.GetTags = function (obj, asString) {
  54468. if (asString === void 0) { asString = true; }
  54469. if (!obj._tags) {
  54470. return null;
  54471. }
  54472. if (asString) {
  54473. var tagsArray = [];
  54474. for (var tag in obj._tags) {
  54475. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  54476. tagsArray.push(tag);
  54477. }
  54478. }
  54479. return tagsArray.join(" ");
  54480. }
  54481. else {
  54482. return obj._tags;
  54483. }
  54484. };
  54485. // the tags 'true' and 'false' are reserved and cannot be used as tags
  54486. // a tag cannot start with '||', '&&', and '!'
  54487. // it cannot contain whitespaces
  54488. Tags.AddTagsTo = function (obj, tagsString) {
  54489. if (!tagsString) {
  54490. return;
  54491. }
  54492. if (typeof tagsString !== "string") {
  54493. return;
  54494. }
  54495. var tags = tagsString.split(" ");
  54496. tags.forEach(function (tag, index, array) {
  54497. Tags._AddTagTo(obj, tag);
  54498. });
  54499. };
  54500. Tags._AddTagTo = function (obj, tag) {
  54501. tag = tag.trim();
  54502. if (tag === "" || tag === "true" || tag === "false") {
  54503. return;
  54504. }
  54505. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  54506. return;
  54507. }
  54508. Tags.EnableFor(obj);
  54509. obj._tags[tag] = true;
  54510. };
  54511. Tags.RemoveTagsFrom = function (obj, tagsString) {
  54512. if (!Tags.HasTags(obj)) {
  54513. return;
  54514. }
  54515. var tags = tagsString.split(" ");
  54516. for (var t in tags) {
  54517. Tags._RemoveTagFrom(obj, tags[t]);
  54518. }
  54519. };
  54520. Tags._RemoveTagFrom = function (obj, tag) {
  54521. delete obj._tags[tag];
  54522. };
  54523. Tags.MatchesQuery = function (obj, tagsQuery) {
  54524. if (tagsQuery === undefined) {
  54525. return true;
  54526. }
  54527. if (tagsQuery === "") {
  54528. return Tags.HasTags(obj);
  54529. }
  54530. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  54531. };
  54532. return Tags;
  54533. }());
  54534. BABYLON.Tags = Tags;
  54535. })(BABYLON || (BABYLON = {}));
  54536. //# sourceMappingURL=babylon.tags.js.map
  54537. var BABYLON;
  54538. (function (BABYLON) {
  54539. var Internals;
  54540. (function (Internals) {
  54541. var AndOrNotEvaluator = /** @class */ (function () {
  54542. function AndOrNotEvaluator() {
  54543. }
  54544. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54545. if (!query.match(/\([^\(\)]*\)/g)) {
  54546. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54547. }
  54548. else {
  54549. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54550. // remove parenthesis
  54551. r = r.slice(1, r.length - 1);
  54552. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54553. });
  54554. }
  54555. if (query === "true") {
  54556. return true;
  54557. }
  54558. if (query === "false") {
  54559. return false;
  54560. }
  54561. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54562. };
  54563. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54564. evaluateCallback = evaluateCallback || (function (r) {
  54565. return r === "true" ? true : false;
  54566. });
  54567. var result;
  54568. var or = parenthesisContent.split("||");
  54569. for (var i in or) {
  54570. if (or.hasOwnProperty(i)) {
  54571. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54572. var and = ori.split("&&");
  54573. if (and.length > 1) {
  54574. for (var j = 0; j < and.length; ++j) {
  54575. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54576. if (andj !== "true" && andj !== "false") {
  54577. if (andj[0] === "!") {
  54578. result = !evaluateCallback(andj.substring(1));
  54579. }
  54580. else {
  54581. result = evaluateCallback(andj);
  54582. }
  54583. }
  54584. else {
  54585. result = andj === "true" ? true : false;
  54586. }
  54587. if (!result) {
  54588. ori = "false";
  54589. break;
  54590. }
  54591. }
  54592. }
  54593. if (result || ori === "true") {
  54594. result = true;
  54595. break;
  54596. }
  54597. // result equals false (or undefined)
  54598. if (ori !== "true" && ori !== "false") {
  54599. if (ori[0] === "!") {
  54600. result = !evaluateCallback(ori.substring(1));
  54601. }
  54602. else {
  54603. result = evaluateCallback(ori);
  54604. }
  54605. }
  54606. else {
  54607. result = ori === "true" ? true : false;
  54608. }
  54609. }
  54610. }
  54611. // the whole parenthesis scope is replaced by 'true' or 'false'
  54612. return result ? "true" : "false";
  54613. };
  54614. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54615. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54616. // remove whitespaces
  54617. r = r.replace(/[\s]/g, function () { return ""; });
  54618. return r.length % 2 ? "!" : "";
  54619. });
  54620. booleanString = booleanString.trim();
  54621. if (booleanString === "!true") {
  54622. booleanString = "false";
  54623. }
  54624. else if (booleanString === "!false") {
  54625. booleanString = "true";
  54626. }
  54627. return booleanString;
  54628. };
  54629. return AndOrNotEvaluator;
  54630. }());
  54631. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54632. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54633. })(BABYLON || (BABYLON = {}));
  54634. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54635. var BABYLON;
  54636. (function (BABYLON) {
  54637. var Database = /** @class */ (function () {
  54638. function Database(urlToScene, callbackManifestChecked) {
  54639. // Handling various flavors of prefixed version of IndexedDB
  54640. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54641. this.callbackManifestChecked = callbackManifestChecked;
  54642. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54643. this.db = null;
  54644. this._enableSceneOffline = false;
  54645. this._enableTexturesOffline = false;
  54646. this.manifestVersionFound = 0;
  54647. this.mustUpdateRessources = false;
  54648. this.hasReachedQuota = false;
  54649. if (!Database.IDBStorageEnabled) {
  54650. this.callbackManifestChecked(true);
  54651. }
  54652. else {
  54653. this.checkManifestFile();
  54654. }
  54655. }
  54656. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54657. get: function () {
  54658. return this._enableSceneOffline;
  54659. },
  54660. enumerable: true,
  54661. configurable: true
  54662. });
  54663. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54664. get: function () {
  54665. return this._enableTexturesOffline;
  54666. },
  54667. enumerable: true,
  54668. configurable: true
  54669. });
  54670. Database.prototype.checkManifestFile = function () {
  54671. var _this = this;
  54672. var noManifestFile = function () {
  54673. _this._enableSceneOffline = false;
  54674. _this._enableTexturesOffline = false;
  54675. _this.callbackManifestChecked(false);
  54676. };
  54677. var timeStampUsed = false;
  54678. var manifestURL = this.currentSceneUrl + ".manifest";
  54679. var xhr = new XMLHttpRequest();
  54680. if (navigator.onLine) {
  54681. // Adding a timestamp to by-pass browsers' cache
  54682. timeStampUsed = true;
  54683. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54684. }
  54685. xhr.open("GET", manifestURL, true);
  54686. xhr.addEventListener("load", function () {
  54687. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54688. try {
  54689. var manifestFile = JSON.parse(xhr.response);
  54690. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54691. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54692. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54693. _this.manifestVersionFound = manifestFile.version;
  54694. }
  54695. if (_this.callbackManifestChecked) {
  54696. _this.callbackManifestChecked(true);
  54697. }
  54698. }
  54699. catch (ex) {
  54700. noManifestFile();
  54701. }
  54702. }
  54703. else {
  54704. noManifestFile();
  54705. }
  54706. }, false);
  54707. xhr.addEventListener("error", function (event) {
  54708. if (timeStampUsed) {
  54709. timeStampUsed = false;
  54710. // Let's retry without the timeStamp
  54711. // It could fail when coupled with HTML5 Offline API
  54712. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54713. xhr.open("GET", retryManifestURL, true);
  54714. xhr.send();
  54715. }
  54716. else {
  54717. noManifestFile();
  54718. }
  54719. }, false);
  54720. try {
  54721. xhr.send();
  54722. }
  54723. catch (ex) {
  54724. BABYLON.Tools.Error("Error on XHR send request.");
  54725. this.callbackManifestChecked(false);
  54726. }
  54727. };
  54728. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54729. var _this = this;
  54730. var handleError = function () {
  54731. _this.isSupported = false;
  54732. if (errorCallback)
  54733. errorCallback();
  54734. };
  54735. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54736. // Your browser doesn't support IndexedDB
  54737. this.isSupported = false;
  54738. if (errorCallback)
  54739. errorCallback();
  54740. }
  54741. else {
  54742. // If the DB hasn't been opened or created yet
  54743. if (!this.db) {
  54744. this.hasReachedQuota = false;
  54745. this.isSupported = true;
  54746. var request = this.idbFactory.open("babylonjs", 1);
  54747. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54748. request.onerror = function (event) {
  54749. handleError();
  54750. };
  54751. // executes when a version change transaction cannot complete due to other active transactions
  54752. request.onblocked = function (event) {
  54753. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54754. handleError();
  54755. };
  54756. // DB has been opened successfully
  54757. request.onsuccess = function (event) {
  54758. _this.db = request.result;
  54759. successCallback();
  54760. };
  54761. // Initialization of the DB. Creating Scenes & Textures stores
  54762. request.onupgradeneeded = function (event) {
  54763. _this.db = (event.target).result;
  54764. if (_this.db) {
  54765. try {
  54766. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54767. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54768. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54769. }
  54770. catch (ex) {
  54771. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54772. handleError();
  54773. }
  54774. }
  54775. };
  54776. }
  54777. else {
  54778. if (successCallback)
  54779. successCallback();
  54780. }
  54781. }
  54782. };
  54783. Database.prototype.loadImageFromDB = function (url, image) {
  54784. var _this = this;
  54785. var completeURL = Database.ReturnFullUrlLocation(url);
  54786. var saveAndLoadImage = function () {
  54787. if (!_this.hasReachedQuota && _this.db !== null) {
  54788. // the texture is not yet in the DB, let's try to save it
  54789. _this._saveImageIntoDBAsync(completeURL, image);
  54790. }
  54791. else {
  54792. image.src = url;
  54793. }
  54794. };
  54795. if (!this.mustUpdateRessources) {
  54796. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54797. }
  54798. else {
  54799. saveAndLoadImage();
  54800. }
  54801. };
  54802. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54803. if (this.isSupported && this.db !== null) {
  54804. var texture;
  54805. var transaction = this.db.transaction(["textures"]);
  54806. transaction.onabort = function (event) {
  54807. image.src = url;
  54808. };
  54809. transaction.oncomplete = function (event) {
  54810. var blobTextureURL;
  54811. if (texture) {
  54812. var URL = window.URL || window.webkitURL;
  54813. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54814. image.onerror = function () {
  54815. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54816. image.src = url;
  54817. };
  54818. image.src = blobTextureURL;
  54819. }
  54820. else {
  54821. notInDBCallback();
  54822. }
  54823. };
  54824. var getRequest = transaction.objectStore("textures").get(url);
  54825. getRequest.onsuccess = function (event) {
  54826. texture = (event.target).result;
  54827. };
  54828. getRequest.onerror = function (event) {
  54829. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54830. image.src = url;
  54831. };
  54832. }
  54833. else {
  54834. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54835. image.src = url;
  54836. }
  54837. };
  54838. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54839. var _this = this;
  54840. if (this.isSupported) {
  54841. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54842. var generateBlobUrl = function () {
  54843. var blobTextureURL;
  54844. if (blob) {
  54845. var URL = window.URL || window.webkitURL;
  54846. try {
  54847. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54848. }
  54849. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54850. catch (ex) {
  54851. blobTextureURL = URL.createObjectURL(blob);
  54852. }
  54853. }
  54854. if (blobTextureURL) {
  54855. image.src = blobTextureURL;
  54856. }
  54857. };
  54858. if (Database.IsUASupportingBlobStorage) {
  54859. var xhr = new XMLHttpRequest(), blob;
  54860. xhr.open("GET", url, true);
  54861. xhr.responseType = "blob";
  54862. xhr.addEventListener("load", function () {
  54863. if (xhr.status === 200 && _this.db) {
  54864. // Blob as response (XHR2)
  54865. blob = xhr.response;
  54866. var transaction = _this.db.transaction(["textures"], "readwrite");
  54867. // the transaction could abort because of a QuotaExceededError error
  54868. transaction.onabort = function (event) {
  54869. try {
  54870. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54871. var srcElement = (event.srcElement || event.target);
  54872. var error = srcElement.error;
  54873. if (error && error.name === "QuotaExceededError") {
  54874. _this.hasReachedQuota = true;
  54875. }
  54876. }
  54877. catch (ex) { }
  54878. generateBlobUrl();
  54879. };
  54880. transaction.oncomplete = function (event) {
  54881. generateBlobUrl();
  54882. };
  54883. var newTexture = { textureUrl: url, data: blob };
  54884. try {
  54885. // Put the blob into the dabase
  54886. var addRequest = transaction.objectStore("textures").put(newTexture);
  54887. addRequest.onsuccess = function (event) {
  54888. };
  54889. addRequest.onerror = function (event) {
  54890. generateBlobUrl();
  54891. };
  54892. }
  54893. catch (ex) {
  54894. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54895. if (ex.code === 25) {
  54896. Database.IsUASupportingBlobStorage = false;
  54897. }
  54898. image.src = url;
  54899. }
  54900. }
  54901. else {
  54902. image.src = url;
  54903. }
  54904. }, false);
  54905. xhr.addEventListener("error", function (event) {
  54906. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54907. image.src = url;
  54908. }, false);
  54909. xhr.send();
  54910. }
  54911. else {
  54912. image.src = url;
  54913. }
  54914. }
  54915. else {
  54916. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54917. image.src = url;
  54918. }
  54919. };
  54920. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54921. var _this = this;
  54922. var updateVersion = function () {
  54923. // the version is not yet in the DB or we need to update it
  54924. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54925. };
  54926. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54927. };
  54928. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54929. var _this = this;
  54930. if (this.isSupported && this.db) {
  54931. var version;
  54932. try {
  54933. var transaction = this.db.transaction(["versions"]);
  54934. transaction.oncomplete = function (event) {
  54935. if (version) {
  54936. // If the version in the JSON file is > than the version in DB
  54937. if (_this.manifestVersionFound > version.data) {
  54938. _this.mustUpdateRessources = true;
  54939. updateInDBCallback();
  54940. }
  54941. else {
  54942. callback(version.data);
  54943. }
  54944. }
  54945. else {
  54946. _this.mustUpdateRessources = true;
  54947. updateInDBCallback();
  54948. }
  54949. };
  54950. transaction.onabort = function (event) {
  54951. callback(-1);
  54952. };
  54953. var getRequest = transaction.objectStore("versions").get(url);
  54954. getRequest.onsuccess = function (event) {
  54955. version = (event.target).result;
  54956. };
  54957. getRequest.onerror = function (event) {
  54958. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54959. callback(-1);
  54960. };
  54961. }
  54962. catch (ex) {
  54963. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54964. callback(-1);
  54965. }
  54966. }
  54967. else {
  54968. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54969. callback(-1);
  54970. }
  54971. };
  54972. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54973. var _this = this;
  54974. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54975. try {
  54976. // Open a transaction to the database
  54977. var transaction = this.db.transaction(["versions"], "readwrite");
  54978. // the transaction could abort because of a QuotaExceededError error
  54979. transaction.onabort = function (event) {
  54980. try {
  54981. var error = event.srcElement['error'];
  54982. if (error && error.name === "QuotaExceededError") {
  54983. _this.hasReachedQuota = true;
  54984. }
  54985. }
  54986. catch (ex) { }
  54987. callback(-1);
  54988. };
  54989. transaction.oncomplete = function (event) {
  54990. callback(_this.manifestVersionFound);
  54991. };
  54992. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54993. // Put the scene into the database
  54994. var addRequest = transaction.objectStore("versions").put(newVersion);
  54995. addRequest.onsuccess = function (event) {
  54996. };
  54997. addRequest.onerror = function (event) {
  54998. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54999. };
  55000. }
  55001. catch (ex) {
  55002. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  55003. callback(-1);
  55004. }
  55005. }
  55006. else {
  55007. callback(-1);
  55008. }
  55009. };
  55010. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  55011. var _this = this;
  55012. var completeUrl = Database.ReturnFullUrlLocation(url);
  55013. var saveAndLoadFile = function () {
  55014. // the scene is not yet in the DB, let's try to save it
  55015. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  55016. };
  55017. this._checkVersionFromDB(completeUrl, function (version) {
  55018. if (version !== -1) {
  55019. if (!_this.mustUpdateRessources) {
  55020. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  55021. }
  55022. else {
  55023. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  55024. }
  55025. }
  55026. else {
  55027. if (errorCallback) {
  55028. errorCallback();
  55029. }
  55030. }
  55031. });
  55032. };
  55033. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  55034. if (this.isSupported && this.db) {
  55035. var targetStore;
  55036. if (url.indexOf(".babylon") !== -1) {
  55037. targetStore = "scenes";
  55038. }
  55039. else {
  55040. targetStore = "textures";
  55041. }
  55042. var file;
  55043. var transaction = this.db.transaction([targetStore]);
  55044. transaction.oncomplete = function (event) {
  55045. if (file) {
  55046. callback(file.data);
  55047. }
  55048. else {
  55049. notInDBCallback();
  55050. }
  55051. };
  55052. transaction.onabort = function (event) {
  55053. notInDBCallback();
  55054. };
  55055. var getRequest = transaction.objectStore(targetStore).get(url);
  55056. getRequest.onsuccess = function (event) {
  55057. file = (event.target).result;
  55058. };
  55059. getRequest.onerror = function (event) {
  55060. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  55061. notInDBCallback();
  55062. };
  55063. }
  55064. else {
  55065. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55066. callback();
  55067. }
  55068. };
  55069. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  55070. var _this = this;
  55071. if (this.isSupported) {
  55072. var targetStore;
  55073. if (url.indexOf(".babylon") !== -1) {
  55074. targetStore = "scenes";
  55075. }
  55076. else {
  55077. targetStore = "textures";
  55078. }
  55079. // Create XHR
  55080. var xhr = new XMLHttpRequest();
  55081. var fileData;
  55082. xhr.open("GET", url, true);
  55083. if (useArrayBuffer) {
  55084. xhr.responseType = "arraybuffer";
  55085. }
  55086. if (progressCallback) {
  55087. xhr.onprogress = progressCallback;
  55088. }
  55089. xhr.addEventListener("load", function () {
  55090. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  55091. // Blob as response (XHR2)
  55092. //fileData = xhr.responseText;
  55093. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  55094. if (!_this.hasReachedQuota && _this.db) {
  55095. // Open a transaction to the database
  55096. var transaction = _this.db.transaction([targetStore], "readwrite");
  55097. // the transaction could abort because of a QuotaExceededError error
  55098. transaction.onabort = function (event) {
  55099. try {
  55100. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55101. var error = event.srcElement['error'];
  55102. if (error && error.name === "QuotaExceededError") {
  55103. _this.hasReachedQuota = true;
  55104. }
  55105. }
  55106. catch (ex) { }
  55107. callback(fileData);
  55108. };
  55109. transaction.oncomplete = function (event) {
  55110. callback(fileData);
  55111. };
  55112. var newFile;
  55113. if (targetStore === "scenes") {
  55114. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  55115. }
  55116. else {
  55117. newFile = { textureUrl: url, data: fileData };
  55118. }
  55119. try {
  55120. // Put the scene into the database
  55121. var addRequest = transaction.objectStore(targetStore).put(newFile);
  55122. addRequest.onsuccess = function (event) {
  55123. };
  55124. addRequest.onerror = function (event) {
  55125. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  55126. };
  55127. }
  55128. catch (ex) {
  55129. callback(fileData);
  55130. }
  55131. }
  55132. else {
  55133. callback(fileData);
  55134. }
  55135. }
  55136. else {
  55137. callback();
  55138. }
  55139. }, false);
  55140. xhr.addEventListener("error", function (event) {
  55141. BABYLON.Tools.Error("error on XHR request.");
  55142. callback();
  55143. }, false);
  55144. xhr.send();
  55145. }
  55146. else {
  55147. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55148. callback();
  55149. }
  55150. };
  55151. Database.IsUASupportingBlobStorage = true;
  55152. Database.IDBStorageEnabled = true;
  55153. Database.parseURL = function (url) {
  55154. var a = document.createElement('a');
  55155. a.href = url;
  55156. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  55157. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  55158. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  55159. return absLocation;
  55160. };
  55161. Database.ReturnFullUrlLocation = function (url) {
  55162. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  55163. return (Database.parseURL(window.location.href) + url);
  55164. }
  55165. else {
  55166. return url;
  55167. }
  55168. };
  55169. return Database;
  55170. }());
  55171. BABYLON.Database = Database;
  55172. })(BABYLON || (BABYLON = {}));
  55173. //# sourceMappingURL=babylon.database.js.map
  55174. var BABYLON;
  55175. (function (BABYLON) {
  55176. var FresnelParameters = /** @class */ (function () {
  55177. function FresnelParameters() {
  55178. this._isEnabled = true;
  55179. this.leftColor = BABYLON.Color3.White();
  55180. this.rightColor = BABYLON.Color3.Black();
  55181. this.bias = 0;
  55182. this.power = 1;
  55183. }
  55184. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  55185. get: function () {
  55186. return this._isEnabled;
  55187. },
  55188. set: function (value) {
  55189. if (this._isEnabled === value) {
  55190. return;
  55191. }
  55192. this._isEnabled = value;
  55193. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  55194. },
  55195. enumerable: true,
  55196. configurable: true
  55197. });
  55198. FresnelParameters.prototype.clone = function () {
  55199. var newFresnelParameters = new FresnelParameters();
  55200. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  55201. return newFresnelParameters;
  55202. };
  55203. FresnelParameters.prototype.serialize = function () {
  55204. var serializationObject = {};
  55205. serializationObject.isEnabled = this.isEnabled;
  55206. serializationObject.leftColor = this.leftColor;
  55207. serializationObject.rightColor = this.rightColor;
  55208. serializationObject.bias = this.bias;
  55209. serializationObject.power = this.power;
  55210. return serializationObject;
  55211. };
  55212. FresnelParameters.Parse = function (parsedFresnelParameters) {
  55213. var fresnelParameters = new FresnelParameters();
  55214. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  55215. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  55216. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  55217. fresnelParameters.bias = parsedFresnelParameters.bias;
  55218. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  55219. return fresnelParameters;
  55220. };
  55221. return FresnelParameters;
  55222. }());
  55223. BABYLON.FresnelParameters = FresnelParameters;
  55224. })(BABYLON || (BABYLON = {}));
  55225. //# sourceMappingURL=babylon.fresnelParameters.js.map
  55226. var BABYLON;
  55227. (function (BABYLON) {
  55228. var MultiMaterial = /** @class */ (function (_super) {
  55229. __extends(MultiMaterial, _super);
  55230. function MultiMaterial(name, scene) {
  55231. var _this = _super.call(this, name, scene, true) || this;
  55232. scene.multiMaterials.push(_this);
  55233. _this.subMaterials = new Array();
  55234. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  55235. return _this;
  55236. }
  55237. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  55238. get: function () {
  55239. return this._subMaterials;
  55240. },
  55241. set: function (value) {
  55242. this._subMaterials = value;
  55243. this._hookArray(value);
  55244. },
  55245. enumerable: true,
  55246. configurable: true
  55247. });
  55248. MultiMaterial.prototype._hookArray = function (array) {
  55249. var _this = this;
  55250. var oldPush = array.push;
  55251. array.push = function () {
  55252. var items = [];
  55253. for (var _i = 0; _i < arguments.length; _i++) {
  55254. items[_i] = arguments[_i];
  55255. }
  55256. var result = oldPush.apply(array, items);
  55257. _this._markAllSubMeshesAsTexturesDirty();
  55258. return result;
  55259. };
  55260. var oldSplice = array.splice;
  55261. array.splice = function (index, deleteCount) {
  55262. var deleted = oldSplice.apply(array, [index, deleteCount]);
  55263. _this._markAllSubMeshesAsTexturesDirty();
  55264. return deleted;
  55265. };
  55266. };
  55267. // Properties
  55268. MultiMaterial.prototype.getSubMaterial = function (index) {
  55269. if (index < 0 || index >= this.subMaterials.length) {
  55270. return this.getScene().defaultMaterial;
  55271. }
  55272. return this.subMaterials[index];
  55273. };
  55274. MultiMaterial.prototype.getActiveTextures = function () {
  55275. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  55276. if (subMaterial) {
  55277. return subMaterial.getActiveTextures();
  55278. }
  55279. else {
  55280. return [];
  55281. }
  55282. }));
  55283. var _a;
  55284. };
  55285. // Methods
  55286. MultiMaterial.prototype.getClassName = function () {
  55287. return "MultiMaterial";
  55288. };
  55289. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  55290. for (var index = 0; index < this.subMaterials.length; index++) {
  55291. var subMaterial = this.subMaterials[index];
  55292. if (subMaterial) {
  55293. if (subMaterial.storeEffectOnSubMeshes) {
  55294. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  55295. return false;
  55296. }
  55297. continue;
  55298. }
  55299. if (!subMaterial.isReady(mesh)) {
  55300. return false;
  55301. }
  55302. }
  55303. }
  55304. return true;
  55305. };
  55306. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  55307. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  55308. for (var index = 0; index < this.subMaterials.length; index++) {
  55309. var subMaterial = null;
  55310. var current = this.subMaterials[index];
  55311. if (cloneChildren && current) {
  55312. subMaterial = current.clone(name + "-" + current.name);
  55313. }
  55314. else {
  55315. subMaterial = this.subMaterials[index];
  55316. }
  55317. newMultiMaterial.subMaterials.push(subMaterial);
  55318. }
  55319. return newMultiMaterial;
  55320. };
  55321. MultiMaterial.prototype.serialize = function () {
  55322. var serializationObject = {};
  55323. serializationObject.name = this.name;
  55324. serializationObject.id = this.id;
  55325. if (BABYLON.Tags) {
  55326. serializationObject.tags = BABYLON.Tags.GetTags(this);
  55327. }
  55328. serializationObject.materials = [];
  55329. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  55330. var subMat = this.subMaterials[matIndex];
  55331. if (subMat) {
  55332. serializationObject.materials.push(subMat.id);
  55333. }
  55334. else {
  55335. serializationObject.materials.push(null);
  55336. }
  55337. }
  55338. return serializationObject;
  55339. };
  55340. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55341. var scene = this.getScene();
  55342. if (!scene) {
  55343. return;
  55344. }
  55345. var index = scene.multiMaterials.indexOf(this);
  55346. if (index >= 0) {
  55347. scene.multiMaterials.splice(index, 1);
  55348. }
  55349. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55350. };
  55351. return MultiMaterial;
  55352. }(BABYLON.Material));
  55353. BABYLON.MultiMaterial = MultiMaterial;
  55354. })(BABYLON || (BABYLON = {}));
  55355. //# sourceMappingURL=babylon.multiMaterial.js.map
  55356. var BABYLON;
  55357. (function (BABYLON) {
  55358. var FreeCameraTouchInput = /** @class */ (function () {
  55359. function FreeCameraTouchInput() {
  55360. this._offsetX = null;
  55361. this._offsetY = null;
  55362. this._pointerPressed = new Array();
  55363. this.touchAngularSensibility = 200000.0;
  55364. this.touchMoveSensibility = 250.0;
  55365. }
  55366. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  55367. var _this = this;
  55368. var previousPosition = null;
  55369. if (this._pointerInput === undefined) {
  55370. this._onLostFocus = function (evt) {
  55371. _this._offsetX = null;
  55372. _this._offsetY = null;
  55373. };
  55374. this._pointerInput = function (p, s) {
  55375. var evt = p.event;
  55376. if (evt.pointerType === "mouse") {
  55377. return;
  55378. }
  55379. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  55380. if (!noPreventDefault) {
  55381. evt.preventDefault();
  55382. }
  55383. _this._pointerPressed.push(evt.pointerId);
  55384. if (_this._pointerPressed.length !== 1) {
  55385. return;
  55386. }
  55387. previousPosition = {
  55388. x: evt.clientX,
  55389. y: evt.clientY
  55390. };
  55391. }
  55392. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  55393. if (!noPreventDefault) {
  55394. evt.preventDefault();
  55395. }
  55396. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55397. if (index === -1) {
  55398. return;
  55399. }
  55400. _this._pointerPressed.splice(index, 1);
  55401. if (index != 0) {
  55402. return;
  55403. }
  55404. previousPosition = null;
  55405. _this._offsetX = null;
  55406. _this._offsetY = null;
  55407. }
  55408. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  55409. if (!noPreventDefault) {
  55410. evt.preventDefault();
  55411. }
  55412. if (!previousPosition) {
  55413. return;
  55414. }
  55415. var index = _this._pointerPressed.indexOf(evt.pointerId);
  55416. if (index != 0) {
  55417. return;
  55418. }
  55419. _this._offsetX = evt.clientX - previousPosition.x;
  55420. _this._offsetY = -(evt.clientY - previousPosition.y);
  55421. }
  55422. };
  55423. }
  55424. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  55425. if (this._onLostFocus) {
  55426. element.addEventListener("blur", this._onLostFocus);
  55427. }
  55428. };
  55429. FreeCameraTouchInput.prototype.detachControl = function (element) {
  55430. if (this._pointerInput && element) {
  55431. if (this._observer) {
  55432. this.camera.getScene().onPointerObservable.remove(this._observer);
  55433. this._observer = null;
  55434. }
  55435. if (this._onLostFocus) {
  55436. element.removeEventListener("blur", this._onLostFocus);
  55437. this._onLostFocus = null;
  55438. }
  55439. this._pointerPressed = [];
  55440. this._offsetX = null;
  55441. this._offsetY = null;
  55442. }
  55443. };
  55444. FreeCameraTouchInput.prototype.checkInputs = function () {
  55445. if (this._offsetX && this._offsetY) {
  55446. var camera = this.camera;
  55447. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  55448. if (this._pointerPressed.length > 1) {
  55449. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  55450. }
  55451. else {
  55452. var speed = camera._computeLocalCameraSpeed();
  55453. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  55454. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  55455. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  55456. }
  55457. }
  55458. };
  55459. FreeCameraTouchInput.prototype.getClassName = function () {
  55460. return "FreeCameraTouchInput";
  55461. };
  55462. FreeCameraTouchInput.prototype.getSimpleName = function () {
  55463. return "touch";
  55464. };
  55465. __decorate([
  55466. BABYLON.serialize()
  55467. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  55468. __decorate([
  55469. BABYLON.serialize()
  55470. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  55471. return FreeCameraTouchInput;
  55472. }());
  55473. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  55474. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  55475. })(BABYLON || (BABYLON = {}));
  55476. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  55477. var BABYLON;
  55478. (function (BABYLON) {
  55479. // We're mainly based on the logic defined into the FreeCamera code
  55480. var TouchCamera = /** @class */ (function (_super) {
  55481. __extends(TouchCamera, _super);
  55482. //-- end properties for backward compatibility for inputs
  55483. function TouchCamera(name, position, scene) {
  55484. var _this = _super.call(this, name, position, scene) || this;
  55485. _this.inputs.addTouch();
  55486. _this._setupInputs();
  55487. return _this;
  55488. }
  55489. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  55490. //-- Begin properties for backward compatibility for inputs
  55491. get: function () {
  55492. var touch = this.inputs.attached["touch"];
  55493. if (touch)
  55494. return touch.touchAngularSensibility;
  55495. return 0;
  55496. },
  55497. set: function (value) {
  55498. var touch = this.inputs.attached["touch"];
  55499. if (touch)
  55500. touch.touchAngularSensibility = value;
  55501. },
  55502. enumerable: true,
  55503. configurable: true
  55504. });
  55505. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  55506. get: function () {
  55507. var touch = this.inputs.attached["touch"];
  55508. if (touch)
  55509. return touch.touchMoveSensibility;
  55510. return 0;
  55511. },
  55512. set: function (value) {
  55513. var touch = this.inputs.attached["touch"];
  55514. if (touch)
  55515. touch.touchMoveSensibility = value;
  55516. },
  55517. enumerable: true,
  55518. configurable: true
  55519. });
  55520. TouchCamera.prototype.getClassName = function () {
  55521. return "TouchCamera";
  55522. };
  55523. TouchCamera.prototype._setupInputs = function () {
  55524. var mouse = this.inputs.attached["mouse"];
  55525. if (mouse) {
  55526. mouse.touchEnabled = false;
  55527. }
  55528. };
  55529. return TouchCamera;
  55530. }(BABYLON.FreeCamera));
  55531. BABYLON.TouchCamera = TouchCamera;
  55532. })(BABYLON || (BABYLON = {}));
  55533. //# sourceMappingURL=babylon.touchCamera.js.map
  55534. var BABYLON;
  55535. (function (BABYLON) {
  55536. var ProceduralTexture = /** @class */ (function (_super) {
  55537. __extends(ProceduralTexture, _super);
  55538. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55539. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55540. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55541. if (isCube === void 0) { isCube = false; }
  55542. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55543. _this.isCube = isCube;
  55544. _this.isEnabled = true;
  55545. _this._currentRefreshId = -1;
  55546. _this._refreshRate = 1;
  55547. _this._vertexBuffers = {};
  55548. _this._uniforms = new Array();
  55549. _this._samplers = new Array();
  55550. _this._textures = {};
  55551. _this._floats = {};
  55552. _this._floatsArrays = {};
  55553. _this._colors3 = {};
  55554. _this._colors4 = {};
  55555. _this._vectors2 = {};
  55556. _this._vectors3 = {};
  55557. _this._matrices = {};
  55558. _this._fallbackTextureUsed = false;
  55559. scene._proceduralTextures.push(_this);
  55560. _this._engine = scene.getEngine();
  55561. _this.name = name;
  55562. _this.isRenderTarget = true;
  55563. _this._size = size;
  55564. _this._generateMipMaps = generateMipMaps;
  55565. _this.setFragment(fragment);
  55566. _this._fallbackTexture = fallbackTexture;
  55567. if (isCube) {
  55568. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55569. _this.setFloat("face", 0);
  55570. }
  55571. else {
  55572. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55573. }
  55574. // VBO
  55575. var vertices = [];
  55576. vertices.push(1, 1);
  55577. vertices.push(-1, 1);
  55578. vertices.push(-1, -1);
  55579. vertices.push(1, -1);
  55580. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55581. _this._createIndexBuffer();
  55582. return _this;
  55583. }
  55584. ProceduralTexture.prototype._createIndexBuffer = function () {
  55585. var engine = this._engine;
  55586. // Indices
  55587. var indices = [];
  55588. indices.push(0);
  55589. indices.push(1);
  55590. indices.push(2);
  55591. indices.push(0);
  55592. indices.push(2);
  55593. indices.push(3);
  55594. this._indexBuffer = engine.createIndexBuffer(indices);
  55595. };
  55596. ProceduralTexture.prototype._rebuild = function () {
  55597. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55598. if (vb) {
  55599. vb._rebuild();
  55600. }
  55601. this._createIndexBuffer();
  55602. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55603. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55604. }
  55605. };
  55606. ProceduralTexture.prototype.reset = function () {
  55607. if (this._effect === undefined) {
  55608. return;
  55609. }
  55610. var engine = this._engine;
  55611. engine._releaseEffect(this._effect);
  55612. };
  55613. ProceduralTexture.prototype.isReady = function () {
  55614. var _this = this;
  55615. var engine = this._engine;
  55616. var shaders;
  55617. if (!this._fragment) {
  55618. return false;
  55619. }
  55620. if (this._fallbackTextureUsed) {
  55621. return true;
  55622. }
  55623. if (this._fragment.fragmentElement !== undefined) {
  55624. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55625. }
  55626. else {
  55627. shaders = { vertex: "procedural", fragment: this._fragment };
  55628. }
  55629. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55630. _this.releaseInternalTexture();
  55631. if (_this._fallbackTexture) {
  55632. _this._texture = _this._fallbackTexture._texture;
  55633. if (_this._texture) {
  55634. _this._texture.incrementReferences();
  55635. }
  55636. }
  55637. _this._fallbackTextureUsed = true;
  55638. });
  55639. return this._effect.isReady();
  55640. };
  55641. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55642. this._currentRefreshId = -1;
  55643. };
  55644. ProceduralTexture.prototype.setFragment = function (fragment) {
  55645. this._fragment = fragment;
  55646. };
  55647. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55648. get: function () {
  55649. return this._refreshRate;
  55650. },
  55651. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55652. set: function (value) {
  55653. this._refreshRate = value;
  55654. this.resetRefreshCounter();
  55655. },
  55656. enumerable: true,
  55657. configurable: true
  55658. });
  55659. ProceduralTexture.prototype._shouldRender = function () {
  55660. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55661. return false;
  55662. }
  55663. if (this._fallbackTextureUsed) {
  55664. return false;
  55665. }
  55666. if (this._currentRefreshId === -1) {
  55667. this._currentRefreshId = 1;
  55668. return true;
  55669. }
  55670. if (this.refreshRate === this._currentRefreshId) {
  55671. this._currentRefreshId = 1;
  55672. return true;
  55673. }
  55674. this._currentRefreshId++;
  55675. return false;
  55676. };
  55677. ProceduralTexture.prototype.getRenderSize = function () {
  55678. return this._size;
  55679. };
  55680. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55681. if (this._fallbackTextureUsed) {
  55682. return;
  55683. }
  55684. this.releaseInternalTexture();
  55685. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55686. };
  55687. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55688. if (this._uniforms.indexOf(uniformName) === -1) {
  55689. this._uniforms.push(uniformName);
  55690. }
  55691. };
  55692. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55693. if (this._samplers.indexOf(name) === -1) {
  55694. this._samplers.push(name);
  55695. }
  55696. this._textures[name] = texture;
  55697. return this;
  55698. };
  55699. ProceduralTexture.prototype.setFloat = function (name, value) {
  55700. this._checkUniform(name);
  55701. this._floats[name] = value;
  55702. return this;
  55703. };
  55704. ProceduralTexture.prototype.setFloats = function (name, value) {
  55705. this._checkUniform(name);
  55706. this._floatsArrays[name] = value;
  55707. return this;
  55708. };
  55709. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55710. this._checkUniform(name);
  55711. this._colors3[name] = value;
  55712. return this;
  55713. };
  55714. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55715. this._checkUniform(name);
  55716. this._colors4[name] = value;
  55717. return this;
  55718. };
  55719. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55720. this._checkUniform(name);
  55721. this._vectors2[name] = value;
  55722. return this;
  55723. };
  55724. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55725. this._checkUniform(name);
  55726. this._vectors3[name] = value;
  55727. return this;
  55728. };
  55729. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55730. this._checkUniform(name);
  55731. this._matrices[name] = value;
  55732. return this;
  55733. };
  55734. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55735. var scene = this.getScene();
  55736. if (!scene) {
  55737. return;
  55738. }
  55739. var engine = this._engine;
  55740. // Render
  55741. engine.enableEffect(this._effect);
  55742. engine.setState(false);
  55743. // Texture
  55744. for (var name in this._textures) {
  55745. this._effect.setTexture(name, this._textures[name]);
  55746. }
  55747. // Float
  55748. for (name in this._floats) {
  55749. this._effect.setFloat(name, this._floats[name]);
  55750. }
  55751. // Floats
  55752. for (name in this._floatsArrays) {
  55753. this._effect.setArray(name, this._floatsArrays[name]);
  55754. }
  55755. // Color3
  55756. for (name in this._colors3) {
  55757. this._effect.setColor3(name, this._colors3[name]);
  55758. }
  55759. // Color4
  55760. for (name in this._colors4) {
  55761. var color = this._colors4[name];
  55762. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55763. }
  55764. // Vector2
  55765. for (name in this._vectors2) {
  55766. this._effect.setVector2(name, this._vectors2[name]);
  55767. }
  55768. // Vector3
  55769. for (name in this._vectors3) {
  55770. this._effect.setVector3(name, this._vectors3[name]);
  55771. }
  55772. // Matrix
  55773. for (name in this._matrices) {
  55774. this._effect.setMatrix(name, this._matrices[name]);
  55775. }
  55776. if (!this._texture) {
  55777. return;
  55778. }
  55779. if (this.isCube) {
  55780. for (var face = 0; face < 6; face++) {
  55781. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55782. // VBOs
  55783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55784. this._effect.setFloat("face", face);
  55785. // Clear
  55786. engine.clear(scene.clearColor, true, true, true);
  55787. // Draw order
  55788. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  55789. // Mipmaps
  55790. if (face === 5) {
  55791. engine.generateMipMapsForCubemap(this._texture);
  55792. }
  55793. }
  55794. }
  55795. else {
  55796. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55797. // VBOs
  55798. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55799. // Clear
  55800. engine.clear(scene.clearColor, true, true, true);
  55801. // Draw order
  55802. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  55803. }
  55804. // Unbind
  55805. engine.unBindFramebuffer(this._texture, this.isCube);
  55806. if (this.onGenerated) {
  55807. this.onGenerated();
  55808. }
  55809. };
  55810. ProceduralTexture.prototype.clone = function () {
  55811. var textureSize = this.getSize();
  55812. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55813. // Base texture
  55814. newTexture.hasAlpha = this.hasAlpha;
  55815. newTexture.level = this.level;
  55816. // RenderTarget Texture
  55817. newTexture.coordinatesMode = this.coordinatesMode;
  55818. return newTexture;
  55819. };
  55820. ProceduralTexture.prototype.dispose = function () {
  55821. var scene = this.getScene();
  55822. if (!scene) {
  55823. return;
  55824. }
  55825. var index = scene._proceduralTextures.indexOf(this);
  55826. if (index >= 0) {
  55827. scene._proceduralTextures.splice(index, 1);
  55828. }
  55829. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55830. if (vertexBuffer) {
  55831. vertexBuffer.dispose();
  55832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55833. }
  55834. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55835. this._indexBuffer = null;
  55836. }
  55837. _super.prototype.dispose.call(this);
  55838. };
  55839. return ProceduralTexture;
  55840. }(BABYLON.Texture));
  55841. BABYLON.ProceduralTexture = ProceduralTexture;
  55842. })(BABYLON || (BABYLON = {}));
  55843. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55844. var BABYLON;
  55845. (function (BABYLON) {
  55846. var CustomProceduralTexture = /** @class */ (function (_super) {
  55847. __extends(CustomProceduralTexture, _super);
  55848. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55849. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55850. _this._animate = true;
  55851. _this._time = 0;
  55852. _this._texturePath = texturePath;
  55853. //Try to load json
  55854. _this.loadJson(texturePath);
  55855. _this.refreshRate = 1;
  55856. return _this;
  55857. }
  55858. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55859. var _this = this;
  55860. var noConfigFile = function () {
  55861. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55862. try {
  55863. _this.setFragment(_this._texturePath);
  55864. }
  55865. catch (ex) {
  55866. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55867. }
  55868. };
  55869. var configFileUrl = jsonUrl + "/config.json";
  55870. var xhr = new XMLHttpRequest();
  55871. xhr.open("GET", configFileUrl, true);
  55872. xhr.addEventListener("load", function () {
  55873. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55874. try {
  55875. _this._config = JSON.parse(xhr.response);
  55876. _this.updateShaderUniforms();
  55877. _this.updateTextures();
  55878. _this.setFragment(_this._texturePath + "/custom");
  55879. _this._animate = _this._config.animate;
  55880. _this.refreshRate = _this._config.refreshrate;
  55881. }
  55882. catch (ex) {
  55883. noConfigFile();
  55884. }
  55885. }
  55886. else {
  55887. noConfigFile();
  55888. }
  55889. }, false);
  55890. xhr.addEventListener("error", function () {
  55891. noConfigFile();
  55892. }, false);
  55893. try {
  55894. xhr.send();
  55895. }
  55896. catch (ex) {
  55897. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55898. }
  55899. };
  55900. CustomProceduralTexture.prototype.isReady = function () {
  55901. if (!_super.prototype.isReady.call(this)) {
  55902. return false;
  55903. }
  55904. for (var name in this._textures) {
  55905. var texture = this._textures[name];
  55906. if (!texture.isReady()) {
  55907. return false;
  55908. }
  55909. }
  55910. return true;
  55911. };
  55912. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55913. var scene = this.getScene();
  55914. if (this._animate && scene) {
  55915. this._time += scene.getAnimationRatio() * 0.03;
  55916. this.updateShaderUniforms();
  55917. }
  55918. _super.prototype.render.call(this, useCameraPostProcess);
  55919. };
  55920. CustomProceduralTexture.prototype.updateTextures = function () {
  55921. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55922. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55923. }
  55924. };
  55925. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55926. if (this._config) {
  55927. for (var j = 0; j < this._config.uniforms.length; j++) {
  55928. var uniform = this._config.uniforms[j];
  55929. switch (uniform.type) {
  55930. case "float":
  55931. this.setFloat(uniform.name, uniform.value);
  55932. break;
  55933. case "color3":
  55934. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55935. break;
  55936. case "color4":
  55937. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55938. break;
  55939. case "vector2":
  55940. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55941. break;
  55942. case "vector3":
  55943. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55944. break;
  55945. }
  55946. }
  55947. }
  55948. this.setFloat("time", this._time);
  55949. };
  55950. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55951. get: function () {
  55952. return this._animate;
  55953. },
  55954. set: function (value) {
  55955. this._animate = value;
  55956. },
  55957. enumerable: true,
  55958. configurable: true
  55959. });
  55960. return CustomProceduralTexture;
  55961. }(BABYLON.ProceduralTexture));
  55962. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55963. })(BABYLON || (BABYLON = {}));
  55964. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55965. var BABYLON;
  55966. (function (BABYLON) {
  55967. var FreeCameraGamepadInput = /** @class */ (function () {
  55968. function FreeCameraGamepadInput() {
  55969. this.gamepadAngularSensibility = 200;
  55970. this.gamepadMoveSensibility = 40;
  55971. // private members
  55972. this._cameraTransform = BABYLON.Matrix.Identity();
  55973. this._deltaTransform = BABYLON.Vector3.Zero();
  55974. this._vector3 = BABYLON.Vector3.Zero();
  55975. this._vector2 = BABYLON.Vector2.Zero();
  55976. }
  55977. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55978. var _this = this;
  55979. var manager = this.camera.getScene().gamepadManager;
  55980. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55981. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55982. // prioritize XBOX gamepads.
  55983. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55984. _this.gamepad = gamepad;
  55985. }
  55986. }
  55987. });
  55988. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55989. if (_this.gamepad === gamepad) {
  55990. _this.gamepad = null;
  55991. }
  55992. });
  55993. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55994. };
  55995. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55996. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55997. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55998. this.gamepad = null;
  55999. };
  56000. FreeCameraGamepadInput.prototype.checkInputs = function () {
  56001. if (this.gamepad && this.gamepad.leftStick) {
  56002. var camera = this.camera;
  56003. var LSValues = this.gamepad.leftStick;
  56004. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  56005. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56006. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  56007. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  56008. var RSValues = this.gamepad.rightStick;
  56009. if (RSValues) {
  56010. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  56011. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  56012. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  56013. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  56014. }
  56015. else {
  56016. RSValues = { x: 0, y: 0 };
  56017. }
  56018. if (!camera.rotationQuaternion) {
  56019. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  56020. }
  56021. else {
  56022. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  56023. }
  56024. var speed = camera._computeLocalCameraSpeed() * 50.0;
  56025. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  56026. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  56027. camera.cameraDirection.addInPlace(this._deltaTransform);
  56028. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  56029. camera.cameraRotation.addInPlace(this._vector2);
  56030. }
  56031. };
  56032. FreeCameraGamepadInput.prototype.getClassName = function () {
  56033. return "FreeCameraGamepadInput";
  56034. };
  56035. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  56036. return "gamepad";
  56037. };
  56038. __decorate([
  56039. BABYLON.serialize()
  56040. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  56041. __decorate([
  56042. BABYLON.serialize()
  56043. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56044. return FreeCameraGamepadInput;
  56045. }());
  56046. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  56047. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  56048. })(BABYLON || (BABYLON = {}));
  56049. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  56050. var BABYLON;
  56051. (function (BABYLON) {
  56052. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  56053. function ArcRotateCameraGamepadInput() {
  56054. this.gamepadRotationSensibility = 80;
  56055. this.gamepadMoveSensibility = 40;
  56056. }
  56057. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56058. var _this = this;
  56059. var manager = this.camera.getScene().gamepadManager;
  56060. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56061. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56062. // prioritize XBOX gamepads.
  56063. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56064. _this.gamepad = gamepad;
  56065. }
  56066. }
  56067. });
  56068. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56069. if (_this.gamepad === gamepad) {
  56070. _this.gamepad = null;
  56071. }
  56072. });
  56073. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56074. };
  56075. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  56076. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56077. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56078. this.gamepad = null;
  56079. };
  56080. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  56081. if (this.gamepad) {
  56082. var camera = this.camera;
  56083. var RSValues = this.gamepad.rightStick;
  56084. if (RSValues) {
  56085. if (RSValues.x != 0) {
  56086. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  56087. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  56088. camera.inertialAlphaOffset += normalizedRX;
  56089. }
  56090. }
  56091. if (RSValues.y != 0) {
  56092. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  56093. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  56094. camera.inertialBetaOffset += normalizedRY;
  56095. }
  56096. }
  56097. }
  56098. var LSValues = this.gamepad.leftStick;
  56099. if (LSValues && LSValues.y != 0) {
  56100. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56101. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  56102. this.camera.inertialRadiusOffset -= normalizedLY;
  56103. }
  56104. }
  56105. }
  56106. };
  56107. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  56108. return "ArcRotateCameraGamepadInput";
  56109. };
  56110. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  56111. return "gamepad";
  56112. };
  56113. __decorate([
  56114. BABYLON.serialize()
  56115. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  56116. __decorate([
  56117. BABYLON.serialize()
  56118. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56119. return ArcRotateCameraGamepadInput;
  56120. }());
  56121. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  56122. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  56123. })(BABYLON || (BABYLON = {}));
  56124. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  56125. var BABYLON;
  56126. (function (BABYLON) {
  56127. var GamepadManager = /** @class */ (function () {
  56128. function GamepadManager(_scene) {
  56129. var _this = this;
  56130. this._scene = _scene;
  56131. this._babylonGamepads = [];
  56132. this._oneGamepadConnected = false;
  56133. this._isMonitoring = false;
  56134. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  56135. if (!BABYLON.Tools.IsWindowObjectExist()) {
  56136. this._gamepadEventSupported = false;
  56137. }
  56138. else {
  56139. this._gamepadEventSupported = 'GamepadEvent' in window;
  56140. this._gamepadSupport = (navigator.getGamepads ||
  56141. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  56142. }
  56143. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  56144. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  56145. for (var i in _this._babylonGamepads) {
  56146. var gamepad = _this._babylonGamepads[i];
  56147. if (gamepad && gamepad._isConnected) {
  56148. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  56149. }
  56150. }
  56151. });
  56152. this._onGamepadConnectedEvent = function (evt) {
  56153. var gamepad = evt.gamepad;
  56154. if (gamepad.index in _this._babylonGamepads) {
  56155. if (_this._babylonGamepads[gamepad.index].isConnected) {
  56156. return;
  56157. }
  56158. }
  56159. var newGamepad;
  56160. if (_this._babylonGamepads[gamepad.index]) {
  56161. newGamepad = _this._babylonGamepads[gamepad.index];
  56162. newGamepad.browserGamepad = gamepad;
  56163. newGamepad._isConnected = true;
  56164. }
  56165. else {
  56166. newGamepad = _this._addNewGamepad(gamepad);
  56167. }
  56168. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56169. _this._startMonitoringGamepads();
  56170. };
  56171. this._onGamepadDisconnectedEvent = function (evt) {
  56172. var gamepad = evt.gamepad;
  56173. // Remove the gamepad from the list of gamepads to monitor.
  56174. for (var i in _this._babylonGamepads) {
  56175. if (_this._babylonGamepads[i].index === gamepad.index) {
  56176. var disconnectedGamepad = _this._babylonGamepads[i];
  56177. disconnectedGamepad._isConnected = false;
  56178. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  56179. break;
  56180. }
  56181. }
  56182. };
  56183. if (this._gamepadSupport) {
  56184. //first add already-connected gamepads
  56185. this._updateGamepadObjects();
  56186. if (this._babylonGamepads.length) {
  56187. this._startMonitoringGamepads();
  56188. }
  56189. // Checking if the gamepad connected event is supported (like in Firefox)
  56190. if (this._gamepadEventSupported) {
  56191. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  56192. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  56193. }
  56194. else {
  56195. this._startMonitoringGamepads();
  56196. }
  56197. }
  56198. }
  56199. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  56200. get: function () {
  56201. return this._babylonGamepads;
  56202. },
  56203. enumerable: true,
  56204. configurable: true
  56205. });
  56206. GamepadManager.prototype.getGamepadByType = function (type) {
  56207. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  56208. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  56209. var gamepad = _a[_i];
  56210. if (gamepad && gamepad.type === type) {
  56211. return gamepad;
  56212. }
  56213. }
  56214. return null;
  56215. };
  56216. GamepadManager.prototype.dispose = function () {
  56217. if (this._gamepadEventSupported) {
  56218. if (this._onGamepadConnectedEvent) {
  56219. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  56220. }
  56221. if (this._onGamepadDisconnectedEvent) {
  56222. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  56223. }
  56224. this._onGamepadConnectedEvent = null;
  56225. this._onGamepadDisconnectedEvent = null;
  56226. }
  56227. this._babylonGamepads.forEach(function (gamepad) {
  56228. gamepad.dispose();
  56229. });
  56230. this.onGamepadConnectedObservable.clear();
  56231. this.onGamepadDisconnectedObservable.clear();
  56232. this._oneGamepadConnected = false;
  56233. this._stopMonitoringGamepads();
  56234. this._babylonGamepads = [];
  56235. };
  56236. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  56237. if (!this._oneGamepadConnected) {
  56238. this._oneGamepadConnected = true;
  56239. }
  56240. var newGamepad;
  56241. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  56242. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  56243. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  56244. }
  56245. else if (gamepad.pose) {
  56246. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  56247. }
  56248. else {
  56249. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  56250. }
  56251. this._babylonGamepads[newGamepad.index] = newGamepad;
  56252. return newGamepad;
  56253. };
  56254. GamepadManager.prototype._startMonitoringGamepads = function () {
  56255. if (!this._isMonitoring) {
  56256. this._isMonitoring = true;
  56257. //back-comp
  56258. if (!this._scene) {
  56259. this._checkGamepadsStatus();
  56260. }
  56261. }
  56262. };
  56263. GamepadManager.prototype._stopMonitoringGamepads = function () {
  56264. this._isMonitoring = false;
  56265. };
  56266. GamepadManager.prototype._checkGamepadsStatus = function () {
  56267. var _this = this;
  56268. // Hack to be compatible Chrome
  56269. this._updateGamepadObjects();
  56270. for (var i in this._babylonGamepads) {
  56271. var gamepad = this._babylonGamepads[i];
  56272. if (!gamepad || !gamepad.isConnected) {
  56273. continue;
  56274. }
  56275. gamepad.update();
  56276. }
  56277. if (this._isMonitoring && !this._scene) {
  56278. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  56279. }
  56280. };
  56281. // This function is called only on Chrome, which does not properly support
  56282. // connection/disconnection events and forces you to recopy again the gamepad object
  56283. GamepadManager.prototype._updateGamepadObjects = function () {
  56284. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  56285. for (var i = 0; i < gamepads.length; i++) {
  56286. if (gamepads[i]) {
  56287. if (!this._babylonGamepads[gamepads[i].index]) {
  56288. var newGamepad = this._addNewGamepad(gamepads[i]);
  56289. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56290. }
  56291. else {
  56292. // Forced to copy again this object for Chrome for unknown reason
  56293. this._babylonGamepads[i].browserGamepad = gamepads[i];
  56294. if (!this._babylonGamepads[i].isConnected) {
  56295. this._babylonGamepads[i]._isConnected = true;
  56296. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  56297. }
  56298. }
  56299. }
  56300. }
  56301. };
  56302. return GamepadManager;
  56303. }());
  56304. BABYLON.GamepadManager = GamepadManager;
  56305. })(BABYLON || (BABYLON = {}));
  56306. //# sourceMappingURL=babylon.gamepadManager.js.map
  56307. var BABYLON;
  56308. (function (BABYLON) {
  56309. var StickValues = /** @class */ (function () {
  56310. function StickValues(x, y) {
  56311. this.x = x;
  56312. this.y = y;
  56313. }
  56314. return StickValues;
  56315. }());
  56316. BABYLON.StickValues = StickValues;
  56317. var Gamepad = /** @class */ (function () {
  56318. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  56319. if (leftStickX === void 0) { leftStickX = 0; }
  56320. if (leftStickY === void 0) { leftStickY = 1; }
  56321. if (rightStickX === void 0) { rightStickX = 2; }
  56322. if (rightStickY === void 0) { rightStickY = 3; }
  56323. this.id = id;
  56324. this.index = index;
  56325. this.browserGamepad = browserGamepad;
  56326. this._isConnected = true;
  56327. this._invertLeftStickY = false;
  56328. this.type = Gamepad.GAMEPAD;
  56329. this._leftStickAxisX = leftStickX;
  56330. this._leftStickAxisY = leftStickY;
  56331. this._rightStickAxisX = rightStickX;
  56332. this._rightStickAxisY = rightStickY;
  56333. if (this.browserGamepad.axes.length >= 2) {
  56334. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56335. }
  56336. if (this.browserGamepad.axes.length >= 4) {
  56337. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56338. }
  56339. }
  56340. Object.defineProperty(Gamepad.prototype, "isConnected", {
  56341. get: function () {
  56342. return this._isConnected;
  56343. },
  56344. enumerable: true,
  56345. configurable: true
  56346. });
  56347. Gamepad.prototype.onleftstickchanged = function (callback) {
  56348. this._onleftstickchanged = callback;
  56349. };
  56350. Gamepad.prototype.onrightstickchanged = function (callback) {
  56351. this._onrightstickchanged = callback;
  56352. };
  56353. Object.defineProperty(Gamepad.prototype, "leftStick", {
  56354. get: function () {
  56355. return this._leftStick;
  56356. },
  56357. set: function (newValues) {
  56358. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  56359. this._onleftstickchanged(newValues);
  56360. }
  56361. this._leftStick = newValues;
  56362. },
  56363. enumerable: true,
  56364. configurable: true
  56365. });
  56366. Object.defineProperty(Gamepad.prototype, "rightStick", {
  56367. get: function () {
  56368. return this._rightStick;
  56369. },
  56370. set: function (newValues) {
  56371. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  56372. this._onrightstickchanged(newValues);
  56373. }
  56374. this._rightStick = newValues;
  56375. },
  56376. enumerable: true,
  56377. configurable: true
  56378. });
  56379. Gamepad.prototype.update = function () {
  56380. if (this._leftStick) {
  56381. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  56382. if (this._invertLeftStickY) {
  56383. this.leftStick.y *= -1;
  56384. }
  56385. }
  56386. if (this._rightStick) {
  56387. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  56388. }
  56389. };
  56390. Gamepad.prototype.dispose = function () {
  56391. };
  56392. Gamepad.GAMEPAD = 0;
  56393. Gamepad.GENERIC = 1;
  56394. Gamepad.XBOX = 2;
  56395. Gamepad.POSE_ENABLED = 3;
  56396. return Gamepad;
  56397. }());
  56398. BABYLON.Gamepad = Gamepad;
  56399. var GenericPad = /** @class */ (function (_super) {
  56400. __extends(GenericPad, _super);
  56401. function GenericPad(id, index, browserGamepad) {
  56402. var _this = _super.call(this, id, index, browserGamepad) || this;
  56403. _this.onButtonDownObservable = new BABYLON.Observable();
  56404. _this.onButtonUpObservable = new BABYLON.Observable();
  56405. _this.type = Gamepad.GENERIC;
  56406. _this._buttons = new Array(browserGamepad.buttons.length);
  56407. return _this;
  56408. }
  56409. GenericPad.prototype.onbuttondown = function (callback) {
  56410. this._onbuttondown = callback;
  56411. };
  56412. GenericPad.prototype.onbuttonup = function (callback) {
  56413. this._onbuttonup = callback;
  56414. };
  56415. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  56416. if (newValue !== currentValue) {
  56417. if (newValue === 1) {
  56418. if (this._onbuttondown) {
  56419. this._onbuttondown(buttonIndex);
  56420. }
  56421. this.onButtonDownObservable.notifyObservers(buttonIndex);
  56422. }
  56423. if (newValue === 0) {
  56424. if (this._onbuttonup) {
  56425. this._onbuttonup(buttonIndex);
  56426. }
  56427. this.onButtonUpObservable.notifyObservers(buttonIndex);
  56428. }
  56429. }
  56430. return newValue;
  56431. };
  56432. GenericPad.prototype.update = function () {
  56433. _super.prototype.update.call(this);
  56434. for (var index = 0; index < this._buttons.length; index++) {
  56435. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  56436. }
  56437. };
  56438. GenericPad.prototype.dispose = function () {
  56439. _super.prototype.dispose.call(this);
  56440. this.onButtonDownObservable.clear();
  56441. this.onButtonUpObservable.clear();
  56442. };
  56443. return GenericPad;
  56444. }(Gamepad));
  56445. BABYLON.GenericPad = GenericPad;
  56446. })(BABYLON || (BABYLON = {}));
  56447. //# sourceMappingURL=babylon.gamepad.js.map
  56448. var BABYLON;
  56449. (function (BABYLON) {
  56450. var Xbox360Button;
  56451. (function (Xbox360Button) {
  56452. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  56453. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  56454. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  56455. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  56456. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  56457. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  56458. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  56459. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  56460. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  56461. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  56462. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  56463. var Xbox360Dpad;
  56464. (function (Xbox360Dpad) {
  56465. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  56466. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  56467. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  56468. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  56469. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  56470. var Xbox360Pad = /** @class */ (function (_super) {
  56471. __extends(Xbox360Pad, _super);
  56472. function Xbox360Pad(id, index, gamepad, xboxOne) {
  56473. if (xboxOne === void 0) { xboxOne = false; }
  56474. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  56475. _this._leftTrigger = 0;
  56476. _this._rightTrigger = 0;
  56477. _this.onButtonDownObservable = new BABYLON.Observable();
  56478. _this.onButtonUpObservable = new BABYLON.Observable();
  56479. _this.onPadDownObservable = new BABYLON.Observable();
  56480. _this.onPadUpObservable = new BABYLON.Observable();
  56481. _this._buttonA = 0;
  56482. _this._buttonB = 0;
  56483. _this._buttonX = 0;
  56484. _this._buttonY = 0;
  56485. _this._buttonBack = 0;
  56486. _this._buttonStart = 0;
  56487. _this._buttonLB = 0;
  56488. _this._buttonRB = 0;
  56489. _this._buttonLeftStick = 0;
  56490. _this._buttonRightStick = 0;
  56491. _this._dPadUp = 0;
  56492. _this._dPadDown = 0;
  56493. _this._dPadLeft = 0;
  56494. _this._dPadRight = 0;
  56495. _this._isXboxOnePad = false;
  56496. _this.type = BABYLON.Gamepad.XBOX;
  56497. _this._isXboxOnePad = xboxOne;
  56498. return _this;
  56499. }
  56500. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  56501. this._onlefttriggerchanged = callback;
  56502. };
  56503. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  56504. this._onrighttriggerchanged = callback;
  56505. };
  56506. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  56507. get: function () {
  56508. return this._leftTrigger;
  56509. },
  56510. set: function (newValue) {
  56511. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  56512. this._onlefttriggerchanged(newValue);
  56513. }
  56514. this._leftTrigger = newValue;
  56515. },
  56516. enumerable: true,
  56517. configurable: true
  56518. });
  56519. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  56520. get: function () {
  56521. return this._rightTrigger;
  56522. },
  56523. set: function (newValue) {
  56524. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  56525. this._onrighttriggerchanged(newValue);
  56526. }
  56527. this._rightTrigger = newValue;
  56528. },
  56529. enumerable: true,
  56530. configurable: true
  56531. });
  56532. Xbox360Pad.prototype.onbuttondown = function (callback) {
  56533. this._onbuttondown = callback;
  56534. };
  56535. Xbox360Pad.prototype.onbuttonup = function (callback) {
  56536. this._onbuttonup = callback;
  56537. };
  56538. Xbox360Pad.prototype.ondpaddown = function (callback) {
  56539. this._ondpaddown = callback;
  56540. };
  56541. Xbox360Pad.prototype.ondpadup = function (callback) {
  56542. this._ondpadup = callback;
  56543. };
  56544. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  56545. if (newValue !== currentValue) {
  56546. if (newValue === 1) {
  56547. if (this._onbuttondown) {
  56548. this._onbuttondown(buttonType);
  56549. }
  56550. this.onButtonDownObservable.notifyObservers(buttonType);
  56551. }
  56552. if (newValue === 0) {
  56553. if (this._onbuttonup) {
  56554. this._onbuttonup(buttonType);
  56555. }
  56556. this.onButtonUpObservable.notifyObservers(buttonType);
  56557. }
  56558. }
  56559. return newValue;
  56560. };
  56561. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56562. if (newValue !== currentValue) {
  56563. if (newValue === 1) {
  56564. if (this._ondpaddown) {
  56565. this._ondpaddown(buttonType);
  56566. }
  56567. this.onPadDownObservable.notifyObservers(buttonType);
  56568. }
  56569. if (newValue === 0) {
  56570. if (this._ondpadup) {
  56571. this._ondpadup(buttonType);
  56572. }
  56573. this.onPadUpObservable.notifyObservers(buttonType);
  56574. }
  56575. }
  56576. return newValue;
  56577. };
  56578. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56579. get: function () {
  56580. return this._buttonA;
  56581. },
  56582. set: function (value) {
  56583. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56584. },
  56585. enumerable: true,
  56586. configurable: true
  56587. });
  56588. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56589. get: function () {
  56590. return this._buttonB;
  56591. },
  56592. set: function (value) {
  56593. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56594. },
  56595. enumerable: true,
  56596. configurable: true
  56597. });
  56598. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56599. get: function () {
  56600. return this._buttonX;
  56601. },
  56602. set: function (value) {
  56603. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56604. },
  56605. enumerable: true,
  56606. configurable: true
  56607. });
  56608. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56609. get: function () {
  56610. return this._buttonY;
  56611. },
  56612. set: function (value) {
  56613. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56614. },
  56615. enumerable: true,
  56616. configurable: true
  56617. });
  56618. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56619. get: function () {
  56620. return this._buttonStart;
  56621. },
  56622. set: function (value) {
  56623. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56624. },
  56625. enumerable: true,
  56626. configurable: true
  56627. });
  56628. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56629. get: function () {
  56630. return this._buttonBack;
  56631. },
  56632. set: function (value) {
  56633. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56634. },
  56635. enumerable: true,
  56636. configurable: true
  56637. });
  56638. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56639. get: function () {
  56640. return this._buttonLB;
  56641. },
  56642. set: function (value) {
  56643. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56644. },
  56645. enumerable: true,
  56646. configurable: true
  56647. });
  56648. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56649. get: function () {
  56650. return this._buttonRB;
  56651. },
  56652. set: function (value) {
  56653. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56654. },
  56655. enumerable: true,
  56656. configurable: true
  56657. });
  56658. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56659. get: function () {
  56660. return this._buttonLeftStick;
  56661. },
  56662. set: function (value) {
  56663. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56664. },
  56665. enumerable: true,
  56666. configurable: true
  56667. });
  56668. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56669. get: function () {
  56670. return this._buttonRightStick;
  56671. },
  56672. set: function (value) {
  56673. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56674. },
  56675. enumerable: true,
  56676. configurable: true
  56677. });
  56678. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56679. get: function () {
  56680. return this._dPadUp;
  56681. },
  56682. set: function (value) {
  56683. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56684. },
  56685. enumerable: true,
  56686. configurable: true
  56687. });
  56688. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56689. get: function () {
  56690. return this._dPadDown;
  56691. },
  56692. set: function (value) {
  56693. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56694. },
  56695. enumerable: true,
  56696. configurable: true
  56697. });
  56698. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56699. get: function () {
  56700. return this._dPadLeft;
  56701. },
  56702. set: function (value) {
  56703. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56704. },
  56705. enumerable: true,
  56706. configurable: true
  56707. });
  56708. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56709. get: function () {
  56710. return this._dPadRight;
  56711. },
  56712. set: function (value) {
  56713. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56714. },
  56715. enumerable: true,
  56716. configurable: true
  56717. });
  56718. Xbox360Pad.prototype.update = function () {
  56719. _super.prototype.update.call(this);
  56720. if (this._isXboxOnePad) {
  56721. this.buttonA = this.browserGamepad.buttons[0].value;
  56722. this.buttonB = this.browserGamepad.buttons[1].value;
  56723. this.buttonX = this.browserGamepad.buttons[2].value;
  56724. this.buttonY = this.browserGamepad.buttons[3].value;
  56725. this.buttonLB = this.browserGamepad.buttons[4].value;
  56726. this.buttonRB = this.browserGamepad.buttons[5].value;
  56727. this.leftTrigger = this.browserGamepad.axes[2];
  56728. this.rightTrigger = this.browserGamepad.axes[5];
  56729. this.buttonBack = this.browserGamepad.buttons[9].value;
  56730. this.buttonStart = this.browserGamepad.buttons[8].value;
  56731. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56732. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56733. this.dPadUp = this.browserGamepad.buttons[11].value;
  56734. this.dPadDown = this.browserGamepad.buttons[12].value;
  56735. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56736. this.dPadRight = this.browserGamepad.buttons[14].value;
  56737. }
  56738. else {
  56739. this.buttonA = this.browserGamepad.buttons[0].value;
  56740. this.buttonB = this.browserGamepad.buttons[1].value;
  56741. this.buttonX = this.browserGamepad.buttons[2].value;
  56742. this.buttonY = this.browserGamepad.buttons[3].value;
  56743. this.buttonLB = this.browserGamepad.buttons[4].value;
  56744. this.buttonRB = this.browserGamepad.buttons[5].value;
  56745. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56746. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56747. this.buttonBack = this.browserGamepad.buttons[8].value;
  56748. this.buttonStart = this.browserGamepad.buttons[9].value;
  56749. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56750. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56751. this.dPadUp = this.browserGamepad.buttons[12].value;
  56752. this.dPadDown = this.browserGamepad.buttons[13].value;
  56753. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56754. this.dPadRight = this.browserGamepad.buttons[15].value;
  56755. }
  56756. };
  56757. Xbox360Pad.prototype.dispose = function () {
  56758. _super.prototype.dispose.call(this);
  56759. this.onButtonDownObservable.clear();
  56760. this.onButtonUpObservable.clear();
  56761. this.onPadDownObservable.clear();
  56762. this.onPadUpObservable.clear();
  56763. };
  56764. return Xbox360Pad;
  56765. }(BABYLON.Gamepad));
  56766. BABYLON.Xbox360Pad = Xbox360Pad;
  56767. })(BABYLON || (BABYLON = {}));
  56768. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56769. var BABYLON;
  56770. (function (BABYLON) {
  56771. var PoseEnabledControllerType;
  56772. (function (PoseEnabledControllerType) {
  56773. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56774. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56775. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56776. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56777. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56778. var PoseEnabledControllerHelper = /** @class */ (function () {
  56779. function PoseEnabledControllerHelper() {
  56780. }
  56781. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56782. // Oculus Touch
  56783. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56784. return new BABYLON.OculusTouchController(vrGamepad);
  56785. }
  56786. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56787. return new BABYLON.WindowsMotionController(vrGamepad);
  56788. }
  56789. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56790. return new BABYLON.ViveController(vrGamepad);
  56791. }
  56792. else {
  56793. return new BABYLON.GenericController(vrGamepad);
  56794. }
  56795. };
  56796. return PoseEnabledControllerHelper;
  56797. }());
  56798. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56799. var PoseEnabledController = /** @class */ (function (_super) {
  56800. __extends(PoseEnabledController, _super);
  56801. function PoseEnabledController(browserGamepad) {
  56802. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56803. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  56804. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  56805. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  56806. // Represents device position and rotation in babylon space
  56807. _this.devicePosition = BABYLON.Vector3.Zero();
  56808. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56809. _this.deviceScaleFactor = 1;
  56810. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56811. _this._deviceToWorld = BABYLON.Matrix.Identity();
  56812. _this._workingMatrix = BABYLON.Matrix.Identity();
  56813. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56814. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56815. _this.position = BABYLON.Vector3.Zero();
  56816. _this.rotationQuaternion = new BABYLON.Quaternion();
  56817. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56818. _this._calculatedRotation = new BABYLON.Quaternion();
  56819. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56820. return _this;
  56821. }
  56822. PoseEnabledController.prototype.update = function () {
  56823. _super.prototype.update.call(this);
  56824. var pose = this.browserGamepad.pose;
  56825. this.updateFromDevice(pose);
  56826. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  56827. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  56828. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  56829. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  56830. if (this._mesh) {
  56831. this._mesh.position.copyFrom(this.devicePosition);
  56832. if (this._mesh.rotationQuaternion) {
  56833. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  56834. }
  56835. }
  56836. };
  56837. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56838. if (poseData) {
  56839. this.rawPose = poseData;
  56840. if (poseData.position) {
  56841. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56842. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56843. this._deviceRoomPosition.z *= -1;
  56844. }
  56845. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56846. this._calculatedPosition.addInPlace(this.position);
  56847. }
  56848. var pose = this.rawPose;
  56849. if (poseData.orientation && pose.orientation) {
  56850. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56851. if (this._mesh) {
  56852. if (this._mesh.getScene().useRightHandedSystem) {
  56853. this._deviceRoomRotationQuaternion.z *= -1;
  56854. this._deviceRoomRotationQuaternion.w *= -1;
  56855. }
  56856. else {
  56857. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  56858. }
  56859. }
  56860. // if the camera is set, rotate to the camera's rotation
  56861. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56862. }
  56863. }
  56864. };
  56865. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56866. if (this._mesh) {
  56867. this._mesh.parent = null;
  56868. }
  56869. this._mesh = mesh;
  56870. if (this._poseControlledCamera) {
  56871. this._mesh.parent = this._poseControlledCamera;
  56872. }
  56873. if (!this._mesh.rotationQuaternion) {
  56874. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56875. }
  56876. };
  56877. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56878. this._poseControlledCamera = camera;
  56879. if (this._mesh) {
  56880. this._mesh.parent = this._poseControlledCamera;
  56881. }
  56882. };
  56883. PoseEnabledController.prototype.dispose = function () {
  56884. if (this._mesh) {
  56885. this._mesh.dispose();
  56886. }
  56887. this._mesh = null;
  56888. _super.prototype.dispose.call(this);
  56889. };
  56890. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56891. get: function () {
  56892. return this._mesh;
  56893. },
  56894. enumerable: true,
  56895. configurable: true
  56896. });
  56897. PoseEnabledController.prototype.getForwardRay = function (length) {
  56898. if (length === void 0) { length = 100; }
  56899. if (!this.mesh) {
  56900. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56901. }
  56902. var m = this.mesh.getWorldMatrix();
  56903. var origin = m.getTranslation();
  56904. var forward = new BABYLON.Vector3(0, 0, -1);
  56905. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56906. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56907. return new BABYLON.Ray(origin, direction, length);
  56908. };
  56909. return PoseEnabledController;
  56910. }(BABYLON.Gamepad));
  56911. BABYLON.PoseEnabledController = PoseEnabledController;
  56912. })(BABYLON || (BABYLON = {}));
  56913. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56914. var BABYLON;
  56915. (function (BABYLON) {
  56916. var WebVRController = /** @class */ (function (_super) {
  56917. __extends(WebVRController, _super);
  56918. function WebVRController(vrGamepad) {
  56919. var _this = _super.call(this, vrGamepad) || this;
  56920. // Observables
  56921. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56922. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56923. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56924. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56925. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56926. _this.pad = { x: 0, y: 0 };
  56927. // avoid GC, store state in a tmp object
  56928. _this._changes = {
  56929. pressChanged: false,
  56930. touchChanged: false,
  56931. valueChanged: false,
  56932. changed: false
  56933. };
  56934. _this._buttons = new Array(vrGamepad.buttons.length);
  56935. _this.hand = vrGamepad.hand;
  56936. return _this;
  56937. }
  56938. WebVRController.prototype.onButtonStateChange = function (callback) {
  56939. this._onButtonStateChange = callback;
  56940. };
  56941. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56942. get: function () {
  56943. return this._defaultModel;
  56944. },
  56945. enumerable: true,
  56946. configurable: true
  56947. });
  56948. WebVRController.prototype.update = function () {
  56949. _super.prototype.update.call(this);
  56950. for (var index = 0; index < this._buttons.length; index++) {
  56951. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56952. }
  56953. ;
  56954. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56955. this.pad.x = this.leftStick.x;
  56956. this.pad.y = this.leftStick.y;
  56957. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56958. }
  56959. };
  56960. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56961. if (!newState) {
  56962. newState = {
  56963. pressed: false,
  56964. touched: false,
  56965. value: 0
  56966. };
  56967. }
  56968. if (!currentState) {
  56969. this._buttons[buttonIndex] = {
  56970. pressed: newState.pressed,
  56971. touched: newState.touched,
  56972. value: newState.value
  56973. };
  56974. return;
  56975. }
  56976. this._checkChanges(newState, currentState);
  56977. if (this._changes.changed) {
  56978. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56979. this.handleButtonChange(buttonIndex, newState, this._changes);
  56980. }
  56981. this._buttons[buttonIndex].pressed = newState.pressed;
  56982. this._buttons[buttonIndex].touched = newState.touched;
  56983. // oculus triggers are never 0, thou not touched.
  56984. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56985. };
  56986. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56987. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56988. this._changes.touchChanged = newState.touched !== currentState.touched;
  56989. this._changes.valueChanged = newState.value !== currentState.value;
  56990. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56991. return this._changes;
  56992. };
  56993. WebVRController.prototype.dispose = function () {
  56994. _super.prototype.dispose.call(this);
  56995. this.onTriggerStateChangedObservable.clear();
  56996. this.onMainButtonStateChangedObservable.clear();
  56997. this.onSecondaryButtonStateChangedObservable.clear();
  56998. this.onPadStateChangedObservable.clear();
  56999. this.onPadValuesChangedObservable.clear();
  57000. };
  57001. return WebVRController;
  57002. }(BABYLON.PoseEnabledController));
  57003. BABYLON.WebVRController = WebVRController;
  57004. })(BABYLON || (BABYLON = {}));
  57005. //# sourceMappingURL=babylon.webVRController.js.map
  57006. var BABYLON;
  57007. (function (BABYLON) {
  57008. var OculusTouchController = /** @class */ (function (_super) {
  57009. __extends(OculusTouchController, _super);
  57010. function OculusTouchController(vrGamepad) {
  57011. var _this = _super.call(this, vrGamepad) || this;
  57012. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  57013. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  57014. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  57015. return _this;
  57016. }
  57017. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57018. var _this = this;
  57019. var meshName;
  57020. // Hand
  57021. if (this.hand === 'left') {
  57022. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  57023. }
  57024. else {
  57025. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  57026. }
  57027. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  57028. /*
  57029. Parent Mesh name: oculus_touch_left
  57030. - body
  57031. - trigger
  57032. - thumbstick
  57033. - grip
  57034. - button_y
  57035. - button_x
  57036. - button_enter
  57037. */
  57038. _this._defaultModel = newMeshes[1];
  57039. _this.attachToMesh(_this._defaultModel);
  57040. if (meshLoaded) {
  57041. meshLoaded(_this._defaultModel);
  57042. }
  57043. });
  57044. };
  57045. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  57046. // helper getters for left and right hand.
  57047. get: function () {
  57048. if (this.hand === 'right') {
  57049. return this.onMainButtonStateChangedObservable;
  57050. }
  57051. else {
  57052. throw new Error('No A button on left hand');
  57053. }
  57054. },
  57055. enumerable: true,
  57056. configurable: true
  57057. });
  57058. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  57059. get: function () {
  57060. if (this.hand === 'right') {
  57061. return this.onSecondaryButtonStateChangedObservable;
  57062. }
  57063. else {
  57064. throw new Error('No B button on left hand');
  57065. }
  57066. },
  57067. enumerable: true,
  57068. configurable: true
  57069. });
  57070. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  57071. get: function () {
  57072. if (this.hand === 'left') {
  57073. return this.onMainButtonStateChangedObservable;
  57074. }
  57075. else {
  57076. throw new Error('No X button on right hand');
  57077. }
  57078. },
  57079. enumerable: true,
  57080. configurable: true
  57081. });
  57082. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  57083. get: function () {
  57084. if (this.hand === 'left') {
  57085. return this.onSecondaryButtonStateChangedObservable;
  57086. }
  57087. else {
  57088. throw new Error('No Y button on right hand');
  57089. }
  57090. },
  57091. enumerable: true,
  57092. configurable: true
  57093. });
  57094. /*
  57095. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  57096. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  57097. 2) secondary trigger (same)
  57098. 3) A (right) X (left), touch, pressed = value
  57099. 4) B / Y
  57100. 5) thumb rest
  57101. */
  57102. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57103. var notifyObject = state; //{ state: state, changes: changes };
  57104. var triggerDirection = this.hand === 'right' ? -1 : 1;
  57105. switch (buttonIdx) {
  57106. case 0:
  57107. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57108. return;
  57109. case 1:// index trigger
  57110. if (this._defaultModel) {
  57111. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  57112. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  57113. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  57114. }
  57115. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57116. return;
  57117. case 2:// secondary trigger
  57118. if (this._defaultModel) {
  57119. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  57120. }
  57121. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  57122. return;
  57123. case 3:
  57124. if (this._defaultModel) {
  57125. if (notifyObject.pressed) {
  57126. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  57127. }
  57128. else {
  57129. (this._defaultModel.getChildren()[1]).position.y = 0;
  57130. }
  57131. }
  57132. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57133. return;
  57134. case 4:
  57135. if (this._defaultModel) {
  57136. if (notifyObject.pressed) {
  57137. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57138. }
  57139. else {
  57140. (this._defaultModel.getChildren()[2]).position.y = 0;
  57141. }
  57142. }
  57143. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57144. return;
  57145. case 5:
  57146. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  57147. return;
  57148. }
  57149. };
  57150. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  57151. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  57152. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  57153. return OculusTouchController;
  57154. }(BABYLON.WebVRController));
  57155. BABYLON.OculusTouchController = OculusTouchController;
  57156. })(BABYLON || (BABYLON = {}));
  57157. //# sourceMappingURL=babylon.oculusTouchController.js.map
  57158. var BABYLON;
  57159. (function (BABYLON) {
  57160. var ViveController = /** @class */ (function (_super) {
  57161. __extends(ViveController, _super);
  57162. function ViveController(vrGamepad) {
  57163. var _this = _super.call(this, vrGamepad) || this;
  57164. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  57165. _this._invertLeftStickY = true;
  57166. return _this;
  57167. }
  57168. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57169. var _this = this;
  57170. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  57171. /*
  57172. Parent Mesh name: ViveWand
  57173. - body
  57174. - r_gripper
  57175. - l_gripper
  57176. - menu_button
  57177. - system_button
  57178. - trackpad
  57179. - trigger
  57180. - LED
  57181. */
  57182. _this._defaultModel = newMeshes[1];
  57183. _this.attachToMesh(_this._defaultModel);
  57184. if (meshLoaded) {
  57185. meshLoaded(_this._defaultModel);
  57186. }
  57187. });
  57188. };
  57189. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  57190. get: function () {
  57191. return this.onMainButtonStateChangedObservable;
  57192. },
  57193. enumerable: true,
  57194. configurable: true
  57195. });
  57196. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  57197. get: function () {
  57198. return this.onMainButtonStateChangedObservable;
  57199. },
  57200. enumerable: true,
  57201. configurable: true
  57202. });
  57203. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  57204. get: function () {
  57205. return this.onSecondaryButtonStateChangedObservable;
  57206. },
  57207. enumerable: true,
  57208. configurable: true
  57209. });
  57210. /**
  57211. * Vive mapping:
  57212. * 0: touchpad
  57213. * 1: trigger
  57214. * 2: left AND right buttons
  57215. * 3: menu button
  57216. */
  57217. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57218. var notifyObject = state; //{ state: state, changes: changes };
  57219. switch (buttonIdx) {
  57220. case 0:
  57221. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57222. return;
  57223. case 1:// index trigger
  57224. if (this._defaultModel) {
  57225. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  57226. }
  57227. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57228. return;
  57229. case 2:// left AND right button
  57230. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57231. return;
  57232. case 3:
  57233. if (this._defaultModel) {
  57234. if (notifyObject.pressed) {
  57235. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57236. }
  57237. else {
  57238. (this._defaultModel.getChildren()[2]).position.y = 0;
  57239. }
  57240. }
  57241. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57242. return;
  57243. }
  57244. };
  57245. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  57246. ViveController.MODEL_FILENAME = 'wand.babylon';
  57247. return ViveController;
  57248. }(BABYLON.WebVRController));
  57249. BABYLON.ViveController = ViveController;
  57250. })(BABYLON || (BABYLON = {}));
  57251. //# sourceMappingURL=babylon.viveController.js.map
  57252. var BABYLON;
  57253. (function (BABYLON) {
  57254. var GenericController = /** @class */ (function (_super) {
  57255. __extends(GenericController, _super);
  57256. function GenericController(vrGamepad) {
  57257. return _super.call(this, vrGamepad) || this;
  57258. }
  57259. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57260. var _this = this;
  57261. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  57262. _this._defaultModel = newMeshes[1];
  57263. _this.attachToMesh(_this._defaultModel);
  57264. if (meshLoaded) {
  57265. meshLoaded(_this._defaultModel);
  57266. }
  57267. });
  57268. };
  57269. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57270. console.log("Button id: " + buttonIdx + "state: ");
  57271. console.dir(state);
  57272. };
  57273. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  57274. GenericController.MODEL_FILENAME = 'generic.babylon';
  57275. return GenericController;
  57276. }(BABYLON.WebVRController));
  57277. BABYLON.GenericController = GenericController;
  57278. })(BABYLON || (BABYLON = {}));
  57279. //# sourceMappingURL=babylon.genericController.js.map
  57280. var BABYLON;
  57281. (function (BABYLON) {
  57282. var LoadedMeshInfo = /** @class */ (function () {
  57283. function LoadedMeshInfo() {
  57284. this.buttonMeshes = {};
  57285. this.axisMeshes = {};
  57286. }
  57287. return LoadedMeshInfo;
  57288. }());
  57289. var WindowsMotionController = /** @class */ (function (_super) {
  57290. __extends(WindowsMotionController, _super);
  57291. function WindowsMotionController(vrGamepad) {
  57292. var _this = _super.call(this, vrGamepad) || this;
  57293. _this._mapping = {
  57294. // Semantic button names
  57295. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  57296. // A mapping of the button name to glTF model node name
  57297. // that should be transformed by button value.
  57298. buttonMeshNames: {
  57299. 'trigger': 'SELECT',
  57300. 'menu': 'MENU',
  57301. 'grip': 'GRASP',
  57302. 'thumbstick': 'THUMBSTICK_PRESS',
  57303. 'trackpad': 'TOUCHPAD_PRESS'
  57304. },
  57305. // This mapping is used to translate from the Motion Controller to Babylon semantics
  57306. buttonObservableNames: {
  57307. 'trigger': 'onTriggerStateChangedObservable',
  57308. 'menu': 'onSecondaryButtonStateChangedObservable',
  57309. 'grip': 'onMainButtonStateChangedObservable',
  57310. 'thumbstick': 'onPadStateChangedObservable',
  57311. 'trackpad': 'onTrackpadChangedObservable'
  57312. },
  57313. // A mapping of the axis name to glTF model node name
  57314. // that should be transformed by axis value.
  57315. // This array mirrors the browserGamepad.axes array, such that
  57316. // the mesh corresponding to axis 0 is in this array index 0.
  57317. axisMeshNames: [
  57318. 'THUMBSTICK_X',
  57319. 'THUMBSTICK_Y',
  57320. 'TOUCHPAD_TOUCH_X',
  57321. 'TOUCHPAD_TOUCH_Y'
  57322. ],
  57323. pointingPoseMeshName: 'POINTING_POSE'
  57324. };
  57325. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  57326. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  57327. _this.trackpad = { x: 0, y: 0 };
  57328. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  57329. _this._loadedMeshInfo = null;
  57330. return _this;
  57331. }
  57332. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  57333. get: function () {
  57334. return this.onTriggerStateChangedObservable;
  57335. },
  57336. enumerable: true,
  57337. configurable: true
  57338. });
  57339. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  57340. get: function () {
  57341. return this.onSecondaryButtonStateChangedObservable;
  57342. },
  57343. enumerable: true,
  57344. configurable: true
  57345. });
  57346. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  57347. get: function () {
  57348. return this.onMainButtonStateChangedObservable;
  57349. },
  57350. enumerable: true,
  57351. configurable: true
  57352. });
  57353. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  57354. get: function () {
  57355. return this.onPadStateChangedObservable;
  57356. },
  57357. enumerable: true,
  57358. configurable: true
  57359. });
  57360. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  57361. get: function () {
  57362. return this.onTrackpadChangedObservable;
  57363. },
  57364. enumerable: true,
  57365. configurable: true
  57366. });
  57367. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  57368. get: function () {
  57369. return this.onTrackpadValuesChangedObservable;
  57370. },
  57371. enumerable: true,
  57372. configurable: true
  57373. });
  57374. /**
  57375. * Called once per frame by the engine.
  57376. */
  57377. WindowsMotionController.prototype.update = function () {
  57378. _super.prototype.update.call(this);
  57379. // Only need to animate axes if there is a loaded mesh
  57380. if (this._loadedMeshInfo) {
  57381. if (this.browserGamepad.axes) {
  57382. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  57383. this.trackpad.x = this.browserGamepad["axes"][2];
  57384. this.trackpad.y = this.browserGamepad["axes"][3];
  57385. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  57386. }
  57387. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  57388. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  57389. }
  57390. }
  57391. }
  57392. };
  57393. /**
  57394. * Called once for each button that changed state since the last frame
  57395. * @param buttonIdx Which button index changed
  57396. * @param state New state of the button
  57397. * @param changes Which properties on the state changed since last frame
  57398. */
  57399. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57400. var buttonName = this._mapping.buttons[buttonIdx];
  57401. if (!buttonName) {
  57402. return;
  57403. }
  57404. // Only emit events for buttons that we know how to map from index to name
  57405. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  57406. if (observable) {
  57407. observable.notifyObservers(state);
  57408. }
  57409. this.lerpButtonTransform(buttonName, state.value);
  57410. };
  57411. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  57412. // If there is no loaded mesh, there is nothing to transform.
  57413. if (!this._loadedMeshInfo) {
  57414. return;
  57415. }
  57416. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  57417. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57418. return;
  57419. }
  57420. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  57421. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  57422. };
  57423. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  57424. if (!this._loadedMeshInfo) {
  57425. return;
  57426. }
  57427. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  57428. if (!meshInfo) {
  57429. return;
  57430. }
  57431. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  57432. return;
  57433. }
  57434. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  57435. var lerpValue = axisValue * 0.5 + 0.5;
  57436. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  57437. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  57438. };
  57439. /**
  57440. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  57441. * @param scene scene in which to add meshes
  57442. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  57443. */
  57444. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  57445. var _this = this;
  57446. if (forceDefault === void 0) { forceDefault = false; }
  57447. var path;
  57448. var filename;
  57449. // Checking if GLB loader is present
  57450. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable("glb")) {
  57451. // Determine the device specific folder based on the ID suffix
  57452. var device = 'default';
  57453. if (this.id && !forceDefault) {
  57454. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  57455. device = ((match && match[0]) || device);
  57456. }
  57457. // Hand
  57458. if (this.hand === 'left') {
  57459. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  57460. }
  57461. else {
  57462. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  57463. }
  57464. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  57465. }
  57466. else {
  57467. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  57468. path = BABYLON.GenericController.MODEL_BASE_URL;
  57469. filename = BABYLON.GenericController.MODEL_FILENAME;
  57470. }
  57471. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  57472. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  57473. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  57474. if (!_this._loadedMeshInfo) {
  57475. return;
  57476. }
  57477. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  57478. _this.attachToMesh(_this._defaultModel);
  57479. if (meshLoaded) {
  57480. meshLoaded(_this._defaultModel);
  57481. }
  57482. }, null, function (scene, message) {
  57483. BABYLON.Tools.Log(message);
  57484. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  57485. if (!forceDefault) {
  57486. _this.initControllerMesh(scene, meshLoaded, true);
  57487. }
  57488. });
  57489. };
  57490. /**
  57491. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  57492. * can be transformed by button presses and axes values, based on this._mapping.
  57493. *
  57494. * @param scene scene in which the meshes exist
  57495. * @param meshes list of meshes that make up the controller model to process
  57496. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  57497. */
  57498. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  57499. var loadedMeshInfo = null;
  57500. // Create a new mesh to contain the glTF hierarchy
  57501. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  57502. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  57503. var childMesh = null;
  57504. for (var i = 0; i < meshes.length; i++) {
  57505. var mesh = meshes[i];
  57506. if (!mesh.parent) {
  57507. // Exclude controller meshes from picking results
  57508. mesh.isPickable = false;
  57509. // Handle root node, attach to the new parentMesh
  57510. childMesh = mesh;
  57511. break;
  57512. }
  57513. }
  57514. if (childMesh) {
  57515. childMesh.setParent(parentMesh);
  57516. // Create our mesh info. Note that this method will always return non-null.
  57517. loadedMeshInfo = this.createMeshInfo(parentMesh);
  57518. }
  57519. else {
  57520. BABYLON.Tools.Warn('Could not find root node in model file.');
  57521. }
  57522. return loadedMeshInfo;
  57523. };
  57524. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  57525. var loadedMeshInfo = new LoadedMeshInfo();
  57526. var i;
  57527. loadedMeshInfo.rootNode = rootNode;
  57528. // Reset the caches
  57529. loadedMeshInfo.buttonMeshes = {};
  57530. loadedMeshInfo.axisMeshes = {};
  57531. // Button Meshes
  57532. for (i = 0; i < this._mapping.buttons.length; i++) {
  57533. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  57534. if (!buttonMeshName) {
  57535. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  57536. continue;
  57537. }
  57538. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  57539. if (!buttonMesh) {
  57540. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  57541. continue;
  57542. }
  57543. var buttonMeshInfo = {
  57544. index: i,
  57545. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  57546. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  57547. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  57548. };
  57549. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  57550. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  57551. }
  57552. else {
  57553. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  57554. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  57555. '(VALUE: ' + !!buttonMeshInfo.value +
  57556. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  57557. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  57558. ')');
  57559. }
  57560. }
  57561. // Axis Meshes
  57562. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  57563. var axisMeshName = this._mapping.axisMeshNames[i];
  57564. if (!axisMeshName) {
  57565. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  57566. continue;
  57567. }
  57568. var axisMesh = getChildByName(rootNode, axisMeshName);
  57569. if (!axisMesh) {
  57570. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  57571. continue;
  57572. }
  57573. var axisMeshInfo = {
  57574. index: i,
  57575. value: getImmediateChildByName(axisMesh, 'VALUE'),
  57576. min: getImmediateChildByName(axisMesh, 'MIN'),
  57577. max: getImmediateChildByName(axisMesh, 'MAX')
  57578. };
  57579. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57580. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57581. }
  57582. else {
  57583. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57584. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57585. '(VALUE: ' + !!axisMeshInfo.value +
  57586. ', MIN: ' + !!axisMeshInfo.min +
  57587. ', MAX:' + !!axisMeshInfo.max +
  57588. ')');
  57589. }
  57590. }
  57591. // Pointing Ray
  57592. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57593. if (!loadedMeshInfo.pointingPoseNode) {
  57594. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57595. }
  57596. return loadedMeshInfo;
  57597. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57598. function getChildByName(node, name) {
  57599. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57600. }
  57601. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57602. function getImmediateChildByName(node, name) {
  57603. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57604. }
  57605. };
  57606. WindowsMotionController.prototype.getForwardRay = function (length) {
  57607. if (length === void 0) { length = 100; }
  57608. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57609. return _super.prototype.getForwardRay.call(this, length);
  57610. }
  57611. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57612. var origin = m.getTranslation();
  57613. var forward = new BABYLON.Vector3(0, 0, -1);
  57614. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57615. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57616. return new BABYLON.Ray(origin, direction, length);
  57617. };
  57618. WindowsMotionController.prototype.dispose = function () {
  57619. _super.prototype.dispose.call(this);
  57620. this.onTrackpadChangedObservable.clear();
  57621. };
  57622. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57623. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57624. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57625. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57626. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57627. return WindowsMotionController;
  57628. }(BABYLON.WebVRController));
  57629. BABYLON.WindowsMotionController = WindowsMotionController;
  57630. })(BABYLON || (BABYLON = {}));
  57631. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57632. var BABYLON;
  57633. (function (BABYLON) {
  57634. var FollowCamera = /** @class */ (function (_super) {
  57635. __extends(FollowCamera, _super);
  57636. function FollowCamera(name, position, scene, lockedTarget) {
  57637. if (lockedTarget === void 0) { lockedTarget = null; }
  57638. var _this = _super.call(this, name, position, scene) || this;
  57639. _this.radius = 12;
  57640. _this.rotationOffset = 0;
  57641. _this.heightOffset = 4;
  57642. _this.cameraAcceleration = 0.05;
  57643. _this.maxCameraSpeed = 20;
  57644. _this.lockedTarget = lockedTarget;
  57645. return _this;
  57646. }
  57647. FollowCamera.prototype.getRadians = function (degrees) {
  57648. return degrees * Math.PI / 180;
  57649. };
  57650. FollowCamera.prototype.follow = function (cameraTarget) {
  57651. if (!cameraTarget)
  57652. return;
  57653. var yRotation;
  57654. if (cameraTarget.rotationQuaternion) {
  57655. var rotMatrix = new BABYLON.Matrix();
  57656. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57657. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57658. }
  57659. else {
  57660. yRotation = cameraTarget.rotation.y;
  57661. }
  57662. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57663. var targetPosition = cameraTarget.getAbsolutePosition();
  57664. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57665. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57666. var dx = targetX - this.position.x;
  57667. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57668. var dz = (targetZ) - this.position.z;
  57669. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57670. var vy = dy * this.cameraAcceleration;
  57671. var vz = dz * this.cameraAcceleration * 2;
  57672. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57673. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57674. }
  57675. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57676. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57677. }
  57678. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57679. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57680. }
  57681. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57682. this.setTarget(targetPosition);
  57683. };
  57684. FollowCamera.prototype._checkInputs = function () {
  57685. _super.prototype._checkInputs.call(this);
  57686. if (this.lockedTarget) {
  57687. this.follow(this.lockedTarget);
  57688. }
  57689. };
  57690. FollowCamera.prototype.getClassName = function () {
  57691. return "FollowCamera";
  57692. };
  57693. __decorate([
  57694. BABYLON.serialize()
  57695. ], FollowCamera.prototype, "radius", void 0);
  57696. __decorate([
  57697. BABYLON.serialize()
  57698. ], FollowCamera.prototype, "rotationOffset", void 0);
  57699. __decorate([
  57700. BABYLON.serialize()
  57701. ], FollowCamera.prototype, "heightOffset", void 0);
  57702. __decorate([
  57703. BABYLON.serialize()
  57704. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57705. __decorate([
  57706. BABYLON.serialize()
  57707. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57708. __decorate([
  57709. BABYLON.serializeAsMeshReference("lockedTargetId")
  57710. ], FollowCamera.prototype, "lockedTarget", void 0);
  57711. return FollowCamera;
  57712. }(BABYLON.TargetCamera));
  57713. BABYLON.FollowCamera = FollowCamera;
  57714. var ArcFollowCamera = /** @class */ (function (_super) {
  57715. __extends(ArcFollowCamera, _super);
  57716. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57717. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57718. _this.alpha = alpha;
  57719. _this.beta = beta;
  57720. _this.radius = radius;
  57721. _this.target = target;
  57722. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57723. _this.follow();
  57724. return _this;
  57725. }
  57726. ArcFollowCamera.prototype.follow = function () {
  57727. if (!this.target) {
  57728. return;
  57729. }
  57730. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57731. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57732. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57733. var targetPosition = this.target.getAbsolutePosition();
  57734. this.position = targetPosition.add(this._cartesianCoordinates);
  57735. this.setTarget(targetPosition);
  57736. };
  57737. ArcFollowCamera.prototype._checkInputs = function () {
  57738. _super.prototype._checkInputs.call(this);
  57739. this.follow();
  57740. };
  57741. ArcFollowCamera.prototype.getClassName = function () {
  57742. return "ArcFollowCamera";
  57743. };
  57744. return ArcFollowCamera;
  57745. }(BABYLON.TargetCamera));
  57746. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57747. })(BABYLON || (BABYLON = {}));
  57748. //# sourceMappingURL=babylon.followCamera.js.map
  57749. var BABYLON;
  57750. (function (BABYLON) {
  57751. // We're mainly based on the logic defined into the FreeCamera code
  57752. var UniversalCamera = /** @class */ (function (_super) {
  57753. __extends(UniversalCamera, _super);
  57754. //-- end properties for backward compatibility for inputs
  57755. function UniversalCamera(name, position, scene) {
  57756. var _this = _super.call(this, name, position, scene) || this;
  57757. _this.inputs.addGamepad();
  57758. return _this;
  57759. }
  57760. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57761. //-- Begin properties for backward compatibility for inputs
  57762. get: function () {
  57763. var gamepad = this.inputs.attached["gamepad"];
  57764. if (gamepad)
  57765. return gamepad.gamepadAngularSensibility;
  57766. return 0;
  57767. },
  57768. set: function (value) {
  57769. var gamepad = this.inputs.attached["gamepad"];
  57770. if (gamepad)
  57771. gamepad.gamepadAngularSensibility = value;
  57772. },
  57773. enumerable: true,
  57774. configurable: true
  57775. });
  57776. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57777. get: function () {
  57778. var gamepad = this.inputs.attached["gamepad"];
  57779. if (gamepad)
  57780. return gamepad.gamepadMoveSensibility;
  57781. return 0;
  57782. },
  57783. set: function (value) {
  57784. var gamepad = this.inputs.attached["gamepad"];
  57785. if (gamepad)
  57786. gamepad.gamepadMoveSensibility = value;
  57787. },
  57788. enumerable: true,
  57789. configurable: true
  57790. });
  57791. UniversalCamera.prototype.getClassName = function () {
  57792. return "UniversalCamera";
  57793. };
  57794. return UniversalCamera;
  57795. }(BABYLON.TouchCamera));
  57796. BABYLON.UniversalCamera = UniversalCamera;
  57797. })(BABYLON || (BABYLON = {}));
  57798. //# sourceMappingURL=babylon.universalCamera.js.map
  57799. var BABYLON;
  57800. (function (BABYLON) {
  57801. // We're mainly based on the logic defined into the FreeCamera code
  57802. var GamepadCamera = /** @class */ (function (_super) {
  57803. __extends(GamepadCamera, _super);
  57804. //-- end properties for backward compatibility for inputs
  57805. function GamepadCamera(name, position, scene) {
  57806. return _super.call(this, name, position, scene) || this;
  57807. }
  57808. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57809. //-- Begin properties for backward compatibility for inputs
  57810. get: function () {
  57811. var gamepad = this.inputs.attached["gamepad"];
  57812. if (gamepad)
  57813. return gamepad.gamepadAngularSensibility;
  57814. return 0;
  57815. },
  57816. set: function (value) {
  57817. var gamepad = this.inputs.attached["gamepad"];
  57818. if (gamepad)
  57819. gamepad.gamepadAngularSensibility = value;
  57820. },
  57821. enumerable: true,
  57822. configurable: true
  57823. });
  57824. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57825. get: function () {
  57826. var gamepad = this.inputs.attached["gamepad"];
  57827. if (gamepad)
  57828. return gamepad.gamepadMoveSensibility;
  57829. return 0;
  57830. },
  57831. set: function (value) {
  57832. var gamepad = this.inputs.attached["gamepad"];
  57833. if (gamepad)
  57834. gamepad.gamepadMoveSensibility = value;
  57835. },
  57836. enumerable: true,
  57837. configurable: true
  57838. });
  57839. GamepadCamera.prototype.getClassName = function () {
  57840. return "GamepadCamera";
  57841. };
  57842. return GamepadCamera;
  57843. }(BABYLON.UniversalCamera));
  57844. BABYLON.GamepadCamera = GamepadCamera;
  57845. })(BABYLON || (BABYLON = {}));
  57846. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57847. var BABYLON;
  57848. (function (BABYLON) {
  57849. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57850. function PostProcessRenderPipelineManager() {
  57851. this._renderPipelines = {};
  57852. }
  57853. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57854. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57855. };
  57856. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57857. if (unique === void 0) { unique = false; }
  57858. var renderPipeline = this._renderPipelines[renderPipelineName];
  57859. if (!renderPipeline) {
  57860. return;
  57861. }
  57862. renderPipeline._attachCameras(cameras, unique);
  57863. };
  57864. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57865. var renderPipeline = this._renderPipelines[renderPipelineName];
  57866. if (!renderPipeline) {
  57867. return;
  57868. }
  57869. renderPipeline._detachCameras(cameras);
  57870. };
  57871. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57872. var renderPipeline = this._renderPipelines[renderPipelineName];
  57873. if (!renderPipeline) {
  57874. return;
  57875. }
  57876. renderPipeline._enableEffect(renderEffectName, cameras);
  57877. };
  57878. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57879. var renderPipeline = this._renderPipelines[renderPipelineName];
  57880. if (!renderPipeline) {
  57881. return;
  57882. }
  57883. renderPipeline._disableEffect(renderEffectName, cameras);
  57884. };
  57885. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57886. var renderPipeline = this._renderPipelines[renderPipelineName];
  57887. if (!renderPipeline) {
  57888. return;
  57889. }
  57890. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57891. };
  57892. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57893. var renderPipeline = this._renderPipelines[renderPipelineName];
  57894. if (!renderPipeline) {
  57895. return;
  57896. }
  57897. renderPipeline._disableDisplayOnlyPass(cameras);
  57898. };
  57899. PostProcessRenderPipelineManager.prototype.update = function () {
  57900. for (var renderPipelineName in this._renderPipelines) {
  57901. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57902. var pipeline = this._renderPipelines[renderPipelineName];
  57903. if (!pipeline.isSupported) {
  57904. pipeline.dispose();
  57905. delete this._renderPipelines[renderPipelineName];
  57906. }
  57907. else {
  57908. pipeline._update();
  57909. }
  57910. }
  57911. }
  57912. };
  57913. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57914. for (var renderPipelineName in this._renderPipelines) {
  57915. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57916. var pipeline = this._renderPipelines[renderPipelineName];
  57917. pipeline._rebuild();
  57918. }
  57919. }
  57920. };
  57921. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57922. for (var renderPipelineName in this._renderPipelines) {
  57923. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57924. var pipeline = this._renderPipelines[renderPipelineName];
  57925. pipeline.dispose();
  57926. }
  57927. }
  57928. };
  57929. return PostProcessRenderPipelineManager;
  57930. }());
  57931. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57932. })(BABYLON || (BABYLON = {}));
  57933. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57934. var BABYLON;
  57935. (function (BABYLON) {
  57936. var PostProcessRenderPass = /** @class */ (function () {
  57937. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57938. this._refCount = 0;
  57939. this._name = name;
  57940. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57941. this.setRenderList(renderList);
  57942. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57943. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57944. this._scene = scene;
  57945. this._renderList = renderList;
  57946. }
  57947. // private
  57948. PostProcessRenderPass.prototype._incRefCount = function () {
  57949. if (this._refCount === 0) {
  57950. this._scene.customRenderTargets.push(this._renderTexture);
  57951. }
  57952. return ++this._refCount;
  57953. };
  57954. PostProcessRenderPass.prototype._decRefCount = function () {
  57955. this._refCount--;
  57956. if (this._refCount <= 0) {
  57957. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57958. }
  57959. return this._refCount;
  57960. };
  57961. PostProcessRenderPass.prototype._update = function () {
  57962. this.setRenderList(this._renderList);
  57963. };
  57964. // public
  57965. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57966. this._renderTexture.renderList = renderList;
  57967. };
  57968. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57969. return this._renderTexture;
  57970. };
  57971. return PostProcessRenderPass;
  57972. }());
  57973. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57974. })(BABYLON || (BABYLON = {}));
  57975. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57976. var BABYLON;
  57977. (function (BABYLON) {
  57978. var PostProcessRenderEffect = /** @class */ (function () {
  57979. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57980. this._name = name;
  57981. this._singleInstance = singleInstance || true;
  57982. this._getPostProcess = getPostProcess;
  57983. this._cameras = {};
  57984. this._indicesForCamera = {};
  57985. this._postProcesses = {};
  57986. this._renderPasses = {};
  57987. this._renderEffectAsPasses = {};
  57988. }
  57989. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57990. get: function () {
  57991. for (var index in this._postProcesses) {
  57992. if (!this._postProcesses[index].isSupported) {
  57993. return false;
  57994. }
  57995. }
  57996. return true;
  57997. },
  57998. enumerable: true,
  57999. configurable: true
  58000. });
  58001. PostProcessRenderEffect.prototype._update = function () {
  58002. for (var renderPassName in this._renderPasses) {
  58003. this._renderPasses[renderPassName]._update();
  58004. }
  58005. };
  58006. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  58007. this._renderPasses[renderPass._name] = renderPass;
  58008. this._linkParameters();
  58009. };
  58010. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  58011. delete this._renderPasses[renderPass._name];
  58012. this._linkParameters();
  58013. };
  58014. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  58015. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  58016. this._linkParameters();
  58017. };
  58018. PostProcessRenderEffect.prototype.getPass = function (passName) {
  58019. for (var renderPassName in this._renderPasses) {
  58020. if (renderPassName === passName) {
  58021. return this._renderPasses[passName];
  58022. }
  58023. }
  58024. return null;
  58025. };
  58026. PostProcessRenderEffect.prototype.emptyPasses = function () {
  58027. this._renderPasses = {};
  58028. this._linkParameters();
  58029. };
  58030. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  58031. var cameraKey;
  58032. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58033. if (!cams) {
  58034. return;
  58035. }
  58036. for (var i = 0; i < cams.length; i++) {
  58037. var camera = cams[i];
  58038. var cameraName = camera.name;
  58039. if (this._singleInstance) {
  58040. cameraKey = 0;
  58041. }
  58042. else {
  58043. cameraKey = cameraName;
  58044. }
  58045. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  58046. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  58047. if (!this._indicesForCamera[cameraName]) {
  58048. this._indicesForCamera[cameraName] = [];
  58049. }
  58050. this._indicesForCamera[cameraName].push(index);
  58051. if (!this._cameras[cameraName]) {
  58052. this._cameras[cameraName] = camera;
  58053. }
  58054. for (var passName in this._renderPasses) {
  58055. this._renderPasses[passName]._incRefCount();
  58056. }
  58057. }
  58058. this._linkParameters();
  58059. };
  58060. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  58061. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58062. if (!cams) {
  58063. return;
  58064. }
  58065. for (var i = 0; i < cams.length; i++) {
  58066. var camera = cams[i];
  58067. var cameraName = camera.name;
  58068. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58069. if (this._cameras[cameraName]) {
  58070. //this._indicesForCamera.splice(index, 1);
  58071. this._cameras[cameraName] = null;
  58072. }
  58073. for (var passName in this._renderPasses) {
  58074. this._renderPasses[passName]._decRefCount();
  58075. }
  58076. }
  58077. };
  58078. PostProcessRenderEffect.prototype._enable = function (cameras) {
  58079. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58080. if (!cams) {
  58081. return;
  58082. }
  58083. for (var i = 0; i < cams.length; i++) {
  58084. var camera = cams[i];
  58085. var cameraName = camera.name;
  58086. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  58087. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  58088. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  58089. }
  58090. }
  58091. for (var passName in this._renderPasses) {
  58092. this._renderPasses[passName]._incRefCount();
  58093. }
  58094. }
  58095. };
  58096. PostProcessRenderEffect.prototype._disable = function (cameras) {
  58097. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58098. if (!cams) {
  58099. return;
  58100. }
  58101. for (var i = 0; i < cams.length; i++) {
  58102. var camera = cams[i];
  58103. var cameraName = camera.Name;
  58104. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58105. for (var passName in this._renderPasses) {
  58106. this._renderPasses[passName]._decRefCount();
  58107. }
  58108. }
  58109. };
  58110. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  58111. if (this._singleInstance) {
  58112. return this._postProcesses[0];
  58113. }
  58114. else {
  58115. if (!camera) {
  58116. return null;
  58117. }
  58118. return this._postProcesses[camera.name];
  58119. }
  58120. };
  58121. PostProcessRenderEffect.prototype._linkParameters = function () {
  58122. var _this = this;
  58123. for (var index in this._postProcesses) {
  58124. if (this.applyParameters) {
  58125. this.applyParameters(this._postProcesses[index]);
  58126. }
  58127. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  58128. _this._linkTextures(effect);
  58129. });
  58130. }
  58131. };
  58132. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  58133. for (var renderPassName in this._renderPasses) {
  58134. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  58135. }
  58136. for (var renderEffectName in this._renderEffectAsPasses) {
  58137. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  58138. }
  58139. };
  58140. return PostProcessRenderEffect;
  58141. }());
  58142. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  58143. })(BABYLON || (BABYLON = {}));
  58144. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  58145. var BABYLON;
  58146. (function (BABYLON) {
  58147. var PostProcessRenderPipeline = /** @class */ (function () {
  58148. function PostProcessRenderPipeline(engine, name) {
  58149. this._engine = engine;
  58150. this._name = name;
  58151. this._renderEffects = {};
  58152. this._renderEffectsForIsolatedPass = new Array();
  58153. this._cameras = [];
  58154. }
  58155. PostProcessRenderPipeline.prototype.getClassName = function () {
  58156. return "PostProcessRenderPipeline";
  58157. };
  58158. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  58159. get: function () {
  58160. for (var renderEffectName in this._renderEffects) {
  58161. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58162. if (!this._renderEffects[renderEffectName].isSupported) {
  58163. return false;
  58164. }
  58165. }
  58166. }
  58167. return true;
  58168. },
  58169. enumerable: true,
  58170. configurable: true
  58171. });
  58172. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  58173. this._renderEffects[renderEffect._name] = renderEffect;
  58174. };
  58175. // private
  58176. PostProcessRenderPipeline.prototype._rebuild = function () {
  58177. };
  58178. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  58179. var renderEffects = this._renderEffects[renderEffectName];
  58180. if (!renderEffects) {
  58181. return;
  58182. }
  58183. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58184. };
  58185. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  58186. var renderEffects = this._renderEffects[renderEffectName];
  58187. if (!renderEffects) {
  58188. return;
  58189. }
  58190. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58191. };
  58192. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  58193. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58194. if (!cams) {
  58195. return;
  58196. }
  58197. var indicesToDelete = [];
  58198. var i;
  58199. for (i = 0; i < cams.length; i++) {
  58200. var camera = cams[i];
  58201. var cameraName = camera.name;
  58202. if (this._cameras.indexOf(camera) === -1) {
  58203. this._cameras[cameraName] = camera;
  58204. }
  58205. else if (unique) {
  58206. indicesToDelete.push(i);
  58207. }
  58208. }
  58209. for (i = 0; i < indicesToDelete.length; i++) {
  58210. cameras.splice(indicesToDelete[i], 1);
  58211. }
  58212. for (var renderEffectName in this._renderEffects) {
  58213. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58214. this._renderEffects[renderEffectName]._attachCameras(cams);
  58215. }
  58216. }
  58217. };
  58218. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  58219. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58220. if (!cams) {
  58221. return;
  58222. }
  58223. for (var renderEffectName in this._renderEffects) {
  58224. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58225. this._renderEffects[renderEffectName]._detachCameras(cams);
  58226. }
  58227. }
  58228. for (var i = 0; i < cams.length; i++) {
  58229. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  58230. }
  58231. };
  58232. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  58233. var _this = this;
  58234. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58235. if (!cams) {
  58236. return;
  58237. }
  58238. var pass = null;
  58239. var renderEffectName;
  58240. for (renderEffectName in this._renderEffects) {
  58241. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58242. pass = this._renderEffects[renderEffectName].getPass(passName);
  58243. if (pass != null) {
  58244. break;
  58245. }
  58246. }
  58247. }
  58248. if (pass === null) {
  58249. return;
  58250. }
  58251. for (renderEffectName in this._renderEffects) {
  58252. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58253. this._renderEffects[renderEffectName]._disable(cams);
  58254. }
  58255. }
  58256. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  58257. for (var i = 0; i < cams.length; i++) {
  58258. var camera = cams[i];
  58259. var cameraName = camera.name;
  58260. 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); });
  58261. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  58262. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  58263. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  58264. }
  58265. };
  58266. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  58267. var _this = this;
  58268. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58269. if (!cams) {
  58270. return;
  58271. }
  58272. for (var i = 0; i < cams.length; i++) {
  58273. var camera = cams[i];
  58274. var cameraName = camera.name;
  58275. 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); });
  58276. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  58277. }
  58278. for (var renderEffectName in this._renderEffects) {
  58279. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58280. this._renderEffects[renderEffectName]._enable(cams);
  58281. }
  58282. }
  58283. };
  58284. PostProcessRenderPipeline.prototype._update = function () {
  58285. for (var renderEffectName in this._renderEffects) {
  58286. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58287. this._renderEffects[renderEffectName]._update();
  58288. }
  58289. }
  58290. for (var i = 0; i < this._cameras.length; i++) {
  58291. var cameraName = this._cameras[i].name;
  58292. if (this._renderEffectsForIsolatedPass[cameraName]) {
  58293. this._renderEffectsForIsolatedPass[cameraName]._update();
  58294. }
  58295. }
  58296. };
  58297. PostProcessRenderPipeline.prototype._reset = function () {
  58298. this._renderEffects = {};
  58299. this._renderEffectsForIsolatedPass = new Array();
  58300. };
  58301. PostProcessRenderPipeline.prototype.dispose = function () {
  58302. // Must be implemented by children
  58303. };
  58304. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  58305. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  58306. __decorate([
  58307. BABYLON.serialize()
  58308. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  58309. return PostProcessRenderPipeline;
  58310. }());
  58311. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  58312. })(BABYLON || (BABYLON = {}));
  58313. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  58314. var BABYLON;
  58315. (function (BABYLON) {
  58316. var DepthRenderer = /** @class */ (function () {
  58317. function DepthRenderer(scene, type) {
  58318. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  58319. var _this = this;
  58320. this._scene = scene;
  58321. var engine = scene.getEngine();
  58322. // Render target
  58323. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  58324. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58325. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58326. this._depthMap.refreshRate = 1;
  58327. this._depthMap.renderParticles = false;
  58328. this._depthMap.renderList = null;
  58329. // set default depth value to 1.0 (far away)
  58330. this._depthMap.onClearObservable.add(function (engine) {
  58331. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58332. });
  58333. // Custom render function
  58334. var renderSubMesh = function (subMesh) {
  58335. var mesh = subMesh.getRenderingMesh();
  58336. var scene = _this._scene;
  58337. var engine = scene.getEngine();
  58338. var material = subMesh.getMaterial();
  58339. if (!material) {
  58340. return;
  58341. }
  58342. // Culling and reverse (right handed system)
  58343. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  58344. // Managing instances
  58345. var batch = mesh._getInstancesRenderList(subMesh._id);
  58346. if (batch.mustReturn) {
  58347. return;
  58348. }
  58349. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  58350. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  58351. engine.enableEffect(_this._effect);
  58352. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  58353. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  58354. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  58355. // Alpha test
  58356. if (material && material.needAlphaTesting()) {
  58357. var alphaTexture = material.getAlphaTestTexture();
  58358. if (alphaTexture) {
  58359. _this._effect.setTexture("diffuseSampler", alphaTexture);
  58360. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  58361. }
  58362. }
  58363. // Bones
  58364. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58365. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  58366. }
  58367. // Draw
  58368. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58369. }
  58370. };
  58371. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58372. var index;
  58373. if (depthOnlySubMeshes.length) {
  58374. engine.setColorWrite(false);
  58375. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58376. renderSubMesh(depthOnlySubMeshes.data[index]);
  58377. }
  58378. engine.setColorWrite(true);
  58379. }
  58380. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58381. renderSubMesh(opaqueSubMeshes.data[index]);
  58382. }
  58383. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58384. renderSubMesh(alphaTestSubMeshes.data[index]);
  58385. }
  58386. };
  58387. }
  58388. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  58389. var material = subMesh.getMaterial();
  58390. if (material.disableDepthWrite) {
  58391. return false;
  58392. }
  58393. var defines = [];
  58394. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58395. var mesh = subMesh.getMesh();
  58396. // Alpha test
  58397. if (material && material.needAlphaTesting()) {
  58398. defines.push("#define ALPHATEST");
  58399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58400. attribs.push(BABYLON.VertexBuffer.UVKind);
  58401. defines.push("#define UV1");
  58402. }
  58403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58404. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58405. defines.push("#define UV2");
  58406. }
  58407. }
  58408. // Bones
  58409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58410. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58411. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58412. if (mesh.numBoneInfluencers > 4) {
  58413. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58414. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58415. }
  58416. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58417. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  58418. }
  58419. else {
  58420. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58421. }
  58422. // Instances
  58423. if (useInstances) {
  58424. defines.push("#define INSTANCES");
  58425. attribs.push("world0");
  58426. attribs.push("world1");
  58427. attribs.push("world2");
  58428. attribs.push("world3");
  58429. }
  58430. // Get correct effect
  58431. var join = defines.join("\n");
  58432. if (this._cachedDefines !== join) {
  58433. this._cachedDefines = join;
  58434. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  58435. }
  58436. return this._effect.isReady();
  58437. };
  58438. DepthRenderer.prototype.getDepthMap = function () {
  58439. return this._depthMap;
  58440. };
  58441. // Methods
  58442. DepthRenderer.prototype.dispose = function () {
  58443. this._depthMap.dispose();
  58444. };
  58445. return DepthRenderer;
  58446. }());
  58447. BABYLON.DepthRenderer = DepthRenderer;
  58448. })(BABYLON || (BABYLON = {}));
  58449. //# sourceMappingURL=babylon.depthRenderer.js.map
  58450. var BABYLON;
  58451. (function (BABYLON) {
  58452. var SSAORenderingPipeline = /** @class */ (function (_super) {
  58453. __extends(SSAORenderingPipeline, _super);
  58454. /**
  58455. * @constructor
  58456. * @param {string} name - The rendering pipeline name
  58457. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58458. * @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 }
  58459. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58460. */
  58461. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  58462. var _this = _super.call(this, scene.getEngine(), name) || this;
  58463. // Members
  58464. /**
  58465. * The PassPostProcess id in the pipeline that contains the original scene color
  58466. * @type {string}
  58467. */
  58468. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58469. /**
  58470. * The SSAO PostProcess id in the pipeline
  58471. * @type {string}
  58472. */
  58473. _this.SSAORenderEffect = "SSAORenderEffect";
  58474. /**
  58475. * The horizontal blur PostProcess id in the pipeline
  58476. * @type {string}
  58477. */
  58478. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58479. /**
  58480. * The vertical blur PostProcess id in the pipeline
  58481. * @type {string}
  58482. */
  58483. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58484. /**
  58485. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58486. * @type {string}
  58487. */
  58488. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58489. /**
  58490. * The output strength of the SSAO post-process. Default value is 1.0.
  58491. * @type {number}
  58492. */
  58493. _this.totalStrength = 1.0;
  58494. /**
  58495. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  58496. * @type {number}
  58497. */
  58498. _this.radius = 0.0001;
  58499. /**
  58500. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  58501. * Must not be equal to fallOff and superior to fallOff.
  58502. * Default value is 0.975
  58503. * @type {number}
  58504. */
  58505. _this.area = 0.0075;
  58506. /**
  58507. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  58508. * Must not be equal to area and inferior to area.
  58509. * Default value is 0.0
  58510. * @type {number}
  58511. */
  58512. _this.fallOff = 0.000001;
  58513. /**
  58514. * The base color of the SSAO post-process
  58515. * The final result is "base + ssao" between [0, 1]
  58516. * @type {number}
  58517. */
  58518. _this.base = 0.5;
  58519. _this._firstUpdate = true;
  58520. _this._scene = scene;
  58521. // Set up assets
  58522. _this._createRandomTexture();
  58523. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58524. var ssaoRatio = ratio.ssaoRatio || ratio;
  58525. var combineRatio = ratio.combineRatio || ratio;
  58526. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58527. _this._createSSAOPostProcess(ssaoRatio);
  58528. _this._createBlurPostProcess(ssaoRatio);
  58529. _this._createSSAOCombinePostProcess(combineRatio);
  58530. // Set up pipeline
  58531. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58532. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58533. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58534. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58535. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58536. // Finish
  58537. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58538. if (cameras)
  58539. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58540. return _this;
  58541. }
  58542. // Public Methods
  58543. /**
  58544. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58545. */
  58546. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58547. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58548. for (var i = 0; i < this._scene.cameras.length; i++) {
  58549. var camera = this._scene.cameras[i];
  58550. this._originalColorPostProcess.dispose(camera);
  58551. this._ssaoPostProcess.dispose(camera);
  58552. this._blurHPostProcess.dispose(camera);
  58553. this._blurVPostProcess.dispose(camera);
  58554. this._ssaoCombinePostProcess.dispose(camera);
  58555. }
  58556. this._randomTexture.dispose();
  58557. if (disableDepthRender)
  58558. this._scene.disableDepthRenderer();
  58559. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58560. _super.prototype.dispose.call(this);
  58561. };
  58562. // Private Methods
  58563. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  58564. var _this = this;
  58565. var size = 16;
  58566. 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);
  58567. 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);
  58568. this._blurHPostProcess.onActivateObservable.add(function () {
  58569. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  58570. _this._blurHPostProcess.kernel = size * dw;
  58571. });
  58572. this._blurVPostProcess.onActivateObservable.add(function () {
  58573. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  58574. _this._blurVPostProcess.kernel = size * dw;
  58575. });
  58576. };
  58577. SSAORenderingPipeline.prototype._rebuild = function () {
  58578. this._firstUpdate = true;
  58579. _super.prototype._rebuild.call(this);
  58580. };
  58581. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58582. var _this = this;
  58583. var numSamples = 16;
  58584. var sampleSphere = [
  58585. 0.5381, 0.1856, -0.4319,
  58586. 0.1379, 0.2486, 0.4430,
  58587. 0.3371, 0.5679, -0.0057,
  58588. -0.6999, -0.0451, -0.0019,
  58589. 0.0689, -0.1598, -0.8547,
  58590. 0.0560, 0.0069, -0.1843,
  58591. -0.0146, 0.1402, 0.0762,
  58592. 0.0100, -0.1924, -0.0344,
  58593. -0.3577, -0.5301, -0.4358,
  58594. -0.3169, 0.1063, 0.0158,
  58595. 0.0103, -0.5869, 0.0046,
  58596. -0.0897, -0.4940, 0.3287,
  58597. 0.7119, -0.0154, -0.0918,
  58598. -0.0533, 0.0596, -0.5411,
  58599. 0.0352, -0.0631, 0.5460,
  58600. -0.4776, 0.2847, -0.0271
  58601. ];
  58602. var samplesFactor = 1.0 / numSamples;
  58603. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58604. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58605. "area", "fallOff", "base", "range", "viewport"
  58606. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58607. this._ssaoPostProcess.onApply = function (effect) {
  58608. if (_this._firstUpdate) {
  58609. effect.setArray3("sampleSphere", sampleSphere);
  58610. effect.setFloat("samplesFactor", samplesFactor);
  58611. effect.setFloat("randTextureTiles", 4.0);
  58612. }
  58613. effect.setFloat("totalStrength", _this.totalStrength);
  58614. effect.setFloat("radius", _this.radius);
  58615. effect.setFloat("area", _this.area);
  58616. effect.setFloat("fallOff", _this.fallOff);
  58617. effect.setFloat("base", _this.base);
  58618. effect.setTexture("textureSampler", _this._depthTexture);
  58619. effect.setTexture("randomSampler", _this._randomTexture);
  58620. };
  58621. };
  58622. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58623. var _this = this;
  58624. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58625. this._ssaoCombinePostProcess.onApply = function (effect) {
  58626. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58627. };
  58628. };
  58629. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58630. var size = 512;
  58631. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58632. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58633. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58634. var context = this._randomTexture.getContext();
  58635. var rand = function (min, max) {
  58636. return Math.random() * (max - min) + min;
  58637. };
  58638. var randVector = BABYLON.Vector3.Zero();
  58639. for (var x = 0; x < size; x++) {
  58640. for (var y = 0; y < size; y++) {
  58641. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58642. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58643. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58644. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58645. context.fillRect(x, y, 1, 1);
  58646. }
  58647. }
  58648. this._randomTexture.update(false);
  58649. };
  58650. __decorate([
  58651. BABYLON.serialize()
  58652. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58653. __decorate([
  58654. BABYLON.serialize()
  58655. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58656. __decorate([
  58657. BABYLON.serialize()
  58658. ], SSAORenderingPipeline.prototype, "area", void 0);
  58659. __decorate([
  58660. BABYLON.serialize()
  58661. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58662. __decorate([
  58663. BABYLON.serialize()
  58664. ], SSAORenderingPipeline.prototype, "base", void 0);
  58665. return SSAORenderingPipeline;
  58666. }(BABYLON.PostProcessRenderPipeline));
  58667. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58668. })(BABYLON || (BABYLON = {}));
  58669. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58670. var BABYLON;
  58671. (function (BABYLON) {
  58672. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58673. __extends(SSAO2RenderingPipeline, _super);
  58674. /**
  58675. * @constructor
  58676. * @param {string} name - The rendering pipeline name
  58677. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58678. * @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 }
  58679. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58680. */
  58681. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58682. var _this = _super.call(this, scene.getEngine(), name) || this;
  58683. // Members
  58684. /**
  58685. * The PassPostProcess id in the pipeline that contains the original scene color
  58686. * @type {string}
  58687. */
  58688. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58689. /**
  58690. * The SSAO PostProcess id in the pipeline
  58691. * @type {string}
  58692. */
  58693. _this.SSAORenderEffect = "SSAORenderEffect";
  58694. /**
  58695. * The horizontal blur PostProcess id in the pipeline
  58696. * @type {string}
  58697. */
  58698. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58699. /**
  58700. * The vertical blur PostProcess id in the pipeline
  58701. * @type {string}
  58702. */
  58703. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58704. /**
  58705. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58706. * @type {string}
  58707. */
  58708. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58709. /**
  58710. * The output strength of the SSAO post-process. Default value is 1.0.
  58711. * @type {number}
  58712. */
  58713. _this.totalStrength = 1.0;
  58714. /**
  58715. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58716. * @type {number}
  58717. */
  58718. _this.maxZ = 100.0;
  58719. /**
  58720. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58721. * @type {number}
  58722. */
  58723. _this.minZAspect = 0.2;
  58724. /**
  58725. * Number of samples used for the SSAO calculations. Default value is 8
  58726. * @type {number}
  58727. */
  58728. _this._samples = 8;
  58729. /**
  58730. * Are we using bilateral blur ?
  58731. * @type {boolean}
  58732. */
  58733. _this._expensiveBlur = true;
  58734. /**
  58735. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58736. * @type {number}
  58737. */
  58738. _this.radius = 2.0;
  58739. /**
  58740. * The base color of the SSAO post-process
  58741. * The final result is "base + ssao" between [0, 1]
  58742. * @type {number}
  58743. */
  58744. _this.base = 0.1;
  58745. _this._firstUpdate = true;
  58746. _this._scene = scene;
  58747. if (!_this.isSupported) {
  58748. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58749. return _this;
  58750. }
  58751. var ssaoRatio = ratio.ssaoRatio || ratio;
  58752. var blurRatio = ratio.blurRatio || ratio;
  58753. // Set up assets
  58754. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58755. _this._createRandomTexture();
  58756. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58757. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58758. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58759. _this._createSSAOPostProcess(1.0);
  58760. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58761. _this._createSSAOCombinePostProcess(blurRatio);
  58762. // Set up pipeline
  58763. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58766. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58767. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58768. // Finish
  58769. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58770. if (cameras)
  58771. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58772. return _this;
  58773. }
  58774. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58775. get: function () {
  58776. return this._samples;
  58777. },
  58778. set: function (n) {
  58779. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58780. this._samples = n;
  58781. this._sampleSphere = this._generateHemisphere();
  58782. this._firstUpdate = true;
  58783. },
  58784. enumerable: true,
  58785. configurable: true
  58786. });
  58787. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58788. get: function () {
  58789. return this._expensiveBlur;
  58790. },
  58791. set: function (b) {
  58792. 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"]);
  58793. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58794. this._expensiveBlur = b;
  58795. this._firstUpdate = true;
  58796. },
  58797. enumerable: true,
  58798. configurable: true
  58799. });
  58800. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58801. /**
  58802. * Support test.
  58803. * @type {boolean}
  58804. */
  58805. get: function () {
  58806. var engine = BABYLON.Engine.LastCreatedEngine;
  58807. if (!engine) {
  58808. return false;
  58809. }
  58810. return engine.getCaps().drawBuffersExtension;
  58811. },
  58812. enumerable: true,
  58813. configurable: true
  58814. });
  58815. // Public Methods
  58816. /**
  58817. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58818. */
  58819. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58820. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58821. for (var i = 0; i < this._scene.cameras.length; i++) {
  58822. var camera = this._scene.cameras[i];
  58823. this._originalColorPostProcess.dispose(camera);
  58824. this._ssaoPostProcess.dispose(camera);
  58825. this._blurHPostProcess.dispose(camera);
  58826. this._blurVPostProcess.dispose(camera);
  58827. this._ssaoCombinePostProcess.dispose(camera);
  58828. }
  58829. this._randomTexture.dispose();
  58830. if (disableGeometryBufferRenderer)
  58831. this._scene.disableGeometryBufferRenderer();
  58832. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58833. _super.prototype.dispose.call(this);
  58834. };
  58835. // Private Methods
  58836. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58837. var _this = this;
  58838. this._samplerOffsets = [];
  58839. var expensive = this.expensiveBlur;
  58840. for (var i = -8; i < 8; i++) {
  58841. this._samplerOffsets.push(i * 2 + 0.5);
  58842. }
  58843. 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");
  58844. this._blurHPostProcess.onApply = function (effect) {
  58845. if (!_this._scene.activeCamera) {
  58846. return;
  58847. }
  58848. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58849. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58850. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58851. effect.setFloat("radius", _this.radius);
  58852. effect.setTexture("depthSampler", _this._depthTexture);
  58853. if (_this._firstUpdate) {
  58854. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58855. }
  58856. };
  58857. 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");
  58858. this._blurVPostProcess.onApply = function (effect) {
  58859. if (!_this._scene.activeCamera) {
  58860. return;
  58861. }
  58862. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58863. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58864. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58865. effect.setFloat("radius", _this.radius);
  58866. effect.setTexture("depthSampler", _this._depthTexture);
  58867. if (_this._firstUpdate) {
  58868. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58869. _this._firstUpdate = false;
  58870. }
  58871. };
  58872. };
  58873. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58874. this._firstUpdate = true;
  58875. _super.prototype._rebuild.call(this);
  58876. };
  58877. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58878. var numSamples = this.samples;
  58879. var result = [];
  58880. var vector, scale;
  58881. var rand = function (min, max) {
  58882. return Math.random() * (max - min) + min;
  58883. };
  58884. var i = 0;
  58885. while (i < numSamples) {
  58886. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58887. vector.normalize();
  58888. scale = i / numSamples;
  58889. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58890. vector.scaleInPlace(scale);
  58891. result.push(vector.x, vector.y, vector.z);
  58892. i++;
  58893. }
  58894. return result;
  58895. };
  58896. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58897. var _this = this;
  58898. var numSamples = this.samples;
  58899. this._sampleSphere = this._generateHemisphere();
  58900. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58901. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58902. "base", "range", "projection", "near", "far", "texelSize",
  58903. "xViewport", "yViewport", "maxZ", "minZAspect"
  58904. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58905. this._ssaoPostProcess.onApply = function (effect) {
  58906. if (_this._firstUpdate) {
  58907. effect.setArray3("sampleSphere", _this._sampleSphere);
  58908. effect.setFloat("randTextureTiles", 4.0);
  58909. }
  58910. if (!_this._scene.activeCamera) {
  58911. return;
  58912. }
  58913. effect.setFloat("samplesFactor", 1 / _this.samples);
  58914. effect.setFloat("totalStrength", _this.totalStrength);
  58915. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58916. effect.setFloat("radius", _this.radius);
  58917. effect.setFloat("maxZ", _this.maxZ);
  58918. effect.setFloat("minZAspect", _this.minZAspect);
  58919. effect.setFloat("base", _this.base);
  58920. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58921. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58922. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58923. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58924. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58925. effect.setTexture("textureSampler", _this._depthTexture);
  58926. effect.setTexture("normalSampler", _this._normalTexture);
  58927. effect.setTexture("randomSampler", _this._randomTexture);
  58928. };
  58929. };
  58930. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58931. var _this = this;
  58932. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58933. this._ssaoCombinePostProcess.onApply = function (effect) {
  58934. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58935. };
  58936. };
  58937. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58938. var size = 512;
  58939. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58940. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58941. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58942. var context = this._randomTexture.getContext();
  58943. var rand = function (min, max) {
  58944. return Math.random() * (max - min) + min;
  58945. };
  58946. var randVector = BABYLON.Vector3.Zero();
  58947. for (var x = 0; x < size; x++) {
  58948. for (var y = 0; y < size; y++) {
  58949. randVector.x = rand(0.0, 1.0);
  58950. randVector.y = rand(0.0, 1.0);
  58951. randVector.z = 0.0;
  58952. randVector.normalize();
  58953. randVector.scaleInPlace(255);
  58954. randVector.x = Math.floor(randVector.x);
  58955. randVector.y = Math.floor(randVector.y);
  58956. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58957. context.fillRect(x, y, 1, 1);
  58958. }
  58959. }
  58960. this._randomTexture.update(false);
  58961. };
  58962. __decorate([
  58963. BABYLON.serialize()
  58964. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58965. __decorate([
  58966. BABYLON.serialize()
  58967. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58968. __decorate([
  58969. BABYLON.serialize()
  58970. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58971. __decorate([
  58972. BABYLON.serialize("samples")
  58973. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58974. __decorate([
  58975. BABYLON.serialize("expensiveBlur")
  58976. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58977. __decorate([
  58978. BABYLON.serialize()
  58979. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58980. __decorate([
  58981. BABYLON.serialize()
  58982. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58983. return SSAO2RenderingPipeline;
  58984. }(BABYLON.PostProcessRenderPipeline));
  58985. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58986. })(BABYLON || (BABYLON = {}));
  58987. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58988. // BABYLON.JS Chromatic Aberration GLSL Shader
  58989. // Author: Olivier Guyot
  58990. // Separates very slightly R, G and B colors on the edges of the screen
  58991. // Inspired by Francois Tarlier & Martins Upitis
  58992. var BABYLON;
  58993. (function (BABYLON) {
  58994. var LensRenderingPipeline = /** @class */ (function (_super) {
  58995. __extends(LensRenderingPipeline, _super);
  58996. /**
  58997. * @constructor
  58998. *
  58999. * Effect parameters are as follow:
  59000. * {
  59001. * chromatic_aberration: number; // from 0 to x (1 for realism)
  59002. * edge_blur: number; // from 0 to x (1 for realism)
  59003. * distortion: number; // from 0 to x (1 for realism)
  59004. * grain_amount: number; // from 0 to 1
  59005. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  59006. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  59007. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  59008. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  59009. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  59010. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  59011. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  59012. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  59013. * }
  59014. * Note: if an effect parameter is unset, effect is disabled
  59015. *
  59016. * @param {string} name - The rendering pipeline name
  59017. * @param {object} parameters - An object containing all parameters (see above)
  59018. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59019. * @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)
  59020. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59021. */
  59022. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  59023. if (ratio === void 0) { ratio = 1.0; }
  59024. var _this = _super.call(this, scene.getEngine(), name) || this;
  59025. // Lens effects can be of the following:
  59026. // - chromatic aberration (slight shift of RGB colors)
  59027. // - blur on the edge of the lens
  59028. // - lens distortion
  59029. // - depth-of-field blur & highlights enhancing
  59030. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  59031. // - grain effect (noise or custom texture)
  59032. // Two additional texture samplers are needed:
  59033. // - depth map (for depth-of-field)
  59034. // - grain texture
  59035. /**
  59036. * The chromatic aberration PostProcess id in the pipeline
  59037. * @type {string}
  59038. */
  59039. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  59040. /**
  59041. * The highlights enhancing PostProcess id in the pipeline
  59042. * @type {string}
  59043. */
  59044. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  59045. /**
  59046. * The depth-of-field PostProcess id in the pipeline
  59047. * @type {string}
  59048. */
  59049. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  59050. _this._scene = scene;
  59051. // Fetch texture samplers
  59052. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59053. if (parameters.grain_texture) {
  59054. _this._grainTexture = parameters.grain_texture;
  59055. }
  59056. else {
  59057. _this._createGrainTexture();
  59058. }
  59059. // save parameters
  59060. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  59061. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  59062. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  59063. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  59064. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  59065. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  59066. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  59067. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  59068. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  59069. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  59070. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  59071. // Create effects
  59072. _this._createChromaticAberrationPostProcess(ratio);
  59073. _this._createHighlightsPostProcess(ratio);
  59074. _this._createDepthOfFieldPostProcess(ratio / 4);
  59075. // Set up pipeline
  59076. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  59077. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  59078. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  59079. if (_this._highlightsGain === -1) {
  59080. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  59081. }
  59082. // Finish
  59083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59084. if (cameras) {
  59085. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59086. }
  59087. return _this;
  59088. }
  59089. // public methods (self explanatory)
  59090. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  59091. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  59092. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  59093. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  59094. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  59095. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  59096. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  59097. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  59098. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  59099. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  59100. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  59101. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  59102. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  59103. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  59104. };
  59105. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  59106. this._highlightsPostProcess.updateEffect();
  59107. };
  59108. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  59109. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  59110. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  59111. this._highlightsGain = amount;
  59112. };
  59113. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  59114. if (this._highlightsGain === -1) {
  59115. this._highlightsGain = 1.0;
  59116. }
  59117. this._highlightsThreshold = amount;
  59118. };
  59119. LensRenderingPipeline.prototype.disableHighlights = function () {
  59120. this._highlightsGain = -1;
  59121. };
  59122. /**
  59123. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  59124. */
  59125. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59126. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59127. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59128. this._chromaticAberrationPostProcess = null;
  59129. this._highlightsPostProcess = null;
  59130. this._depthOfFieldPostProcess = null;
  59131. this._grainTexture.dispose();
  59132. if (disableDepthRender)
  59133. this._scene.disableDepthRenderer();
  59134. };
  59135. // colors shifting and distortion
  59136. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  59137. var _this = this;
  59138. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  59139. [], // samplers
  59140. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59141. this._chromaticAberrationPostProcess.onApply = function (effect) {
  59142. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  59143. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59144. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59145. };
  59146. };
  59147. // highlights enhancing
  59148. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  59149. var _this = this;
  59150. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  59151. [], // samplers
  59152. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  59153. this._highlightsPostProcess.onApply = function (effect) {
  59154. effect.setFloat('gain', _this._highlightsGain);
  59155. effect.setFloat('threshold', _this._highlightsThreshold);
  59156. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  59157. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59158. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59159. };
  59160. };
  59161. // colors shifting and distortion
  59162. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  59163. var _this = this;
  59164. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  59165. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  59166. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  59167. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59168. this._depthOfFieldPostProcess.onApply = function (effect) {
  59169. effect.setTexture("depthSampler", _this._depthTexture);
  59170. effect.setTexture("grainSampler", _this._grainTexture);
  59171. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  59172. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  59173. effect.setFloat('grain_amount', _this._grainAmount);
  59174. effect.setBool('blur_noise', _this._blurNoise);
  59175. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59176. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59177. effect.setFloat('distortion', _this._distortion);
  59178. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  59179. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  59180. effect.setFloat('aperture', _this._dofAperture);
  59181. effect.setFloat('darken', _this._dofDarken);
  59182. effect.setFloat('edge_blur', _this._edgeBlur);
  59183. effect.setBool('highlights', (_this._highlightsGain !== -1));
  59184. if (_this._scene.activeCamera) {
  59185. effect.setFloat('near', _this._scene.activeCamera.minZ);
  59186. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  59187. }
  59188. };
  59189. };
  59190. // creates a black and white random noise texture, 512x512
  59191. LensRenderingPipeline.prototype._createGrainTexture = function () {
  59192. var size = 512;
  59193. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59194. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59195. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59196. var context = this._grainTexture.getContext();
  59197. var rand = function (min, max) {
  59198. return Math.random() * (max - min) + min;
  59199. };
  59200. var value;
  59201. for (var x = 0; x < size; x++) {
  59202. for (var y = 0; y < size; y++) {
  59203. value = Math.floor(rand(0.42, 0.58) * 255);
  59204. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  59205. context.fillRect(x, y, 1, 1);
  59206. }
  59207. }
  59208. this._grainTexture.update(false);
  59209. };
  59210. return LensRenderingPipeline;
  59211. }(BABYLON.PostProcessRenderPipeline));
  59212. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  59213. })(BABYLON || (BABYLON = {}));
  59214. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  59215. var BABYLON;
  59216. (function (BABYLON) {
  59217. var StandardRenderingPipeline = /** @class */ (function (_super) {
  59218. __extends(StandardRenderingPipeline, _super);
  59219. /**
  59220. * @constructor
  59221. * @param {string} name - The rendering pipeline name
  59222. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59223. * @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)
  59224. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59225. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59226. */
  59227. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59228. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59229. var _this = _super.call(this, scene.getEngine(), name) || this;
  59230. _this.downSampleX4PostProcess = null;
  59231. _this.brightPassPostProcess = null;
  59232. _this.blurHPostProcesses = [];
  59233. _this.blurVPostProcesses = [];
  59234. _this.textureAdderPostProcess = null;
  59235. _this.volumetricLightPostProcess = null;
  59236. _this.volumetricLightSmoothXPostProcess = null;
  59237. _this.volumetricLightSmoothYPostProcess = null;
  59238. _this.volumetricLightMergePostProces = null;
  59239. _this.volumetricLightFinalPostProcess = null;
  59240. _this.luminancePostProcess = null;
  59241. _this.luminanceDownSamplePostProcesses = [];
  59242. _this.hdrPostProcess = null;
  59243. _this.textureAdderFinalPostProcess = null;
  59244. _this.lensFlareFinalPostProcess = null;
  59245. _this.hdrFinalPostProcess = null;
  59246. _this.lensFlarePostProcess = null;
  59247. _this.lensFlareComposePostProcess = null;
  59248. _this.motionBlurPostProcess = null;
  59249. _this.depthOfFieldPostProcess = null;
  59250. // Values
  59251. _this.brightThreshold = 1.0;
  59252. _this.blurWidth = 512.0;
  59253. _this.horizontalBlur = false;
  59254. _this.exposure = 1.0;
  59255. _this.lensTexture = null;
  59256. _this.volumetricLightCoefficient = 0.2;
  59257. _this.volumetricLightPower = 4.0;
  59258. _this.volumetricLightBlurScale = 64.0;
  59259. _this.sourceLight = null;
  59260. _this.hdrMinimumLuminance = 1.0;
  59261. _this.hdrDecreaseRate = 0.5;
  59262. _this.hdrIncreaseRate = 0.5;
  59263. _this.lensColorTexture = null;
  59264. _this.lensFlareStrength = 20.0;
  59265. _this.lensFlareGhostDispersal = 1.4;
  59266. _this.lensFlareHaloWidth = 0.7;
  59267. _this.lensFlareDistortionStrength = 16.0;
  59268. _this.lensStarTexture = null;
  59269. _this.lensFlareDirtTexture = null;
  59270. _this.depthOfFieldDistance = 10.0;
  59271. _this.depthOfFieldBlurWidth = 64.0;
  59272. _this.motionStrength = 1.0;
  59273. // IAnimatable
  59274. _this.animations = [];
  59275. _this._currentDepthOfFieldSource = null;
  59276. _this._hdrCurrentLuminance = 1.0;
  59277. // Getters and setters
  59278. _this._bloomEnabled = true;
  59279. _this._depthOfFieldEnabled = false;
  59280. _this._vlsEnabled = false;
  59281. _this._lensFlareEnabled = false;
  59282. _this._hdrEnabled = false;
  59283. _this._motionBlurEnabled = false;
  59284. _this._motionBlurSamples = 64.0;
  59285. _this._volumetricLightStepsCount = 50.0;
  59286. _this._cameras = cameras || [];
  59287. // Initialize
  59288. _this._scene = scene;
  59289. _this._basePostProcess = originalPostProcess;
  59290. _this._ratio = ratio;
  59291. // Misc
  59292. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59293. // Finish
  59294. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59295. _this._buildPipeline();
  59296. return _this;
  59297. }
  59298. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  59299. get: function () {
  59300. return this._bloomEnabled;
  59301. },
  59302. set: function (enabled) {
  59303. if (this._bloomEnabled === enabled) {
  59304. return;
  59305. }
  59306. this._bloomEnabled = enabled;
  59307. this._buildPipeline();
  59308. },
  59309. enumerable: true,
  59310. configurable: true
  59311. });
  59312. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59313. get: function () {
  59314. return this._depthOfFieldEnabled;
  59315. },
  59316. set: function (enabled) {
  59317. if (this._depthOfFieldEnabled === enabled) {
  59318. return;
  59319. }
  59320. this._depthOfFieldEnabled = enabled;
  59321. this._buildPipeline();
  59322. },
  59323. enumerable: true,
  59324. configurable: true
  59325. });
  59326. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59327. get: function () {
  59328. return this._lensFlareEnabled;
  59329. },
  59330. set: function (enabled) {
  59331. if (this._lensFlareEnabled === enabled) {
  59332. return;
  59333. }
  59334. this._lensFlareEnabled = enabled;
  59335. this._buildPipeline();
  59336. },
  59337. enumerable: true,
  59338. configurable: true
  59339. });
  59340. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  59341. get: function () {
  59342. return this._hdrEnabled;
  59343. },
  59344. set: function (enabled) {
  59345. if (this._hdrEnabled === enabled) {
  59346. return;
  59347. }
  59348. this._hdrEnabled = enabled;
  59349. this._buildPipeline();
  59350. },
  59351. enumerable: true,
  59352. configurable: true
  59353. });
  59354. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  59355. get: function () {
  59356. return this._vlsEnabled;
  59357. },
  59358. set: function (enabled) {
  59359. if (this._vlsEnabled === enabled) {
  59360. return;
  59361. }
  59362. if (enabled) {
  59363. var geometry = this._scene.enableGeometryBufferRenderer();
  59364. if (!geometry) {
  59365. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  59366. return;
  59367. }
  59368. }
  59369. this._vlsEnabled = enabled;
  59370. this._buildPipeline();
  59371. },
  59372. enumerable: true,
  59373. configurable: true
  59374. });
  59375. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  59376. get: function () {
  59377. return this._motionBlurEnabled;
  59378. },
  59379. set: function (enabled) {
  59380. if (this._motionBlurEnabled === enabled) {
  59381. return;
  59382. }
  59383. this._motionBlurEnabled = enabled;
  59384. this._buildPipeline();
  59385. },
  59386. enumerable: true,
  59387. configurable: true
  59388. });
  59389. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  59390. get: function () {
  59391. return this._volumetricLightStepsCount;
  59392. },
  59393. set: function (count) {
  59394. if (this.volumetricLightPostProcess) {
  59395. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  59396. }
  59397. this._volumetricLightStepsCount = count;
  59398. },
  59399. enumerable: true,
  59400. configurable: true
  59401. });
  59402. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  59403. get: function () {
  59404. return this._motionBlurSamples;
  59405. },
  59406. set: function (samples) {
  59407. if (this.motionBlurPostProcess) {
  59408. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  59409. }
  59410. this._motionBlurSamples = samples;
  59411. },
  59412. enumerable: true,
  59413. configurable: true
  59414. });
  59415. StandardRenderingPipeline.prototype._buildPipeline = function () {
  59416. var _this = this;
  59417. var ratio = this._ratio;
  59418. var scene = this._scene;
  59419. this._disposePostProcesses();
  59420. this._reset();
  59421. // Create pass post-process
  59422. if (!this._basePostProcess) {
  59423. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  59424. this.originalPostProcess.onApply = function (effect) {
  59425. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  59426. };
  59427. }
  59428. else {
  59429. this.originalPostProcess = this._basePostProcess;
  59430. }
  59431. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59432. this._currentDepthOfFieldSource = this.originalPostProcess;
  59433. if (this._vlsEnabled) {
  59434. // Create volumetric light
  59435. this._createVolumetricLightPostProcess(scene, ratio);
  59436. // Create volumetric light final post-process
  59437. 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);
  59438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  59439. }
  59440. if (this._bloomEnabled) {
  59441. // Create down sample X4 post-process
  59442. this._createDownSampleX4PostProcess(scene, ratio / 2);
  59443. // Create bright pass post-process
  59444. this._createBrightPassPostProcess(scene, ratio / 2);
  59445. // Create gaussian blur post-processes (down sampling blurs)
  59446. this._createBlurPostProcesses(scene, ratio / 4, 1);
  59447. // Create texture adder post-process
  59448. this._createTextureAdderPostProcess(scene, ratio);
  59449. // Create depth-of-field source post-process
  59450. 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);
  59451. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59452. }
  59453. if (this._lensFlareEnabled) {
  59454. // Create lens flare post-process
  59455. this._createLensFlarePostProcess(scene, ratio);
  59456. // Create depth-of-field source post-process post lens-flare and disable it now
  59457. 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);
  59458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59459. }
  59460. if (this._hdrEnabled) {
  59461. // Create luminance
  59462. this._createLuminancePostProcesses(scene, this._floatTextureType);
  59463. // Create HDR
  59464. this._createHdrPostProcess(scene, ratio);
  59465. // Create depth-of-field source post-process post hdr and disable it now
  59466. 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);
  59467. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  59468. }
  59469. if (this._depthOfFieldEnabled) {
  59470. // Create gaussian blur used by depth-of-field
  59471. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  59472. // Create depth-of-field post-process
  59473. this._createDepthOfFieldPostProcess(scene, ratio);
  59474. }
  59475. if (this._motionBlurEnabled) {
  59476. // Create motion blur post-process
  59477. this._createMotionBlurPostProcess(scene, ratio);
  59478. }
  59479. if (this._cameras !== null) {
  59480. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59481. }
  59482. };
  59483. // Down Sample X4 Post-Processs
  59484. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59485. var _this = this;
  59486. var downSampleX4Offsets = new Array(32);
  59487. 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);
  59488. this.downSampleX4PostProcess.onApply = function (effect) {
  59489. var id = 0;
  59490. var width = _this.downSampleX4PostProcess.width;
  59491. var height = _this.downSampleX4PostProcess.height;
  59492. for (var i = -2; i < 2; i++) {
  59493. for (var j = -2; j < 2; j++) {
  59494. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  59495. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  59496. id += 2;
  59497. }
  59498. }
  59499. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59500. };
  59501. // Add to pipeline
  59502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59503. };
  59504. // Brightpass Post-Process
  59505. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59506. var _this = this;
  59507. var brightOffsets = new Array(8);
  59508. 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);
  59509. this.brightPassPostProcess.onApply = function (effect) {
  59510. var sU = (1.0 / _this.brightPassPostProcess.width);
  59511. var sV = (1.0 / _this.brightPassPostProcess.height);
  59512. brightOffsets[0] = -0.5 * sU;
  59513. brightOffsets[1] = 0.5 * sV;
  59514. brightOffsets[2] = 0.5 * sU;
  59515. brightOffsets[3] = 0.5 * sV;
  59516. brightOffsets[4] = -0.5 * sU;
  59517. brightOffsets[5] = -0.5 * sV;
  59518. brightOffsets[6] = 0.5 * sU;
  59519. brightOffsets[7] = -0.5 * sV;
  59520. effect.setArray2("dsOffsets", brightOffsets);
  59521. effect.setFloat("brightThreshold", _this.brightThreshold);
  59522. };
  59523. // Add to pipeline
  59524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59525. };
  59526. // Create blur H&V post-processes
  59527. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59528. var _this = this;
  59529. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59530. var engine = scene.getEngine();
  59531. 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);
  59532. 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);
  59533. blurX.onActivateObservable.add(function () {
  59534. var dw = blurX.width / engine.getRenderWidth();
  59535. blurX.kernel = _this[blurWidthKey] * dw;
  59536. });
  59537. blurY.onActivateObservable.add(function () {
  59538. var dw = blurY.height / engine.getRenderHeight();
  59539. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  59540. });
  59541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  59542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  59543. this.blurHPostProcesses.push(blurX);
  59544. this.blurVPostProcesses.push(blurY);
  59545. };
  59546. // Create texture adder post-process
  59547. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59548. var _this = this;
  59549. 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);
  59550. this.textureAdderPostProcess.onApply = function (effect) {
  59551. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  59552. effect.setTexture("lensSampler", _this.lensTexture);
  59553. effect.setFloat("exposure", _this.exposure);
  59554. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  59555. };
  59556. // Add to pipeline
  59557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59558. };
  59559. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  59560. var _this = this;
  59561. var geometryRenderer = scene.enableGeometryBufferRenderer();
  59562. geometryRenderer.enablePosition = true;
  59563. var geometry = geometryRenderer.getGBuffer();
  59564. // Base post-process
  59565. 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));
  59566. var depthValues = BABYLON.Vector2.Zero();
  59567. this.volumetricLightPostProcess.onApply = function (effect) {
  59568. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59569. var generator = _this.sourceLight.getShadowGenerator();
  59570. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59571. effect.setTexture("positionSampler", geometry.textures[2]);
  59572. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59573. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59574. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59575. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59576. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59577. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59578. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59579. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59580. effect.setVector2("depthValues", depthValues);
  59581. }
  59582. };
  59583. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59584. // Smooth
  59585. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59586. // Merge
  59587. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59588. this.volumetricLightMergePostProces.onApply = function (effect) {
  59589. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59590. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59591. };
  59592. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59593. };
  59594. // Create luminance
  59595. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59596. var _this = this;
  59597. // Create luminance
  59598. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59599. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59600. var offsets = [];
  59601. this.luminancePostProcess.onApply = function (effect) {
  59602. var sU = (1.0 / _this.luminancePostProcess.width);
  59603. var sV = (1.0 / _this.luminancePostProcess.height);
  59604. offsets[0] = -0.5 * sU;
  59605. offsets[1] = 0.5 * sV;
  59606. offsets[2] = 0.5 * sU;
  59607. offsets[3] = 0.5 * sV;
  59608. offsets[4] = -0.5 * sU;
  59609. offsets[5] = -0.5 * sV;
  59610. offsets[6] = 0.5 * sU;
  59611. offsets[7] = -0.5 * sV;
  59612. effect.setArray2("lumOffsets", offsets);
  59613. };
  59614. // Add to pipeline
  59615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59616. // Create down sample luminance
  59617. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59618. var size = Math.pow(3, i);
  59619. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59620. if (i === 0) {
  59621. defines += "#define FINAL_DOWN_SAMPLER";
  59622. }
  59623. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59624. this.luminanceDownSamplePostProcesses.push(postProcess);
  59625. }
  59626. // Create callbacks and add effects
  59627. var lastLuminance = this.luminancePostProcess;
  59628. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59629. var downSampleOffsets = new Array(18);
  59630. pp.onApply = function (effect) {
  59631. if (!lastLuminance) {
  59632. return;
  59633. }
  59634. var id = 0;
  59635. for (var x = -1; x < 2; x++) {
  59636. for (var y = -1; y < 2; y++) {
  59637. downSampleOffsets[id] = x / lastLuminance.width;
  59638. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59639. id += 2;
  59640. }
  59641. }
  59642. effect.setArray2("dsOffsets", downSampleOffsets);
  59643. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59644. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59645. lastLuminance = _this.luminancePostProcess;
  59646. }
  59647. else {
  59648. lastLuminance = pp;
  59649. }
  59650. };
  59651. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59652. pp.onAfterRender = function (effect) {
  59653. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59654. 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);
  59655. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59656. };
  59657. }
  59658. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59659. });
  59660. };
  59661. // Create HDR post-process
  59662. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59663. var _this = this;
  59664. 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);
  59665. var outputLiminance = 1;
  59666. var time = 0;
  59667. var lastTime = 0;
  59668. this.hdrPostProcess.onApply = function (effect) {
  59669. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59670. time += scene.getEngine().getDeltaTime();
  59671. if (outputLiminance < 0) {
  59672. outputLiminance = _this._hdrCurrentLuminance;
  59673. }
  59674. else {
  59675. var dt = (lastTime - time) / 1000.0;
  59676. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59677. outputLiminance += _this.hdrDecreaseRate * dt;
  59678. }
  59679. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59680. outputLiminance -= _this.hdrIncreaseRate * dt;
  59681. }
  59682. else {
  59683. outputLiminance = _this._hdrCurrentLuminance;
  59684. }
  59685. }
  59686. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59687. effect.setFloat("averageLuminance", outputLiminance);
  59688. lastTime = time;
  59689. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59690. };
  59691. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59692. };
  59693. // Create lens flare post-process
  59694. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59695. var _this = this;
  59696. 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);
  59697. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59698. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59699. 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);
  59700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59701. var resolution = new BABYLON.Vector2(0, 0);
  59702. // Lens flare
  59703. this.lensFlarePostProcess.onApply = function (effect) {
  59704. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59705. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59706. effect.setFloat("strength", _this.lensFlareStrength);
  59707. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59708. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59709. // Shift
  59710. resolution.x = _this.lensFlarePostProcess.width;
  59711. resolution.y = _this.lensFlarePostProcess.height;
  59712. effect.setVector2("resolution", resolution);
  59713. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59714. };
  59715. // Compose
  59716. 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);
  59717. 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);
  59718. this.lensFlareComposePostProcess.onApply = function (effect) {
  59719. if (!_this._scene.activeCamera) {
  59720. return;
  59721. }
  59722. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59723. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59724. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59725. // Lens start rotation matrix
  59726. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59727. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59728. 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));
  59729. camRot *= 4.0;
  59730. 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);
  59731. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59732. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59733. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59734. };
  59735. };
  59736. // Create depth-of-field post-process
  59737. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59738. var _this = this;
  59739. 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);
  59740. this.depthOfFieldPostProcess.onApply = function (effect) {
  59741. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59742. effect.setTexture("depthSampler", _this._getDepthTexture());
  59743. effect.setFloat("distance", _this.depthOfFieldDistance);
  59744. };
  59745. // Add to pipeline
  59746. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59747. };
  59748. // Create motion blur post-process
  59749. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59750. var _this = this;
  59751. 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);
  59752. var motionScale = 0;
  59753. var prevViewProjection = BABYLON.Matrix.Identity();
  59754. var invViewProjection = BABYLON.Matrix.Identity();
  59755. var viewProjection = BABYLON.Matrix.Identity();
  59756. var screenSize = BABYLON.Vector2.Zero();
  59757. this.motionBlurPostProcess.onApply = function (effect) {
  59758. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59759. viewProjection.invertToRef(invViewProjection);
  59760. effect.setMatrix("inverseViewProjection", invViewProjection);
  59761. effect.setMatrix("prevViewProjection", prevViewProjection);
  59762. prevViewProjection = viewProjection;
  59763. screenSize.x = _this.motionBlurPostProcess.width;
  59764. screenSize.y = _this.motionBlurPostProcess.height;
  59765. effect.setVector2("screenSize", screenSize);
  59766. motionScale = scene.getEngine().getFps() / 60.0;
  59767. effect.setFloat("motionScale", motionScale);
  59768. effect.setFloat("motionStrength", _this.motionStrength);
  59769. effect.setTexture("depthSampler", _this._getDepthTexture());
  59770. };
  59771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59772. };
  59773. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59774. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59775. var renderer = this._scene.enableGeometryBufferRenderer();
  59776. return renderer.getGBuffer().textures[0];
  59777. }
  59778. return this._scene.enableDepthRenderer().getDepthMap();
  59779. };
  59780. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59781. for (var i = 0; i < this._cameras.length; i++) {
  59782. var camera = this._cameras[i];
  59783. if (this.originalPostProcess) {
  59784. this.originalPostProcess.dispose(camera);
  59785. }
  59786. if (this.downSampleX4PostProcess) {
  59787. this.downSampleX4PostProcess.dispose(camera);
  59788. }
  59789. if (this.brightPassPostProcess) {
  59790. this.brightPassPostProcess.dispose(camera);
  59791. }
  59792. if (this.textureAdderPostProcess) {
  59793. this.textureAdderPostProcess.dispose(camera);
  59794. }
  59795. if (this.textureAdderFinalPostProcess) {
  59796. this.textureAdderFinalPostProcess.dispose(camera);
  59797. }
  59798. if (this.volumetricLightPostProcess) {
  59799. this.volumetricLightPostProcess.dispose(camera);
  59800. }
  59801. if (this.volumetricLightSmoothXPostProcess) {
  59802. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59803. }
  59804. if (this.volumetricLightSmoothYPostProcess) {
  59805. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59806. }
  59807. if (this.volumetricLightMergePostProces) {
  59808. this.volumetricLightMergePostProces.dispose(camera);
  59809. }
  59810. if (this.volumetricLightFinalPostProcess) {
  59811. this.volumetricLightFinalPostProcess.dispose(camera);
  59812. }
  59813. if (this.lensFlarePostProcess) {
  59814. this.lensFlarePostProcess.dispose(camera);
  59815. }
  59816. if (this.lensFlareComposePostProcess) {
  59817. this.lensFlareComposePostProcess.dispose(camera);
  59818. }
  59819. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59820. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59821. }
  59822. if (this.luminancePostProcess) {
  59823. this.luminancePostProcess.dispose(camera);
  59824. }
  59825. if (this.hdrPostProcess) {
  59826. this.hdrPostProcess.dispose(camera);
  59827. }
  59828. if (this.hdrFinalPostProcess) {
  59829. this.hdrFinalPostProcess.dispose(camera);
  59830. }
  59831. if (this.depthOfFieldPostProcess) {
  59832. this.depthOfFieldPostProcess.dispose(camera);
  59833. }
  59834. if (this.motionBlurPostProcess) {
  59835. this.motionBlurPostProcess.dispose(camera);
  59836. }
  59837. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59838. this.blurHPostProcesses[j].dispose(camera);
  59839. }
  59840. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59841. this.blurVPostProcesses[j].dispose(camera);
  59842. }
  59843. }
  59844. this.originalPostProcess = null;
  59845. this.downSampleX4PostProcess = null;
  59846. this.brightPassPostProcess = null;
  59847. this.textureAdderPostProcess = null;
  59848. this.textureAdderFinalPostProcess = null;
  59849. this.volumetricLightPostProcess = null;
  59850. this.volumetricLightSmoothXPostProcess = null;
  59851. this.volumetricLightSmoothYPostProcess = null;
  59852. this.volumetricLightMergePostProces = null;
  59853. this.volumetricLightFinalPostProcess = null;
  59854. this.lensFlarePostProcess = null;
  59855. this.lensFlareComposePostProcess = null;
  59856. this.luminancePostProcess = null;
  59857. this.hdrPostProcess = null;
  59858. this.hdrFinalPostProcess = null;
  59859. this.depthOfFieldPostProcess = null;
  59860. this.motionBlurPostProcess = null;
  59861. this.luminanceDownSamplePostProcesses = [];
  59862. this.blurHPostProcesses = [];
  59863. this.blurVPostProcesses = [];
  59864. };
  59865. // Dispose
  59866. StandardRenderingPipeline.prototype.dispose = function () {
  59867. this._disposePostProcesses();
  59868. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59869. _super.prototype.dispose.call(this);
  59870. };
  59871. // Serialize rendering pipeline
  59872. StandardRenderingPipeline.prototype.serialize = function () {
  59873. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59874. serializationObject.customType = "StandardRenderingPipeline";
  59875. return serializationObject;
  59876. };
  59877. /**
  59878. * Static members
  59879. */
  59880. // Parse serialized pipeline
  59881. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59882. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59883. };
  59884. // Luminance steps
  59885. StandardRenderingPipeline.LuminanceSteps = 6;
  59886. __decorate([
  59887. BABYLON.serialize()
  59888. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59889. __decorate([
  59890. BABYLON.serialize()
  59891. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59892. __decorate([
  59893. BABYLON.serialize()
  59894. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59895. __decorate([
  59896. BABYLON.serialize()
  59897. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59898. __decorate([
  59899. BABYLON.serializeAsTexture("lensTexture")
  59900. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59901. __decorate([
  59902. BABYLON.serialize()
  59903. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59904. __decorate([
  59905. BABYLON.serialize()
  59906. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59907. __decorate([
  59908. BABYLON.serialize()
  59909. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59910. __decorate([
  59911. BABYLON.serialize()
  59912. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59913. __decorate([
  59914. BABYLON.serialize()
  59915. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59916. __decorate([
  59917. BABYLON.serialize()
  59918. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59919. __decorate([
  59920. BABYLON.serializeAsTexture("lensColorTexture")
  59921. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59922. __decorate([
  59923. BABYLON.serialize()
  59924. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59925. __decorate([
  59926. BABYLON.serialize()
  59927. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59928. __decorate([
  59929. BABYLON.serialize()
  59930. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59931. __decorate([
  59932. BABYLON.serialize()
  59933. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59934. __decorate([
  59935. BABYLON.serializeAsTexture("lensStarTexture")
  59936. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59937. __decorate([
  59938. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59939. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59940. __decorate([
  59941. BABYLON.serialize()
  59942. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59943. __decorate([
  59944. BABYLON.serialize()
  59945. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59946. __decorate([
  59947. BABYLON.serialize()
  59948. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59949. __decorate([
  59950. BABYLON.serialize()
  59951. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  59952. __decorate([
  59953. BABYLON.serialize()
  59954. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59955. __decorate([
  59956. BABYLON.serialize()
  59957. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59958. __decorate([
  59959. BABYLON.serialize()
  59960. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59961. __decorate([
  59962. BABYLON.serialize()
  59963. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59964. __decorate([
  59965. BABYLON.serialize()
  59966. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59967. __decorate([
  59968. BABYLON.serialize()
  59969. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59970. __decorate([
  59971. BABYLON.serialize()
  59972. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59973. __decorate([
  59974. BABYLON.serialize()
  59975. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59976. return StandardRenderingPipeline;
  59977. }(BABYLON.PostProcessRenderPipeline));
  59978. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59979. })(BABYLON || (BABYLON = {}));
  59980. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59981. var BABYLON;
  59982. (function (BABYLON) {
  59983. var FxaaPostProcess = /** @class */ (function (_super) {
  59984. __extends(FxaaPostProcess, _super);
  59985. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59986. if (camera === void 0) { camera = null; }
  59987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59988. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59989. _this.onApplyObservable.add(function (effect) {
  59990. var texelSize = _this.texelSize;
  59991. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59992. });
  59993. return _this;
  59994. }
  59995. return FxaaPostProcess;
  59996. }(BABYLON.PostProcess));
  59997. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59998. })(BABYLON || (BABYLON = {}));
  59999. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  60000. var BABYLON;
  60001. (function (BABYLON) {
  60002. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  60003. __extends(DefaultRenderingPipeline, _super);
  60004. /**
  60005. * @constructor
  60006. * @param {string} name - The rendering pipeline name
  60007. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60008. * @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)
  60009. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60010. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  60011. */
  60012. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  60013. if (automaticBuild === void 0) { automaticBuild = true; }
  60014. var _this = _super.call(this, scene.getEngine(), name) || this;
  60015. _this.PassPostProcessId = "PassPostProcessEffect";
  60016. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  60017. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  60018. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  60019. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  60020. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  60021. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  60022. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  60023. // IAnimatable
  60024. _this.animations = [];
  60025. // Values
  60026. _this._bloomEnabled = false;
  60027. _this._fxaaEnabled = false;
  60028. _this._imageProcessingEnabled = true;
  60029. _this._bloomScale = 0.6;
  60030. _this._buildAllowed = true;
  60031. /**
  60032. * Specifies the size of the bloom blur kernel, relative to the final output size
  60033. */
  60034. _this.bloomKernel = 64;
  60035. /**
  60036. * Specifies the weight of the bloom in the final rendering
  60037. */
  60038. _this._bloomWeight = 0.15;
  60039. _this._cameras = cameras || [];
  60040. _this._buildAllowed = automaticBuild;
  60041. // Initialize
  60042. _this._scene = scene;
  60043. var caps = _this._scene.getEngine().getCaps();
  60044. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  60045. // Misc
  60046. if (_this._hdr) {
  60047. if (caps.textureHalfFloatRender) {
  60048. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60049. }
  60050. else if (caps.textureFloatRender) {
  60051. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60052. }
  60053. }
  60054. else {
  60055. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60056. }
  60057. // Attach
  60058. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60059. _this._buildPipeline();
  60060. return _this;
  60061. }
  60062. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  60063. get: function () {
  60064. return this._bloomWeight;
  60065. },
  60066. set: function (value) {
  60067. if (this._bloomWeight === value) {
  60068. return;
  60069. }
  60070. this._bloomWeight = value;
  60071. if (this._hdr && this.copyBack) {
  60072. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  60073. }
  60074. },
  60075. enumerable: true,
  60076. configurable: true
  60077. });
  60078. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  60079. get: function () {
  60080. return this._bloomScale;
  60081. },
  60082. set: function (value) {
  60083. if (this._bloomScale === value) {
  60084. return;
  60085. }
  60086. this._bloomScale = value;
  60087. this._buildPipeline();
  60088. },
  60089. enumerable: true,
  60090. configurable: true
  60091. });
  60092. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  60093. get: function () {
  60094. return this._bloomEnabled;
  60095. },
  60096. set: function (enabled) {
  60097. if (this._bloomEnabled === enabled) {
  60098. return;
  60099. }
  60100. this._bloomEnabled = enabled;
  60101. this._buildPipeline();
  60102. },
  60103. enumerable: true,
  60104. configurable: true
  60105. });
  60106. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  60107. get: function () {
  60108. return this._fxaaEnabled;
  60109. },
  60110. set: function (enabled) {
  60111. if (this._fxaaEnabled === enabled) {
  60112. return;
  60113. }
  60114. this._fxaaEnabled = enabled;
  60115. this._buildPipeline();
  60116. },
  60117. enumerable: true,
  60118. configurable: true
  60119. });
  60120. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  60121. get: function () {
  60122. return this._imageProcessingEnabled;
  60123. },
  60124. set: function (enabled) {
  60125. if (this._imageProcessingEnabled === enabled) {
  60126. return;
  60127. }
  60128. this._imageProcessingEnabled = enabled;
  60129. this._buildPipeline();
  60130. },
  60131. enumerable: true,
  60132. configurable: true
  60133. });
  60134. /**
  60135. * Force the compilation of the entire pipeline.
  60136. */
  60137. DefaultRenderingPipeline.prototype.prepare = function () {
  60138. var previousState = this._buildAllowed;
  60139. this._buildAllowed = true;
  60140. this._buildPipeline();
  60141. this._buildAllowed = previousState;
  60142. };
  60143. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  60144. var _this = this;
  60145. if (!this._buildAllowed) {
  60146. return;
  60147. }
  60148. var engine = this._scene.getEngine();
  60149. this._disposePostProcesses();
  60150. this._reset();
  60151. if (this.bloomEnabled) {
  60152. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60153. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  60154. if (!this._hdr) {
  60155. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60156. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  60157. this.highlights.autoClear = false;
  60158. this.highlights.alwaysForcePOT = true;
  60159. }
  60160. 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);
  60161. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  60162. this.blurX.alwaysForcePOT = true;
  60163. this.blurX.autoClear = false;
  60164. this.blurX.onActivateObservable.add(function () {
  60165. var dw = _this.blurX.width / engine.getRenderWidth(true);
  60166. _this.blurX.kernel = _this.bloomKernel * dw;
  60167. });
  60168. 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);
  60169. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  60170. this.blurY.alwaysForcePOT = true;
  60171. this.blurY.autoClear = false;
  60172. this.blurY.onActivateObservable.add(function () {
  60173. var dh = _this.blurY.height / engine.getRenderHeight(true);
  60174. _this.blurY.kernel = _this.bloomKernel * dh;
  60175. });
  60176. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60177. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  60178. this.copyBack.alwaysForcePOT = true;
  60179. if (this._hdr) {
  60180. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  60181. var w = this.bloomWeight;
  60182. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  60183. }
  60184. else {
  60185. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  60186. }
  60187. this.copyBack.autoClear = false;
  60188. }
  60189. if (this._imageProcessingEnabled) {
  60190. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60191. if (this._hdr) {
  60192. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  60193. }
  60194. else {
  60195. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  60196. }
  60197. }
  60198. if (this.fxaaEnabled) {
  60199. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60200. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  60201. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60202. }
  60203. else if (this._hdr && this.imageProcessing) {
  60204. this.finalMerge = this.imageProcessing;
  60205. }
  60206. else {
  60207. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60208. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  60209. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60210. }
  60211. if (this.bloomEnabled) {
  60212. if (this._hdr) {
  60213. this.copyBack.shareOutputWith(this.blurX);
  60214. if (this.imageProcessing) {
  60215. this.imageProcessing.shareOutputWith(this.pass);
  60216. this.imageProcessing.autoClear = false;
  60217. }
  60218. else if (this.fxaa) {
  60219. this.fxaa.shareOutputWith(this.pass);
  60220. }
  60221. else {
  60222. this.finalMerge.shareOutputWith(this.pass);
  60223. }
  60224. }
  60225. else {
  60226. if (this.fxaa) {
  60227. this.fxaa.shareOutputWith(this.pass);
  60228. }
  60229. else {
  60230. this.finalMerge.shareOutputWith(this.pass);
  60231. }
  60232. }
  60233. }
  60234. if (this._cameras !== null) {
  60235. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60236. }
  60237. };
  60238. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  60239. for (var i = 0; i < this._cameras.length; i++) {
  60240. var camera = this._cameras[i];
  60241. if (this.pass) {
  60242. this.pass.dispose(camera);
  60243. }
  60244. if (this.highlights) {
  60245. this.highlights.dispose(camera);
  60246. }
  60247. if (this.blurX) {
  60248. this.blurX.dispose(camera);
  60249. }
  60250. if (this.blurY) {
  60251. this.blurY.dispose(camera);
  60252. }
  60253. if (this.copyBack) {
  60254. this.copyBack.dispose(camera);
  60255. }
  60256. if (this.imageProcessing) {
  60257. this.imageProcessing.dispose(camera);
  60258. }
  60259. if (this.fxaa) {
  60260. this.fxaa.dispose(camera);
  60261. }
  60262. if (this.finalMerge) {
  60263. this.finalMerge.dispose(camera);
  60264. }
  60265. }
  60266. this.pass = null;
  60267. this.highlights = null;
  60268. this.blurX = null;
  60269. this.blurY = null;
  60270. this.copyBack = null;
  60271. this.imageProcessing = null;
  60272. this.fxaa = null;
  60273. this.finalMerge = null;
  60274. };
  60275. // Dispose
  60276. DefaultRenderingPipeline.prototype.dispose = function () {
  60277. this._disposePostProcesses();
  60278. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60279. _super.prototype.dispose.call(this);
  60280. };
  60281. // Serialize rendering pipeline
  60282. DefaultRenderingPipeline.prototype.serialize = function () {
  60283. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60284. serializationObject.customType = "DefaultRenderingPipeline";
  60285. return serializationObject;
  60286. };
  60287. // Parse serialized pipeline
  60288. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60289. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  60290. };
  60291. __decorate([
  60292. BABYLON.serialize()
  60293. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  60294. __decorate([
  60295. BABYLON.serialize()
  60296. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  60297. __decorate([
  60298. BABYLON.serialize()
  60299. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  60300. __decorate([
  60301. BABYLON.serialize()
  60302. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  60303. __decorate([
  60304. BABYLON.serialize()
  60305. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  60306. __decorate([
  60307. BABYLON.serialize()
  60308. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  60309. __decorate([
  60310. BABYLON.serialize()
  60311. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  60312. __decorate([
  60313. BABYLON.serialize()
  60314. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  60315. return DefaultRenderingPipeline;
  60316. }(BABYLON.PostProcessRenderPipeline));
  60317. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  60318. })(BABYLON || (BABYLON = {}));
  60319. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  60320. var BABYLON;
  60321. (function (BABYLON) {
  60322. var GeometryBufferRenderer = /** @class */ (function () {
  60323. function GeometryBufferRenderer(scene, ratio) {
  60324. if (ratio === void 0) { ratio = 1; }
  60325. this._enablePosition = false;
  60326. this._scene = scene;
  60327. this._ratio = ratio;
  60328. // Render target
  60329. this._createRenderTargets();
  60330. }
  60331. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  60332. set: function (meshes) {
  60333. this._multiRenderTarget.renderList = meshes;
  60334. },
  60335. enumerable: true,
  60336. configurable: true
  60337. });
  60338. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  60339. get: function () {
  60340. return this._multiRenderTarget.isSupported;
  60341. },
  60342. enumerable: true,
  60343. configurable: true
  60344. });
  60345. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  60346. get: function () {
  60347. return this._enablePosition;
  60348. },
  60349. set: function (enable) {
  60350. this._enablePosition = enable;
  60351. this.dispose();
  60352. this._createRenderTargets();
  60353. },
  60354. enumerable: true,
  60355. configurable: true
  60356. });
  60357. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  60358. var material = subMesh.getMaterial();
  60359. if (material && material.disableDepthWrite) {
  60360. return false;
  60361. }
  60362. var defines = [];
  60363. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60364. var mesh = subMesh.getMesh();
  60365. // Alpha test
  60366. if (material && material.needAlphaTesting()) {
  60367. defines.push("#define ALPHATEST");
  60368. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60369. attribs.push(BABYLON.VertexBuffer.UVKind);
  60370. defines.push("#define UV1");
  60371. }
  60372. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60373. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60374. defines.push("#define UV2");
  60375. }
  60376. }
  60377. // Buffers
  60378. if (this._enablePosition) {
  60379. defines.push("#define POSITION");
  60380. }
  60381. // Bones
  60382. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60383. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60384. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60385. if (mesh.numBoneInfluencers > 4) {
  60386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60388. }
  60389. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60390. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  60391. }
  60392. else {
  60393. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60394. }
  60395. // Instances
  60396. if (useInstances) {
  60397. defines.push("#define INSTANCES");
  60398. attribs.push("world0");
  60399. attribs.push("world1");
  60400. attribs.push("world2");
  60401. attribs.push("world3");
  60402. }
  60403. // Get correct effect
  60404. var join = defines.join("\n");
  60405. if (this._cachedDefines !== join) {
  60406. this._cachedDefines = join;
  60407. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  60408. }
  60409. return this._effect.isReady();
  60410. };
  60411. GeometryBufferRenderer.prototype.getGBuffer = function () {
  60412. return this._multiRenderTarget;
  60413. };
  60414. // Methods
  60415. GeometryBufferRenderer.prototype.dispose = function () {
  60416. this.getGBuffer().dispose();
  60417. };
  60418. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  60419. var _this = this;
  60420. var engine = this._scene.getEngine();
  60421. var count = this._enablePosition ? 3 : 2;
  60422. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  60423. if (!this.isSupported) {
  60424. return;
  60425. }
  60426. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60427. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60428. this._multiRenderTarget.refreshRate = 1;
  60429. this._multiRenderTarget.renderParticles = false;
  60430. this._multiRenderTarget.renderList = null;
  60431. // set default depth value to 1.0 (far away)
  60432. this._multiRenderTarget.onClearObservable.add(function (engine) {
  60433. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  60434. });
  60435. // Custom render function
  60436. var renderSubMesh = function (subMesh) {
  60437. var mesh = subMesh.getRenderingMesh();
  60438. var scene = _this._scene;
  60439. var engine = scene.getEngine();
  60440. var material = subMesh.getMaterial();
  60441. if (!material) {
  60442. return;
  60443. }
  60444. // Culling
  60445. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  60446. // Managing instances
  60447. var batch = mesh._getInstancesRenderList(subMesh._id);
  60448. if (batch.mustReturn) {
  60449. return;
  60450. }
  60451. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60452. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60453. engine.enableEffect(_this._effect);
  60454. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  60455. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60456. _this._effect.setMatrix("view", scene.getViewMatrix());
  60457. // Alpha test
  60458. if (material && material.needAlphaTesting()) {
  60459. var alphaTexture = material.getAlphaTestTexture();
  60460. if (alphaTexture) {
  60461. _this._effect.setTexture("diffuseSampler", alphaTexture);
  60462. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60463. }
  60464. }
  60465. // Bones
  60466. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60467. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60468. }
  60469. // Draw
  60470. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60471. }
  60472. };
  60473. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60474. var index;
  60475. if (depthOnlySubMeshes.length) {
  60476. engine.setColorWrite(false);
  60477. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60478. renderSubMesh(depthOnlySubMeshes.data[index]);
  60479. }
  60480. engine.setColorWrite(true);
  60481. }
  60482. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60483. renderSubMesh(opaqueSubMeshes.data[index]);
  60484. }
  60485. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60486. renderSubMesh(alphaTestSubMeshes.data[index]);
  60487. }
  60488. };
  60489. };
  60490. return GeometryBufferRenderer;
  60491. }());
  60492. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  60493. })(BABYLON || (BABYLON = {}));
  60494. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  60495. var BABYLON;
  60496. (function (BABYLON) {
  60497. var RefractionPostProcess = /** @class */ (function (_super) {
  60498. __extends(RefractionPostProcess, _super);
  60499. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  60500. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  60501. _this.color = color;
  60502. _this.depth = depth;
  60503. _this.colorLevel = colorLevel;
  60504. _this.onActivateObservable.add(function (cam) {
  60505. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  60506. });
  60507. _this.onApplyObservable.add(function (effect) {
  60508. effect.setColor3("baseColor", _this.color);
  60509. effect.setFloat("depth", _this.depth);
  60510. effect.setFloat("colorLevel", _this.colorLevel);
  60511. effect.setTexture("refractionSampler", _this._refRexture);
  60512. });
  60513. return _this;
  60514. }
  60515. // Methods
  60516. RefractionPostProcess.prototype.dispose = function (camera) {
  60517. if (this._refRexture) {
  60518. this._refRexture.dispose();
  60519. }
  60520. _super.prototype.dispose.call(this, camera);
  60521. };
  60522. return RefractionPostProcess;
  60523. }(BABYLON.PostProcess));
  60524. BABYLON.RefractionPostProcess = RefractionPostProcess;
  60525. })(BABYLON || (BABYLON = {}));
  60526. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  60527. var BABYLON;
  60528. (function (BABYLON) {
  60529. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  60530. __extends(BlackAndWhitePostProcess, _super);
  60531. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  60532. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  60533. _this.degree = 1;
  60534. _this.onApplyObservable.add(function (effect) {
  60535. effect.setFloat("degree", _this.degree);
  60536. });
  60537. return _this;
  60538. }
  60539. return BlackAndWhitePostProcess;
  60540. }(BABYLON.PostProcess));
  60541. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  60542. })(BABYLON || (BABYLON = {}));
  60543. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  60544. var BABYLON;
  60545. (function (BABYLON) {
  60546. var ConvolutionPostProcess = /** @class */ (function (_super) {
  60547. __extends(ConvolutionPostProcess, _super);
  60548. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  60549. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  60550. _this.kernel = kernel;
  60551. _this.onApply = function (effect) {
  60552. effect.setFloat2("screenSize", _this.width, _this.height);
  60553. effect.setArray("kernel", _this.kernel);
  60554. };
  60555. return _this;
  60556. }
  60557. // Statics
  60558. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  60559. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  60560. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  60561. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  60562. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  60563. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  60564. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  60565. return ConvolutionPostProcess;
  60566. }(BABYLON.PostProcess));
  60567. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  60568. })(BABYLON || (BABYLON = {}));
  60569. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  60570. var BABYLON;
  60571. (function (BABYLON) {
  60572. var FilterPostProcess = /** @class */ (function (_super) {
  60573. __extends(FilterPostProcess, _super);
  60574. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60575. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60576. _this.kernelMatrix = kernelMatrix;
  60577. _this.onApply = function (effect) {
  60578. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60579. };
  60580. return _this;
  60581. }
  60582. return FilterPostProcess;
  60583. }(BABYLON.PostProcess));
  60584. BABYLON.FilterPostProcess = FilterPostProcess;
  60585. })(BABYLON || (BABYLON = {}));
  60586. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60587. var BABYLON;
  60588. (function (BABYLON) {
  60589. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60590. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60591. __extends(VolumetricLightScatteringPostProcess, _super);
  60592. /**
  60593. * @constructor
  60594. * @param {string} name - The post-process name
  60595. * @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)
  60596. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60597. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60598. * @param {number} samples - The post-process quality, default 100
  60599. * @param {number} samplingMode - The post-process filtering mode
  60600. * @param {BABYLON.Engine} engine - The babylon engine
  60601. * @param {boolean} reusable - If the post-process is reusable
  60602. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60603. */
  60604. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60605. if (samples === void 0) { samples = 100; }
  60606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60607. 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;
  60608. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60609. /**
  60610. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60611. * @type {Vector3}
  60612. */
  60613. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60614. /**
  60615. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60616. * @type {boolean}
  60617. */
  60618. _this.useCustomMeshPosition = false;
  60619. /**
  60620. * If the post-process should inverse the light scattering direction
  60621. * @type {boolean}
  60622. */
  60623. _this.invert = true;
  60624. /**
  60625. * Array containing the excluded meshes not rendered in the internal pass
  60626. */
  60627. _this.excludedMeshes = new Array();
  60628. /**
  60629. * Controls the overall intensity of the post-process
  60630. * @type {number}
  60631. */
  60632. _this.exposure = 0.3;
  60633. /**
  60634. * Dissipates each sample's contribution in range [0, 1]
  60635. * @type {number}
  60636. */
  60637. _this.decay = 0.96815;
  60638. /**
  60639. * Controls the overall intensity of each sample
  60640. * @type {number}
  60641. */
  60642. _this.weight = 0.58767;
  60643. /**
  60644. * Controls the density of each sample
  60645. * @type {number}
  60646. */
  60647. _this.density = 0.926;
  60648. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60649. engine = scene.getEngine();
  60650. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60651. // Configure mesh
  60652. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60653. // Configure
  60654. _this._createPass(scene, ratio.passRatio || ratio);
  60655. _this.onActivate = function (camera) {
  60656. if (!_this.isSupported) {
  60657. _this.dispose(camera);
  60658. }
  60659. _this.onActivate = null;
  60660. };
  60661. _this.onApplyObservable.add(function (effect) {
  60662. _this._updateMeshScreenCoordinates(scene);
  60663. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60664. effect.setFloat("exposure", _this.exposure);
  60665. effect.setFloat("decay", _this.decay);
  60666. effect.setFloat("weight", _this.weight);
  60667. effect.setFloat("density", _this.density);
  60668. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60669. });
  60670. return _this;
  60671. }
  60672. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60673. get: function () {
  60674. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60675. return false;
  60676. },
  60677. set: function (useDiffuseColor) {
  60678. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60679. },
  60680. enumerable: true,
  60681. configurable: true
  60682. });
  60683. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60684. return "VolumetricLightScatteringPostProcess";
  60685. };
  60686. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60687. var mesh = subMesh.getMesh();
  60688. // Render this.mesh as default
  60689. if (mesh === this.mesh && mesh.material) {
  60690. return mesh.material.isReady(mesh);
  60691. }
  60692. var defines = [];
  60693. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60694. var material = subMesh.getMaterial();
  60695. // Alpha test
  60696. if (material) {
  60697. if (material.needAlphaTesting()) {
  60698. defines.push("#define ALPHATEST");
  60699. }
  60700. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60701. attribs.push(BABYLON.VertexBuffer.UVKind);
  60702. defines.push("#define UV1");
  60703. }
  60704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60705. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60706. defines.push("#define UV2");
  60707. }
  60708. }
  60709. // Bones
  60710. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60711. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60712. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60713. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60714. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60715. }
  60716. else {
  60717. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60718. }
  60719. // Instances
  60720. if (useInstances) {
  60721. defines.push("#define INSTANCES");
  60722. attribs.push("world0");
  60723. attribs.push("world1");
  60724. attribs.push("world2");
  60725. attribs.push("world3");
  60726. }
  60727. // Get correct effect
  60728. var join = defines.join("\n");
  60729. if (this._cachedDefines !== join) {
  60730. this._cachedDefines = join;
  60731. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60732. }
  60733. return this._volumetricLightScatteringPass.isReady();
  60734. };
  60735. /**
  60736. * Sets the new light position for light scattering effect
  60737. * @param {BABYLON.Vector3} The new custom light position
  60738. */
  60739. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60740. this.customMeshPosition = position;
  60741. };
  60742. /**
  60743. * Returns the light position for light scattering effect
  60744. * @return {BABYLON.Vector3} The custom light position
  60745. */
  60746. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60747. return this.customMeshPosition;
  60748. };
  60749. /**
  60750. * Disposes the internal assets and detaches the post-process from the camera
  60751. */
  60752. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60753. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60754. if (rttIndex !== -1) {
  60755. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60756. }
  60757. this._volumetricLightScatteringRTT.dispose();
  60758. _super.prototype.dispose.call(this, camera);
  60759. };
  60760. /**
  60761. * Returns the render target texture used by the post-process
  60762. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60763. */
  60764. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60765. return this._volumetricLightScatteringRTT;
  60766. };
  60767. // Private methods
  60768. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60769. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60770. return true;
  60771. }
  60772. return false;
  60773. };
  60774. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60775. var _this = this;
  60776. var engine = scene.getEngine();
  60777. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60778. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60779. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60780. this._volumetricLightScatteringRTT.renderList = null;
  60781. this._volumetricLightScatteringRTT.renderParticles = false;
  60782. var camera = this.getCamera();
  60783. if (camera) {
  60784. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60785. }
  60786. else {
  60787. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60788. }
  60789. // Custom render function for submeshes
  60790. var renderSubMesh = function (subMesh) {
  60791. var mesh = subMesh.getRenderingMesh();
  60792. if (_this._meshExcluded(mesh)) {
  60793. return;
  60794. }
  60795. var material = subMesh.getMaterial();
  60796. if (!material) {
  60797. return;
  60798. }
  60799. var scene = mesh.getScene();
  60800. var engine = scene.getEngine();
  60801. // Culling
  60802. engine.setState(material.backFaceCulling);
  60803. // Managing instances
  60804. var batch = mesh._getInstancesRenderList(subMesh._id);
  60805. if (batch.mustReturn) {
  60806. return;
  60807. }
  60808. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60809. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60810. var effect = _this._volumetricLightScatteringPass;
  60811. if (mesh === _this.mesh) {
  60812. if (subMesh.effect) {
  60813. effect = subMesh.effect;
  60814. }
  60815. else {
  60816. effect = material.getEffect();
  60817. }
  60818. }
  60819. engine.enableEffect(effect);
  60820. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60821. if (mesh === _this.mesh) {
  60822. material.bind(mesh.getWorldMatrix(), mesh);
  60823. }
  60824. else {
  60825. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60826. // Alpha test
  60827. if (material && material.needAlphaTesting()) {
  60828. var alphaTexture = material.getAlphaTestTexture();
  60829. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60830. if (alphaTexture) {
  60831. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60832. }
  60833. }
  60834. // Bones
  60835. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60836. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60837. }
  60838. }
  60839. // Draw
  60840. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60841. }
  60842. };
  60843. // Render target texture callbacks
  60844. var savedSceneClearColor;
  60845. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60846. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60847. savedSceneClearColor = scene.clearColor;
  60848. scene.clearColor = sceneClearColor;
  60849. });
  60850. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60851. scene.clearColor = savedSceneClearColor;
  60852. });
  60853. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60854. var engine = scene.getEngine();
  60855. var index;
  60856. if (depthOnlySubMeshes.length) {
  60857. engine.setColorWrite(false);
  60858. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60859. renderSubMesh(depthOnlySubMeshes.data[index]);
  60860. }
  60861. engine.setColorWrite(true);
  60862. }
  60863. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60864. renderSubMesh(opaqueSubMeshes.data[index]);
  60865. }
  60866. engine.setAlphaTesting(true);
  60867. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60868. renderSubMesh(alphaTestSubMeshes.data[index]);
  60869. }
  60870. engine.setAlphaTesting(false);
  60871. if (transparentSubMeshes.length) {
  60872. // Sort sub meshes
  60873. for (index = 0; index < transparentSubMeshes.length; index++) {
  60874. var submesh = transparentSubMeshes.data[index];
  60875. var boundingInfo = submesh.getBoundingInfo();
  60876. if (boundingInfo && scene.activeCamera) {
  60877. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60878. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60879. }
  60880. }
  60881. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60882. sortedArray.sort(function (a, b) {
  60883. // Alpha index first
  60884. if (a._alphaIndex > b._alphaIndex) {
  60885. return 1;
  60886. }
  60887. if (a._alphaIndex < b._alphaIndex) {
  60888. return -1;
  60889. }
  60890. // Then distance to camera
  60891. if (a._distanceToCamera < b._distanceToCamera) {
  60892. return 1;
  60893. }
  60894. if (a._distanceToCamera > b._distanceToCamera) {
  60895. return -1;
  60896. }
  60897. return 0;
  60898. });
  60899. // Render sub meshes
  60900. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60901. for (index = 0; index < sortedArray.length; index++) {
  60902. renderSubMesh(sortedArray[index]);
  60903. }
  60904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60905. }
  60906. };
  60907. };
  60908. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60909. var transform = scene.getTransformMatrix();
  60910. var meshPosition;
  60911. if (this.useCustomMeshPosition) {
  60912. meshPosition = this.customMeshPosition;
  60913. }
  60914. else if (this.attachedNode) {
  60915. meshPosition = this.attachedNode.position;
  60916. }
  60917. else {
  60918. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60919. }
  60920. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60921. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60922. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60923. if (this.invert)
  60924. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60925. };
  60926. // Static methods
  60927. /**
  60928. * Creates a default mesh for the Volumeric Light Scattering post-process
  60929. * @param {string} The mesh name
  60930. * @param {BABYLON.Scene} The scene where to create the mesh
  60931. * @return {BABYLON.Mesh} the default mesh
  60932. */
  60933. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60934. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60935. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60936. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60937. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60938. mesh.material = material;
  60939. return mesh;
  60940. };
  60941. __decorate([
  60942. BABYLON.serializeAsVector3()
  60943. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60944. __decorate([
  60945. BABYLON.serialize()
  60946. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60947. __decorate([
  60948. BABYLON.serialize()
  60949. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60950. __decorate([
  60951. BABYLON.serializeAsMeshReference()
  60952. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60953. __decorate([
  60954. BABYLON.serialize()
  60955. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60956. __decorate([
  60957. BABYLON.serialize()
  60958. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60959. __decorate([
  60960. BABYLON.serialize()
  60961. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60962. __decorate([
  60963. BABYLON.serialize()
  60964. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60965. __decorate([
  60966. BABYLON.serialize()
  60967. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60968. return VolumetricLightScatteringPostProcess;
  60969. }(BABYLON.PostProcess));
  60970. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60971. })(BABYLON || (BABYLON = {}));
  60972. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60973. //
  60974. // This post-process allows the modification of rendered colors by using
  60975. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60976. //
  60977. // The object needs to be provided an url to a texture containing the color
  60978. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60979. // Use an image editing software to tweak the LUT to match your needs.
  60980. //
  60981. // For an example of a color LUT, see here:
  60982. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60983. // For explanations on color grading, see here:
  60984. // http://udn.epicgames.com/Three/ColorGrading.html
  60985. //
  60986. var BABYLON;
  60987. (function (BABYLON) {
  60988. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60989. __extends(ColorCorrectionPostProcess, _super);
  60990. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60991. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60992. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60993. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60994. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60995. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60996. _this.onApply = function (effect) {
  60997. effect.setTexture("colorTable", _this._colorTableTexture);
  60998. };
  60999. return _this;
  61000. }
  61001. return ColorCorrectionPostProcess;
  61002. }(BABYLON.PostProcess));
  61003. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  61004. })(BABYLON || (BABYLON = {}));
  61005. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  61006. var BABYLON;
  61007. (function (BABYLON) {
  61008. var TonemappingOperator;
  61009. (function (TonemappingOperator) {
  61010. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  61011. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  61012. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  61013. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  61014. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  61015. ;
  61016. var TonemapPostProcess = /** @class */ (function (_super) {
  61017. __extends(TonemapPostProcess, _super);
  61018. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  61019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61020. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61021. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  61022. _this._operator = _operator;
  61023. _this.exposureAdjustment = exposureAdjustment;
  61024. var defines = "#define ";
  61025. if (_this._operator === TonemappingOperator.Hable)
  61026. defines += "HABLE_TONEMAPPING";
  61027. else if (_this._operator === TonemappingOperator.Reinhard)
  61028. defines += "REINHARD_TONEMAPPING";
  61029. else if (_this._operator === TonemappingOperator.HejiDawson)
  61030. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  61031. else if (_this._operator === TonemappingOperator.Photographic)
  61032. defines += "PHOTOGRAPHIC_TONEMAPPING";
  61033. //sadly a second call to create the effect.
  61034. _this.updateEffect(defines);
  61035. _this.onApply = function (effect) {
  61036. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  61037. };
  61038. return _this;
  61039. }
  61040. return TonemapPostProcess;
  61041. }(BABYLON.PostProcess));
  61042. BABYLON.TonemapPostProcess = TonemapPostProcess;
  61043. })(BABYLON || (BABYLON = {}));
  61044. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  61045. var BABYLON;
  61046. (function (BABYLON) {
  61047. var DisplayPassPostProcess = /** @class */ (function (_super) {
  61048. __extends(DisplayPassPostProcess, _super);
  61049. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  61050. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  61051. }
  61052. return DisplayPassPostProcess;
  61053. }(BABYLON.PostProcess));
  61054. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  61055. })(BABYLON || (BABYLON = {}));
  61056. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  61057. var BABYLON;
  61058. (function (BABYLON) {
  61059. var HighlightsPostProcess = /** @class */ (function (_super) {
  61060. __extends(HighlightsPostProcess, _super);
  61061. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61062. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61063. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  61064. }
  61065. return HighlightsPostProcess;
  61066. }(BABYLON.PostProcess));
  61067. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  61068. })(BABYLON || (BABYLON = {}));
  61069. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  61070. var BABYLON;
  61071. (function (BABYLON) {
  61072. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  61073. __extends(ImageProcessingPostProcess, _super);
  61074. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  61075. if (camera === void 0) { camera = null; }
  61076. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61077. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  61078. _this._fromLinearSpace = true;
  61079. /**
  61080. * Defines cache preventing GC.
  61081. */
  61082. _this._defines = {
  61083. IMAGEPROCESSING: false,
  61084. VIGNETTE: false,
  61085. VIGNETTEBLENDMODEMULTIPLY: false,
  61086. VIGNETTEBLENDMODEOPAQUE: false,
  61087. TONEMAPPING: false,
  61088. CONTRAST: false,
  61089. COLORCURVES: false,
  61090. COLORGRADING: false,
  61091. COLORGRADING3D: false,
  61092. FROMLINEARSPACE: false,
  61093. SAMPLER3DGREENDEPTH: false,
  61094. SAMPLER3DBGRMAP: false,
  61095. IMAGEPROCESSINGPOSTPROCESS: false,
  61096. EXPOSURE: false,
  61097. };
  61098. // Setup the configuration as forced by the constructor. This would then not force the
  61099. // scene materials output in linear space and let untouched the default forward pass.
  61100. if (imageProcessingConfiguration) {
  61101. imageProcessingConfiguration.applyByPostProcess = true;
  61102. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  61103. // This will cause the shader to be compiled
  61104. _this.fromLinearSpace = false;
  61105. }
  61106. else {
  61107. _this._attachImageProcessingConfiguration(null, true);
  61108. _this.imageProcessingConfiguration.applyByPostProcess = true;
  61109. }
  61110. _this.onApply = function (effect) {
  61111. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  61112. };
  61113. return _this;
  61114. }
  61115. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  61116. /**
  61117. * Gets the image processing configuration used either in this material.
  61118. */
  61119. get: function () {
  61120. return this._imageProcessingConfiguration;
  61121. },
  61122. /**
  61123. * Sets the Default image processing configuration used either in the this material.
  61124. *
  61125. * If sets to null, the scene one is in use.
  61126. */
  61127. set: function (value) {
  61128. this._attachImageProcessingConfiguration(value);
  61129. },
  61130. enumerable: true,
  61131. configurable: true
  61132. });
  61133. /**
  61134. * Attaches a new image processing configuration to the PBR Material.
  61135. * @param configuration
  61136. */
  61137. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  61138. var _this = this;
  61139. if (doNotBuild === void 0) { doNotBuild = false; }
  61140. if (configuration === this._imageProcessingConfiguration) {
  61141. return;
  61142. }
  61143. // Detaches observer.
  61144. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61145. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61146. }
  61147. // Pick the scene configuration if needed.
  61148. if (!configuration) {
  61149. var scene = null;
  61150. var engine = this.getEngine();
  61151. var camera = this.getCamera();
  61152. if (camera) {
  61153. scene = camera.getScene();
  61154. }
  61155. else if (engine && engine.scenes) {
  61156. var scenes = engine.scenes;
  61157. scene = scenes[scenes.length - 1];
  61158. }
  61159. else {
  61160. scene = BABYLON.Engine.LastCreatedScene;
  61161. }
  61162. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  61163. }
  61164. else {
  61165. this._imageProcessingConfiguration = configuration;
  61166. }
  61167. // Attaches observer.
  61168. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  61169. _this._updateParameters();
  61170. });
  61171. // Ensure the effect will be rebuilt.
  61172. if (!doNotBuild) {
  61173. this._updateParameters();
  61174. }
  61175. };
  61176. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  61177. /**
  61178. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61179. */
  61180. get: function () {
  61181. return this.imageProcessingConfiguration.colorCurves;
  61182. },
  61183. /**
  61184. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61185. */
  61186. set: function (value) {
  61187. this.imageProcessingConfiguration.colorCurves = value;
  61188. },
  61189. enumerable: true,
  61190. configurable: true
  61191. });
  61192. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  61193. /**
  61194. * Gets wether the color curves effect is enabled.
  61195. */
  61196. get: function () {
  61197. return this.imageProcessingConfiguration.colorCurvesEnabled;
  61198. },
  61199. /**
  61200. * Sets wether the color curves effect is enabled.
  61201. */
  61202. set: function (value) {
  61203. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  61204. },
  61205. enumerable: true,
  61206. configurable: true
  61207. });
  61208. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  61209. /**
  61210. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61211. */
  61212. get: function () {
  61213. return this.imageProcessingConfiguration.colorGradingTexture;
  61214. },
  61215. /**
  61216. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  61217. */
  61218. set: function (value) {
  61219. this.imageProcessingConfiguration.colorGradingTexture = value;
  61220. },
  61221. enumerable: true,
  61222. configurable: true
  61223. });
  61224. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  61225. /**
  61226. * Gets wether the color grading effect is enabled.
  61227. */
  61228. get: function () {
  61229. return this.imageProcessingConfiguration.colorGradingEnabled;
  61230. },
  61231. /**
  61232. * Gets wether the color grading effect is enabled.
  61233. */
  61234. set: function (value) {
  61235. this.imageProcessingConfiguration.colorGradingEnabled = value;
  61236. },
  61237. enumerable: true,
  61238. configurable: true
  61239. });
  61240. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  61241. /**
  61242. * Gets exposure used in the effect.
  61243. */
  61244. get: function () {
  61245. return this.imageProcessingConfiguration.exposure;
  61246. },
  61247. /**
  61248. * Sets exposure used in the effect.
  61249. */
  61250. set: function (value) {
  61251. this.imageProcessingConfiguration.exposure = value;
  61252. },
  61253. enumerable: true,
  61254. configurable: true
  61255. });
  61256. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  61257. /**
  61258. * Gets wether tonemapping is enabled or not.
  61259. */
  61260. get: function () {
  61261. return this._imageProcessingConfiguration.toneMappingEnabled;
  61262. },
  61263. /**
  61264. * Sets wether tonemapping is enabled or not
  61265. */
  61266. set: function (value) {
  61267. this._imageProcessingConfiguration.toneMappingEnabled = value;
  61268. },
  61269. enumerable: true,
  61270. configurable: true
  61271. });
  61272. ;
  61273. ;
  61274. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  61275. /**
  61276. * Gets contrast used in the effect.
  61277. */
  61278. get: function () {
  61279. return this.imageProcessingConfiguration.contrast;
  61280. },
  61281. /**
  61282. * Sets contrast used in the effect.
  61283. */
  61284. set: function (value) {
  61285. this.imageProcessingConfiguration.contrast = value;
  61286. },
  61287. enumerable: true,
  61288. configurable: true
  61289. });
  61290. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  61291. /**
  61292. * Gets Vignette stretch size.
  61293. */
  61294. get: function () {
  61295. return this.imageProcessingConfiguration.vignetteStretch;
  61296. },
  61297. /**
  61298. * Sets Vignette stretch size.
  61299. */
  61300. set: function (value) {
  61301. this.imageProcessingConfiguration.vignetteStretch = value;
  61302. },
  61303. enumerable: true,
  61304. configurable: true
  61305. });
  61306. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  61307. /**
  61308. * Gets Vignette centre X Offset.
  61309. */
  61310. get: function () {
  61311. return this.imageProcessingConfiguration.vignetteCentreX;
  61312. },
  61313. /**
  61314. * Sets Vignette centre X Offset.
  61315. */
  61316. set: function (value) {
  61317. this.imageProcessingConfiguration.vignetteCentreX = value;
  61318. },
  61319. enumerable: true,
  61320. configurable: true
  61321. });
  61322. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  61323. /**
  61324. * Gets Vignette centre Y Offset.
  61325. */
  61326. get: function () {
  61327. return this.imageProcessingConfiguration.vignetteCentreY;
  61328. },
  61329. /**
  61330. * Sets Vignette centre Y Offset.
  61331. */
  61332. set: function (value) {
  61333. this.imageProcessingConfiguration.vignetteCentreY = value;
  61334. },
  61335. enumerable: true,
  61336. configurable: true
  61337. });
  61338. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  61339. /**
  61340. * Gets Vignette weight or intensity of the vignette effect.
  61341. */
  61342. get: function () {
  61343. return this.imageProcessingConfiguration.vignetteWeight;
  61344. },
  61345. /**
  61346. * Sets Vignette weight or intensity of the vignette effect.
  61347. */
  61348. set: function (value) {
  61349. this.imageProcessingConfiguration.vignetteWeight = value;
  61350. },
  61351. enumerable: true,
  61352. configurable: true
  61353. });
  61354. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  61355. /**
  61356. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61357. * if vignetteEnabled is set to true.
  61358. */
  61359. get: function () {
  61360. return this.imageProcessingConfiguration.vignetteColor;
  61361. },
  61362. /**
  61363. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  61364. * if vignetteEnabled is set to true.
  61365. */
  61366. set: function (value) {
  61367. this.imageProcessingConfiguration.vignetteColor = value;
  61368. },
  61369. enumerable: true,
  61370. configurable: true
  61371. });
  61372. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  61373. /**
  61374. * Gets Camera field of view used by the Vignette effect.
  61375. */
  61376. get: function () {
  61377. return this.imageProcessingConfiguration.vignetteCameraFov;
  61378. },
  61379. /**
  61380. * Sets Camera field of view used by the Vignette effect.
  61381. */
  61382. set: function (value) {
  61383. this.imageProcessingConfiguration.vignetteCameraFov = value;
  61384. },
  61385. enumerable: true,
  61386. configurable: true
  61387. });
  61388. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  61389. /**
  61390. * Gets the vignette blend mode allowing different kind of effect.
  61391. */
  61392. get: function () {
  61393. return this.imageProcessingConfiguration.vignetteBlendMode;
  61394. },
  61395. /**
  61396. * Sets the vignette blend mode allowing different kind of effect.
  61397. */
  61398. set: function (value) {
  61399. this.imageProcessingConfiguration.vignetteBlendMode = value;
  61400. },
  61401. enumerable: true,
  61402. configurable: true
  61403. });
  61404. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  61405. /**
  61406. * Gets wether the vignette effect is enabled.
  61407. */
  61408. get: function () {
  61409. return this.imageProcessingConfiguration.vignetteEnabled;
  61410. },
  61411. /**
  61412. * Sets wether the vignette effect is enabled.
  61413. */
  61414. set: function (value) {
  61415. this.imageProcessingConfiguration.vignetteEnabled = value;
  61416. },
  61417. enumerable: true,
  61418. configurable: true
  61419. });
  61420. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  61421. /**
  61422. * Gets wether the input of the processing is in Gamma or Linear Space.
  61423. */
  61424. get: function () {
  61425. return this._fromLinearSpace;
  61426. },
  61427. /**
  61428. * Sets wether the input of the processing is in Gamma or Linear Space.
  61429. */
  61430. set: function (value) {
  61431. if (this._fromLinearSpace === value) {
  61432. return;
  61433. }
  61434. this._fromLinearSpace = value;
  61435. this._updateParameters();
  61436. },
  61437. enumerable: true,
  61438. configurable: true
  61439. });
  61440. ImageProcessingPostProcess.prototype.getClassName = function () {
  61441. return "ImageProcessingPostProcess";
  61442. };
  61443. ImageProcessingPostProcess.prototype._updateParameters = function () {
  61444. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  61445. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  61446. var defines = "";
  61447. for (var define in this._defines) {
  61448. if (this._defines[define]) {
  61449. defines += "#define " + define + ";\r\n";
  61450. }
  61451. }
  61452. var samplers = ["textureSampler"];
  61453. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  61454. var uniforms = ["scale"];
  61455. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  61456. this.updateEffect(defines, uniforms, samplers);
  61457. };
  61458. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  61459. _super.prototype.dispose.call(this, camera);
  61460. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61461. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61462. }
  61463. this.imageProcessingConfiguration.applyByPostProcess = false;
  61464. };
  61465. __decorate([
  61466. BABYLON.serialize()
  61467. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  61468. return ImageProcessingPostProcess;
  61469. }(BABYLON.PostProcess));
  61470. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  61471. })(BABYLON || (BABYLON = {}));
  61472. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  61473. var BABYLON;
  61474. (function (BABYLON) {
  61475. var BlurPostProcess = /** @class */ (function (_super) {
  61476. __extends(BlurPostProcess, _super);
  61477. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  61478. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61479. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61480. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  61481. _this.direction = direction;
  61482. _this._packedFloat = false;
  61483. _this.onApplyObservable.add(function (effect) {
  61484. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  61485. });
  61486. _this.kernel = kernel;
  61487. return _this;
  61488. }
  61489. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  61490. /**
  61491. * Gets the length in pixels of the blur sample region
  61492. */
  61493. get: function () {
  61494. return this._idealKernel;
  61495. },
  61496. /**
  61497. * Sets the length in pixels of the blur sample region
  61498. */
  61499. set: function (v) {
  61500. if (this._idealKernel === v) {
  61501. return;
  61502. }
  61503. v = Math.max(v, 1);
  61504. this._idealKernel = v;
  61505. this._kernel = this._nearestBestKernel(v);
  61506. this._updateParameters();
  61507. },
  61508. enumerable: true,
  61509. configurable: true
  61510. });
  61511. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  61512. /**
  61513. * Gets wether or not the blur is unpacking/repacking floats
  61514. */
  61515. get: function () {
  61516. return this._packedFloat;
  61517. },
  61518. /**
  61519. * Sets wether or not the blur needs to unpack/repack floats
  61520. */
  61521. set: function (v) {
  61522. if (this._packedFloat === v) {
  61523. return;
  61524. }
  61525. this._packedFloat = v;
  61526. this._updateParameters();
  61527. },
  61528. enumerable: true,
  61529. configurable: true
  61530. });
  61531. BlurPostProcess.prototype._updateParameters = function () {
  61532. // Generate sampling offsets and weights
  61533. var N = this._kernel;
  61534. var centerIndex = (N - 1) / 2;
  61535. // Generate Gaussian sampling weights over kernel
  61536. var offsets = [];
  61537. var weights = [];
  61538. var totalWeight = 0;
  61539. for (var i = 0; i < N; i++) {
  61540. var u = i / (N - 1);
  61541. var w = this._gaussianWeight(u * 2.0 - 1);
  61542. offsets[i] = (i - centerIndex);
  61543. weights[i] = w;
  61544. totalWeight += w;
  61545. }
  61546. // Normalize weights
  61547. for (var i = 0; i < weights.length; i++) {
  61548. weights[i] /= totalWeight;
  61549. }
  61550. // Optimize: combine samples to take advantage of hardware linear sampling
  61551. // Walk from left to center, combining pairs (symmetrically)
  61552. var linearSamplingWeights = [];
  61553. var linearSamplingOffsets = [];
  61554. var linearSamplingMap = [];
  61555. for (var i = 0; i <= centerIndex; i += 2) {
  61556. var j = Math.min(i + 1, Math.floor(centerIndex));
  61557. var singleCenterSample = i === j;
  61558. if (singleCenterSample) {
  61559. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61560. }
  61561. else {
  61562. var sharedCell = j === centerIndex;
  61563. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  61564. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  61565. if (offsetLinear === 0) {
  61566. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  61567. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  61568. }
  61569. else {
  61570. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  61571. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  61572. }
  61573. }
  61574. }
  61575. for (var i = 0; i < linearSamplingMap.length; i++) {
  61576. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  61577. linearSamplingWeights[i] = linearSamplingMap[i].w;
  61578. }
  61579. // Replace with optimized
  61580. offsets = linearSamplingOffsets;
  61581. weights = linearSamplingWeights;
  61582. // Generate shaders
  61583. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61584. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61585. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61586. var defines = "";
  61587. for (var i = 0; i < varyingCount; i++) {
  61588. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61589. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61590. }
  61591. var depCount = 0;
  61592. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61593. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61594. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61595. depCount++;
  61596. }
  61597. if (this.packedFloat) {
  61598. defines += "#define PACKEDFLOAT 1";
  61599. }
  61600. this.updateEffect(defines, null, null, {
  61601. varyingCount: varyingCount,
  61602. depCount: depCount
  61603. });
  61604. };
  61605. /**
  61606. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61607. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61608. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61609. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61610. * The gaps between physical kernels are compensated for in the weighting of the samples
  61611. * @param idealKernel Ideal blur kernel.
  61612. * @return Nearest best kernel.
  61613. */
  61614. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61615. var v = Math.round(idealKernel);
  61616. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61617. var k = _a[_i];
  61618. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61619. return Math.max(k, 3);
  61620. }
  61621. }
  61622. return Math.max(v, 3);
  61623. };
  61624. /**
  61625. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61626. * @param x The point on the Gaussian distribution to sample.
  61627. * @return the value of the Gaussian function at x.
  61628. */
  61629. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61630. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61631. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61632. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61633. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61634. // truncated at around 1.3% of peak strength.
  61635. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61636. var sigma = (1 / 3);
  61637. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61638. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61639. var weight = (1.0 / denominator) * Math.exp(exponent);
  61640. return weight;
  61641. };
  61642. /**
  61643. * Generates a string that can be used as a floating point number in GLSL.
  61644. * @param x Value to print.
  61645. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61646. * @return GLSL float string.
  61647. */
  61648. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61649. if (decimalFigures === void 0) { decimalFigures = 8; }
  61650. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61651. };
  61652. return BlurPostProcess;
  61653. }(BABYLON.PostProcess));
  61654. BABYLON.BlurPostProcess = BlurPostProcess;
  61655. })(BABYLON || (BABYLON = {}));
  61656. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61657. var BABYLON;
  61658. (function (BABYLON) {
  61659. var Bone = /** @class */ (function (_super) {
  61660. __extends(Bone, _super);
  61661. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61662. if (parentBone === void 0) { parentBone = null; }
  61663. if (localMatrix === void 0) { localMatrix = null; }
  61664. if (restPose === void 0) { restPose = null; }
  61665. if (baseMatrix === void 0) { baseMatrix = null; }
  61666. if (index === void 0) { index = null; }
  61667. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61668. _this.name = name;
  61669. _this.children = new Array();
  61670. _this.animations = new Array();
  61671. // Set this value to map this bone to a different index in the transform matrices.
  61672. // Set this value to -1 to exclude the bone from the transform matrices.
  61673. _this._index = null;
  61674. _this._worldTransform = new BABYLON.Matrix();
  61675. _this._absoluteTransform = new BABYLON.Matrix();
  61676. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61677. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61678. _this._scaleVector = BABYLON.Vector3.One();
  61679. _this._negateScaleChildren = BABYLON.Vector3.One();
  61680. _this._scalingDeterminant = 1;
  61681. _this._skeleton = skeleton;
  61682. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61683. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61684. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61685. _this._index = index;
  61686. skeleton.bones.push(_this);
  61687. _this.setParent(parentBone, false);
  61688. _this._updateDifferenceMatrix();
  61689. return _this;
  61690. }
  61691. Object.defineProperty(Bone.prototype, "_matrix", {
  61692. get: function () {
  61693. return this._localMatrix;
  61694. },
  61695. set: function (val) {
  61696. if (this._localMatrix) {
  61697. this._localMatrix.copyFrom(val);
  61698. }
  61699. else {
  61700. this._localMatrix = val;
  61701. }
  61702. },
  61703. enumerable: true,
  61704. configurable: true
  61705. });
  61706. // Members
  61707. Bone.prototype.getSkeleton = function () {
  61708. return this._skeleton;
  61709. };
  61710. Bone.prototype.getParent = function () {
  61711. return this._parent;
  61712. };
  61713. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61714. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61715. if (this._parent === parent) {
  61716. return;
  61717. }
  61718. if (this._parent) {
  61719. var index = this._parent.children.indexOf(this);
  61720. if (index !== -1) {
  61721. this._parent.children.splice(index, 1);
  61722. }
  61723. }
  61724. this._parent = parent;
  61725. if (this._parent) {
  61726. this._parent.children.push(this);
  61727. }
  61728. if (updateDifferenceMatrix) {
  61729. this._updateDifferenceMatrix();
  61730. }
  61731. };
  61732. Bone.prototype.getLocalMatrix = function () {
  61733. return this._localMatrix;
  61734. };
  61735. Bone.prototype.getBaseMatrix = function () {
  61736. return this._baseMatrix;
  61737. };
  61738. Bone.prototype.getRestPose = function () {
  61739. return this._restPose;
  61740. };
  61741. Bone.prototype.returnToRest = function () {
  61742. this.updateMatrix(this._restPose.clone());
  61743. };
  61744. Bone.prototype.getWorldMatrix = function () {
  61745. return this._worldTransform;
  61746. };
  61747. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61748. return this._invertedAbsoluteTransform;
  61749. };
  61750. Bone.prototype.getAbsoluteTransform = function () {
  61751. return this._absoluteTransform;
  61752. };
  61753. Object.defineProperty(Bone.prototype, "position", {
  61754. // Properties (matches AbstractMesh properties)
  61755. get: function () {
  61756. return this.getPosition();
  61757. },
  61758. set: function (newPosition) {
  61759. this.setPosition(newPosition);
  61760. },
  61761. enumerable: true,
  61762. configurable: true
  61763. });
  61764. Object.defineProperty(Bone.prototype, "rotation", {
  61765. get: function () {
  61766. return this.getRotation();
  61767. },
  61768. set: function (newRotation) {
  61769. this.setRotation(newRotation);
  61770. },
  61771. enumerable: true,
  61772. configurable: true
  61773. });
  61774. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61775. get: function () {
  61776. return this.getRotationQuaternion();
  61777. },
  61778. set: function (newRotation) {
  61779. this.setRotationQuaternion(newRotation);
  61780. },
  61781. enumerable: true,
  61782. configurable: true
  61783. });
  61784. Object.defineProperty(Bone.prototype, "scaling", {
  61785. get: function () {
  61786. return this.getScale();
  61787. },
  61788. set: function (newScaling) {
  61789. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61790. },
  61791. enumerable: true,
  61792. configurable: true
  61793. });
  61794. // Methods
  61795. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61796. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61797. this._baseMatrix = matrix.clone();
  61798. this._localMatrix = matrix.clone();
  61799. this._skeleton._markAsDirty();
  61800. if (updateDifferenceMatrix) {
  61801. this._updateDifferenceMatrix();
  61802. }
  61803. };
  61804. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61805. if (!rootMatrix) {
  61806. rootMatrix = this._baseMatrix;
  61807. }
  61808. if (this._parent) {
  61809. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61810. }
  61811. else {
  61812. this._absoluteTransform.copyFrom(rootMatrix);
  61813. }
  61814. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61815. for (var index = 0; index < this.children.length; index++) {
  61816. this.children[index]._updateDifferenceMatrix();
  61817. }
  61818. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61819. };
  61820. Bone.prototype.markAsDirty = function () {
  61821. this._currentRenderId++;
  61822. this._skeleton._markAsDirty();
  61823. };
  61824. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61825. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61826. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61827. // all animation may be coming from a library skeleton, so may need to create animation
  61828. if (this.animations.length === 0) {
  61829. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61830. this.animations[0].setKeys([]);
  61831. }
  61832. // get animation info / verify there is such a range from the source bone
  61833. var sourceRange = source.animations[0].getRange(rangeName);
  61834. if (!sourceRange) {
  61835. return false;
  61836. }
  61837. var from = sourceRange.from;
  61838. var to = sourceRange.to;
  61839. var sourceKeys = source.animations[0].getKeys();
  61840. // rescaling prep
  61841. var sourceBoneLength = source.length;
  61842. var sourceParent = source.getParent();
  61843. var parent = this.getParent();
  61844. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61845. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61846. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61847. var destKeys = this.animations[0].getKeys();
  61848. // loop vars declaration
  61849. var orig;
  61850. var origTranslation;
  61851. var mat;
  61852. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61853. orig = sourceKeys[key];
  61854. if (orig.frame >= from && orig.frame <= to) {
  61855. if (rescaleAsRequired) {
  61856. mat = orig.value.clone();
  61857. // scale based on parent ratio, when bone has parent
  61858. if (parentScalingReqd) {
  61859. origTranslation = mat.getTranslation();
  61860. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61861. // scale based on skeleton dimension ratio when root bone, and value is passed
  61862. }
  61863. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61864. origTranslation = mat.getTranslation();
  61865. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61866. // use original when root bone, and no data for skelDimensionsRatio
  61867. }
  61868. else {
  61869. mat = orig.value;
  61870. }
  61871. }
  61872. else {
  61873. mat = orig.value;
  61874. }
  61875. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61876. }
  61877. }
  61878. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61879. return true;
  61880. };
  61881. /**
  61882. * Translate the bone in local or world space.
  61883. * @param vec The amount to translate the bone.
  61884. * @param space The space that the translation is in.
  61885. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61886. */
  61887. Bone.prototype.translate = function (vec, space, mesh) {
  61888. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61889. var lm = this.getLocalMatrix();
  61890. if (space == BABYLON.Space.LOCAL) {
  61891. lm.m[12] += vec.x;
  61892. lm.m[13] += vec.y;
  61893. lm.m[14] += vec.z;
  61894. }
  61895. else {
  61896. var wm = null;
  61897. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61898. if (mesh) {
  61899. wm = mesh.getWorldMatrix();
  61900. }
  61901. this._skeleton.computeAbsoluteTransforms();
  61902. var tmat = Bone._tmpMats[0];
  61903. var tvec = Bone._tmpVecs[0];
  61904. if (this._parent) {
  61905. if (mesh && wm) {
  61906. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61907. tmat.multiplyToRef(wm, tmat);
  61908. }
  61909. else {
  61910. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61911. }
  61912. }
  61913. tmat.m[12] = 0;
  61914. tmat.m[13] = 0;
  61915. tmat.m[14] = 0;
  61916. tmat.invert();
  61917. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61918. lm.m[12] += tvec.x;
  61919. lm.m[13] += tvec.y;
  61920. lm.m[14] += tvec.z;
  61921. }
  61922. this.markAsDirty();
  61923. };
  61924. /**
  61925. * Set the postion of the bone in local or world space.
  61926. * @param position The position to set the bone.
  61927. * @param space The space that the position is in.
  61928. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61929. */
  61930. Bone.prototype.setPosition = function (position, space, mesh) {
  61931. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61932. var lm = this.getLocalMatrix();
  61933. if (space == BABYLON.Space.LOCAL) {
  61934. lm.m[12] = position.x;
  61935. lm.m[13] = position.y;
  61936. lm.m[14] = position.z;
  61937. }
  61938. else {
  61939. var wm = null;
  61940. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61941. if (mesh) {
  61942. wm = mesh.getWorldMatrix();
  61943. }
  61944. this._skeleton.computeAbsoluteTransforms();
  61945. var tmat = Bone._tmpMats[0];
  61946. var vec = Bone._tmpVecs[0];
  61947. if (this._parent) {
  61948. if (mesh && wm) {
  61949. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61950. tmat.multiplyToRef(wm, tmat);
  61951. }
  61952. else {
  61953. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61954. }
  61955. }
  61956. tmat.invert();
  61957. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61958. lm.m[12] = vec.x;
  61959. lm.m[13] = vec.y;
  61960. lm.m[14] = vec.z;
  61961. }
  61962. this.markAsDirty();
  61963. };
  61964. /**
  61965. * Set the absolute postion of the bone (world space).
  61966. * @param position The position to set the bone.
  61967. * @param mesh The mesh that this bone is attached to.
  61968. */
  61969. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61970. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61971. };
  61972. /**
  61973. * Set the scale of the bone on the x, y and z axes.
  61974. * @param x The scale of the bone on the x axis.
  61975. * @param x The scale of the bone on the y axis.
  61976. * @param z The scale of the bone on the z axis.
  61977. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61978. */
  61979. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61980. if (scaleChildren === void 0) { scaleChildren = false; }
  61981. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61982. if (!scaleChildren) {
  61983. this._negateScaleChildren.x = 1 / x;
  61984. this._negateScaleChildren.y = 1 / y;
  61985. this._negateScaleChildren.z = 1 / z;
  61986. }
  61987. this._syncScaleVector();
  61988. }
  61989. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61990. };
  61991. /**
  61992. * Scale the bone on the x, y and z axes.
  61993. * @param x The amount to scale the bone on the x axis.
  61994. * @param x The amount to scale the bone on the y axis.
  61995. * @param z The amount to scale the bone on the z axis.
  61996. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61997. */
  61998. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61999. if (scaleChildren === void 0) { scaleChildren = false; }
  62000. var locMat = this.getLocalMatrix();
  62001. var origLocMat = Bone._tmpMats[0];
  62002. origLocMat.copyFrom(locMat);
  62003. var origLocMatInv = Bone._tmpMats[1];
  62004. origLocMatInv.copyFrom(origLocMat);
  62005. origLocMatInv.invert();
  62006. var scaleMat = Bone._tmpMats[2];
  62007. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  62008. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  62009. this._scaleVector.x *= x;
  62010. this._scaleVector.y *= y;
  62011. this._scaleVector.z *= z;
  62012. locMat.multiplyToRef(origLocMatInv, locMat);
  62013. locMat.multiplyToRef(scaleMat, locMat);
  62014. locMat.multiplyToRef(origLocMat, locMat);
  62015. var parent = this.getParent();
  62016. if (parent) {
  62017. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  62018. }
  62019. else {
  62020. this.getAbsoluteTransform().copyFrom(locMat);
  62021. }
  62022. var len = this.children.length;
  62023. scaleMat.invert();
  62024. for (var i = 0; i < len; i++) {
  62025. var child = this.children[i];
  62026. var cm = child.getLocalMatrix();
  62027. cm.multiplyToRef(scaleMat, cm);
  62028. var lm = child.getLocalMatrix();
  62029. lm.m[12] *= x;
  62030. lm.m[13] *= y;
  62031. lm.m[14] *= z;
  62032. }
  62033. this.computeAbsoluteTransforms();
  62034. if (scaleChildren) {
  62035. for (var i = 0; i < len; i++) {
  62036. this.children[i].scale(x, y, z, scaleChildren);
  62037. }
  62038. }
  62039. this.markAsDirty();
  62040. };
  62041. /**
  62042. * Set the yaw, pitch, and roll of the bone in local or world space.
  62043. * @param yaw The rotation of the bone on the y axis.
  62044. * @param pitch The rotation of the bone on the x axis.
  62045. * @param roll The rotation of the bone on the z axis.
  62046. * @param space The space that the axes of rotation are in.
  62047. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62048. */
  62049. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  62050. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62051. var rotMat = Bone._tmpMats[0];
  62052. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  62053. var rotMatInv = Bone._tmpMats[1];
  62054. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62055. rotMatInv.multiplyToRef(rotMat, rotMat);
  62056. this._rotateWithMatrix(rotMat, space, mesh);
  62057. };
  62058. /**
  62059. * Rotate the bone on an axis in local or world space.
  62060. * @param axis The axis to rotate the bone on.
  62061. * @param amount The amount to rotate the bone.
  62062. * @param space The space that the axis is in.
  62063. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62064. */
  62065. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  62066. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62067. var rmat = Bone._tmpMats[0];
  62068. rmat.m[12] = 0;
  62069. rmat.m[13] = 0;
  62070. rmat.m[14] = 0;
  62071. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  62072. this._rotateWithMatrix(rmat, space, mesh);
  62073. };
  62074. /**
  62075. * Set the rotation of the bone to a particular axis angle in local or world space.
  62076. * @param axis The axis to rotate the bone on.
  62077. * @param angle The angle that the bone should be rotated to.
  62078. * @param space The space that the axis is in.
  62079. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62080. */
  62081. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  62082. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62083. var rotMat = Bone._tmpMats[0];
  62084. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  62085. var rotMatInv = Bone._tmpMats[1];
  62086. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62087. rotMatInv.multiplyToRef(rotMat, rotMat);
  62088. this._rotateWithMatrix(rotMat, space, mesh);
  62089. };
  62090. /**
  62091. * Set the euler rotation of the bone in local of world space.
  62092. * @param rotation The euler rotation that the bone should be set to.
  62093. * @param space The space that the rotation is in.
  62094. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62095. */
  62096. Bone.prototype.setRotation = function (rotation, space, mesh) {
  62097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62098. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  62099. };
  62100. /**
  62101. * Set the quaternion rotation of the bone in local of world space.
  62102. * @param quat The quaternion rotation that the bone should be set to.
  62103. * @param space The space that the rotation is in.
  62104. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62105. */
  62106. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  62107. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62108. var rotMatInv = Bone._tmpMats[0];
  62109. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62110. var rotMat = Bone._tmpMats[1];
  62111. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  62112. rotMatInv.multiplyToRef(rotMat, rotMat);
  62113. this._rotateWithMatrix(rotMat, space, mesh);
  62114. };
  62115. /**
  62116. * Set the rotation matrix of the bone in local of world space.
  62117. * @param rotMat The rotation matrix that the bone should be set to.
  62118. * @param space The space that the rotation is in.
  62119. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62120. */
  62121. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  62122. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62123. var rotMatInv = Bone._tmpMats[0];
  62124. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62125. var rotMat2 = Bone._tmpMats[1];
  62126. rotMat2.copyFrom(rotMat);
  62127. rotMatInv.multiplyToRef(rotMat, rotMat2);
  62128. this._rotateWithMatrix(rotMat2, space, mesh);
  62129. };
  62130. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  62131. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62132. var lmat = this.getLocalMatrix();
  62133. var lx = lmat.m[12];
  62134. var ly = lmat.m[13];
  62135. var lz = lmat.m[14];
  62136. var parent = this.getParent();
  62137. var parentScale = Bone._tmpMats[3];
  62138. var parentScaleInv = Bone._tmpMats[4];
  62139. if (parent) {
  62140. if (space == BABYLON.Space.WORLD) {
  62141. if (mesh) {
  62142. parentScale.copyFrom(mesh.getWorldMatrix());
  62143. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  62144. }
  62145. else {
  62146. parentScale.copyFrom(parent.getAbsoluteTransform());
  62147. }
  62148. }
  62149. else {
  62150. parentScale = parent._scaleMatrix;
  62151. }
  62152. parentScaleInv.copyFrom(parentScale);
  62153. parentScaleInv.invert();
  62154. lmat.multiplyToRef(parentScale, lmat);
  62155. lmat.multiplyToRef(rmat, lmat);
  62156. lmat.multiplyToRef(parentScaleInv, lmat);
  62157. }
  62158. else {
  62159. if (space == BABYLON.Space.WORLD && mesh) {
  62160. parentScale.copyFrom(mesh.getWorldMatrix());
  62161. parentScaleInv.copyFrom(parentScale);
  62162. parentScaleInv.invert();
  62163. lmat.multiplyToRef(parentScale, lmat);
  62164. lmat.multiplyToRef(rmat, lmat);
  62165. lmat.multiplyToRef(parentScaleInv, lmat);
  62166. }
  62167. else {
  62168. lmat.multiplyToRef(rmat, lmat);
  62169. }
  62170. }
  62171. lmat.m[12] = lx;
  62172. lmat.m[13] = ly;
  62173. lmat.m[14] = lz;
  62174. this.computeAbsoluteTransforms();
  62175. this.markAsDirty();
  62176. };
  62177. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  62178. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62179. if (space == BABYLON.Space.WORLD) {
  62180. var scaleMatrix = Bone._tmpMats[2];
  62181. scaleMatrix.copyFrom(this._scaleMatrix);
  62182. rotMatInv.copyFrom(this.getAbsoluteTransform());
  62183. if (mesh) {
  62184. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  62185. var meshScale = Bone._tmpMats[3];
  62186. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  62187. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  62188. }
  62189. rotMatInv.invert();
  62190. scaleMatrix.m[0] *= this._scalingDeterminant;
  62191. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62192. }
  62193. else {
  62194. rotMatInv.copyFrom(this.getLocalMatrix());
  62195. rotMatInv.invert();
  62196. var scaleMatrix = Bone._tmpMats[2];
  62197. scaleMatrix.copyFrom(this._scaleMatrix);
  62198. if (this._parent) {
  62199. var pscaleMatrix = Bone._tmpMats[3];
  62200. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  62201. pscaleMatrix.invert();
  62202. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  62203. }
  62204. else {
  62205. scaleMatrix.m[0] *= this._scalingDeterminant;
  62206. }
  62207. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62208. }
  62209. };
  62210. /**
  62211. * Get the scale of the bone
  62212. * @returns the scale of the bone
  62213. */
  62214. Bone.prototype.getScale = function () {
  62215. return this._scaleVector.clone();
  62216. };
  62217. /**
  62218. * Copy the scale of the bone to a vector3.
  62219. * @param result The vector3 to copy the scale to
  62220. */
  62221. Bone.prototype.getScaleToRef = function (result) {
  62222. result.copyFrom(this._scaleVector);
  62223. };
  62224. /**
  62225. * Get the position of the bone in local or world space.
  62226. * @param space The space that the returned position is in.
  62227. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62228. * @returns The position of the bone
  62229. */
  62230. Bone.prototype.getPosition = function (space, mesh) {
  62231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62232. if (mesh === void 0) { mesh = null; }
  62233. var pos = BABYLON.Vector3.Zero();
  62234. this.getPositionToRef(space, mesh, pos);
  62235. return pos;
  62236. };
  62237. /**
  62238. * Copy the position of the bone to a vector3 in local or world space.
  62239. * @param space The space that the returned position is in.
  62240. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62241. * @param result The vector3 to copy the position to.
  62242. */
  62243. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  62244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62245. if (space == BABYLON.Space.LOCAL) {
  62246. var lm = this.getLocalMatrix();
  62247. result.x = lm.m[12];
  62248. result.y = lm.m[13];
  62249. result.z = lm.m[14];
  62250. }
  62251. else {
  62252. var wm = null;
  62253. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62254. if (mesh) {
  62255. wm = mesh.getWorldMatrix();
  62256. }
  62257. this._skeleton.computeAbsoluteTransforms();
  62258. var tmat = Bone._tmpMats[0];
  62259. if (mesh && wm) {
  62260. tmat.copyFrom(this.getAbsoluteTransform());
  62261. tmat.multiplyToRef(wm, tmat);
  62262. }
  62263. else {
  62264. tmat = this.getAbsoluteTransform();
  62265. }
  62266. result.x = tmat.m[12];
  62267. result.y = tmat.m[13];
  62268. result.z = tmat.m[14];
  62269. }
  62270. };
  62271. /**
  62272. * Get the absolute position of the bone (world space).
  62273. * @param mesh The mesh that this bone is attached to.
  62274. * @returns The absolute position of the bone
  62275. */
  62276. Bone.prototype.getAbsolutePosition = function (mesh) {
  62277. if (mesh === void 0) { mesh = null; }
  62278. var pos = BABYLON.Vector3.Zero();
  62279. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  62280. return pos;
  62281. };
  62282. /**
  62283. * Copy the absolute position of the bone (world space) to the result param.
  62284. * @param mesh The mesh that this bone is attached to.
  62285. * @param result The vector3 to copy the absolute position to.
  62286. */
  62287. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  62288. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  62289. };
  62290. /**
  62291. * Compute the absolute transforms of this bone and its children.
  62292. */
  62293. Bone.prototype.computeAbsoluteTransforms = function () {
  62294. if (this._parent) {
  62295. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62296. }
  62297. else {
  62298. this._absoluteTransform.copyFrom(this._localMatrix);
  62299. var poseMatrix = this._skeleton.getPoseMatrix();
  62300. if (poseMatrix) {
  62301. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  62302. }
  62303. }
  62304. var children = this.children;
  62305. var len = children.length;
  62306. for (var i = 0; i < len; i++) {
  62307. children[i].computeAbsoluteTransforms();
  62308. }
  62309. };
  62310. Bone.prototype._syncScaleVector = function () {
  62311. var lm = this.getLocalMatrix();
  62312. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  62313. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  62314. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  62315. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  62316. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  62317. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  62318. this._scaleVector.x = xs * Math.sqrt(xsq);
  62319. this._scaleVector.y = ys * Math.sqrt(ysq);
  62320. this._scaleVector.z = zs * Math.sqrt(zsq);
  62321. if (this._parent) {
  62322. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  62323. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  62324. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  62325. }
  62326. 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);
  62327. };
  62328. /**
  62329. * Get the world direction from an axis that is in the local space of the bone.
  62330. * @param localAxis The local direction that is used to compute the world direction.
  62331. * @param mesh The mesh that this bone is attached to.
  62332. * @returns The world direction
  62333. */
  62334. Bone.prototype.getDirection = function (localAxis, mesh) {
  62335. if (mesh === void 0) { mesh = null; }
  62336. var result = BABYLON.Vector3.Zero();
  62337. this.getDirectionToRef(localAxis, mesh, result);
  62338. return result;
  62339. };
  62340. /**
  62341. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  62342. * @param localAxis The local direction that is used to compute the world direction.
  62343. * @param mesh The mesh that this bone is attached to.
  62344. * @param result The vector3 that the world direction will be copied to.
  62345. */
  62346. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  62347. if (mesh === void 0) { mesh = null; }
  62348. var wm = null;
  62349. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62350. if (mesh) {
  62351. wm = mesh.getWorldMatrix();
  62352. }
  62353. this._skeleton.computeAbsoluteTransforms();
  62354. var mat = Bone._tmpMats[0];
  62355. mat.copyFrom(this.getAbsoluteTransform());
  62356. if (mesh && wm) {
  62357. mat.multiplyToRef(wm, mat);
  62358. }
  62359. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  62360. result.normalize();
  62361. };
  62362. /**
  62363. * Get the euler rotation of the bone in local or world space.
  62364. * @param space The space that the rotation should be in.
  62365. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62366. * @returns The euler rotation
  62367. */
  62368. Bone.prototype.getRotation = function (space, mesh) {
  62369. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62370. if (mesh === void 0) { mesh = null; }
  62371. var result = BABYLON.Vector3.Zero();
  62372. this.getRotationToRef(space, mesh, result);
  62373. return result;
  62374. };
  62375. /**
  62376. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  62377. * @param space The space that the rotation should be in.
  62378. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62379. * @param result The vector3 that the rotation should be copied to.
  62380. */
  62381. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  62382. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62383. if (mesh === void 0) { mesh = null; }
  62384. var quat = Bone._tmpQuat;
  62385. this.getRotationQuaternionToRef(space, mesh, quat);
  62386. quat.toEulerAnglesToRef(result);
  62387. };
  62388. /**
  62389. * Get the quaternion rotation of the bone in either local or world space.
  62390. * @param space The space that the rotation should be in.
  62391. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62392. * @returns The quaternion rotation
  62393. */
  62394. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  62395. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62396. if (mesh === void 0) { mesh = null; }
  62397. var result = BABYLON.Quaternion.Identity();
  62398. this.getRotationQuaternionToRef(space, mesh, result);
  62399. return result;
  62400. };
  62401. /**
  62402. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  62403. * @param space The space that the rotation should be in.
  62404. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62405. * @param result The quaternion that the rotation should be copied to.
  62406. */
  62407. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  62408. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62409. if (mesh === void 0) { mesh = null; }
  62410. if (space == BABYLON.Space.LOCAL) {
  62411. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62412. }
  62413. else {
  62414. var mat = Bone._tmpMats[0];
  62415. var amat = this.getAbsoluteTransform();
  62416. if (mesh) {
  62417. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62418. }
  62419. else {
  62420. mat.copyFrom(amat);
  62421. }
  62422. mat.m[0] *= this._scalingDeterminant;
  62423. mat.m[1] *= this._scalingDeterminant;
  62424. mat.m[2] *= this._scalingDeterminant;
  62425. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  62426. }
  62427. };
  62428. /**
  62429. * Get the rotation matrix of the bone in local or world space.
  62430. * @param space The space that the rotation should be in.
  62431. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62432. * @returns The rotation matrix
  62433. */
  62434. Bone.prototype.getRotationMatrix = function (space, mesh) {
  62435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62436. var result = BABYLON.Matrix.Identity();
  62437. this.getRotationMatrixToRef(space, mesh, result);
  62438. return result;
  62439. };
  62440. /**
  62441. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  62442. * @param space The space that the rotation should be in.
  62443. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62444. * @param result The quaternion that the rotation should be copied to.
  62445. */
  62446. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  62447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62448. if (space == BABYLON.Space.LOCAL) {
  62449. this.getLocalMatrix().getRotationMatrixToRef(result);
  62450. }
  62451. else {
  62452. var mat = Bone._tmpMats[0];
  62453. var amat = this.getAbsoluteTransform();
  62454. if (mesh) {
  62455. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  62456. }
  62457. else {
  62458. mat.copyFrom(amat);
  62459. }
  62460. mat.m[0] *= this._scalingDeterminant;
  62461. mat.m[1] *= this._scalingDeterminant;
  62462. mat.m[2] *= this._scalingDeterminant;
  62463. mat.getRotationMatrixToRef(result);
  62464. }
  62465. };
  62466. /**
  62467. * Get the world position of a point that is in the local space of the bone.
  62468. * @param position The local position
  62469. * @param mesh The mesh that this bone is attached to.
  62470. * @returns The world position
  62471. */
  62472. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  62473. if (mesh === void 0) { mesh = null; }
  62474. var result = BABYLON.Vector3.Zero();
  62475. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  62476. return result;
  62477. };
  62478. /**
  62479. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  62480. * @param position The local position
  62481. * @param mesh The mesh that this bone is attached to.
  62482. * @param result The vector3 that the world position should be copied to.
  62483. */
  62484. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  62485. if (mesh === void 0) { mesh = null; }
  62486. var wm = null;
  62487. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62488. if (mesh) {
  62489. wm = mesh.getWorldMatrix();
  62490. }
  62491. this._skeleton.computeAbsoluteTransforms();
  62492. var tmat = Bone._tmpMats[0];
  62493. if (mesh && wm) {
  62494. tmat.copyFrom(this.getAbsoluteTransform());
  62495. tmat.multiplyToRef(wm, tmat);
  62496. }
  62497. else {
  62498. tmat = this.getAbsoluteTransform();
  62499. }
  62500. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62501. };
  62502. /**
  62503. * Get the local position of a point that is in world space.
  62504. * @param position The world position
  62505. * @param mesh The mesh that this bone is attached to.
  62506. * @returns The local position
  62507. */
  62508. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  62509. if (mesh === void 0) { mesh = null; }
  62510. var result = BABYLON.Vector3.Zero();
  62511. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  62512. return result;
  62513. };
  62514. /**
  62515. * Get the local position of a point that is in world space and copy it to the result param.
  62516. * @param position The world position
  62517. * @param mesh The mesh that this bone is attached to.
  62518. * @param result The vector3 that the local position should be copied to.
  62519. */
  62520. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  62521. if (mesh === void 0) { mesh = null; }
  62522. var wm = null;
  62523. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62524. if (mesh) {
  62525. wm = mesh.getWorldMatrix();
  62526. }
  62527. this._skeleton.computeAbsoluteTransforms();
  62528. var tmat = Bone._tmpMats[0];
  62529. tmat.copyFrom(this.getAbsoluteTransform());
  62530. if (mesh && wm) {
  62531. tmat.multiplyToRef(wm, tmat);
  62532. }
  62533. tmat.invert();
  62534. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  62535. };
  62536. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62537. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  62538. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62539. return Bone;
  62540. }(BABYLON.Node));
  62541. BABYLON.Bone = Bone;
  62542. })(BABYLON || (BABYLON = {}));
  62543. //# sourceMappingURL=babylon.bone.js.map
  62544. var BABYLON;
  62545. (function (BABYLON) {
  62546. var BoneIKController = /** @class */ (function () {
  62547. function BoneIKController(mesh, bone, options) {
  62548. this.targetPosition = BABYLON.Vector3.Zero();
  62549. this.poleTargetPosition = BABYLON.Vector3.Zero();
  62550. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  62551. this.poleAngle = 0;
  62552. this.slerpAmount = 1;
  62553. this._bone1Quat = BABYLON.Quaternion.Identity();
  62554. this._bone1Mat = BABYLON.Matrix.Identity();
  62555. this._bone2Ang = Math.PI;
  62556. this._maxAngle = Math.PI;
  62557. this._rightHandedSystem = false;
  62558. this._bendAxis = BABYLON.Vector3.Right();
  62559. this._slerping = false;
  62560. this._adjustRoll = 0;
  62561. this._bone2 = bone;
  62562. this._bone1 = bone.getParent();
  62563. if (!this._bone1) {
  62564. return;
  62565. }
  62566. this.mesh = mesh;
  62567. var bonePos = bone.getPosition();
  62568. if (bone.getAbsoluteTransform().determinant() > 0) {
  62569. this._rightHandedSystem = true;
  62570. this._bendAxis.x = 0;
  62571. this._bendAxis.y = 0;
  62572. this._bendAxis.z = -1;
  62573. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  62574. this._adjustRoll = Math.PI * .5;
  62575. this._bendAxis.z = 1;
  62576. }
  62577. }
  62578. if (this._bone1.length) {
  62579. var boneScale1 = this._bone1.getScale();
  62580. var boneScale2 = this._bone2.getScale();
  62581. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62582. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62583. }
  62584. else if (this._bone1.children[0]) {
  62585. mesh.computeWorldMatrix(true);
  62586. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62587. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62588. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62589. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62590. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62591. }
  62592. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62593. this.maxAngle = Math.PI;
  62594. if (options) {
  62595. if (options.targetMesh) {
  62596. this.targetMesh = options.targetMesh;
  62597. this.targetMesh.computeWorldMatrix(true);
  62598. }
  62599. if (options.poleTargetMesh) {
  62600. this.poleTargetMesh = options.poleTargetMesh;
  62601. this.poleTargetMesh.computeWorldMatrix(true);
  62602. }
  62603. else if (options.poleTargetBone) {
  62604. this.poleTargetBone = options.poleTargetBone;
  62605. }
  62606. else if (this._bone1.getParent()) {
  62607. this.poleTargetBone = this._bone1.getParent();
  62608. }
  62609. if (options.poleTargetLocalOffset) {
  62610. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62611. }
  62612. if (options.poleAngle) {
  62613. this.poleAngle = options.poleAngle;
  62614. }
  62615. if (options.bendAxis) {
  62616. this._bendAxis.copyFrom(options.bendAxis);
  62617. }
  62618. if (options.maxAngle) {
  62619. this.maxAngle = options.maxAngle;
  62620. }
  62621. if (options.slerpAmount) {
  62622. this.slerpAmount = options.slerpAmount;
  62623. }
  62624. }
  62625. }
  62626. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62627. get: function () {
  62628. return this._maxAngle;
  62629. },
  62630. set: function (value) {
  62631. this._setMaxAngle(value);
  62632. },
  62633. enumerable: true,
  62634. configurable: true
  62635. });
  62636. BoneIKController.prototype._setMaxAngle = function (ang) {
  62637. if (ang < 0) {
  62638. ang = 0;
  62639. }
  62640. if (ang > Math.PI || ang == undefined) {
  62641. ang = Math.PI;
  62642. }
  62643. this._maxAngle = ang;
  62644. var a = this._bone1Length;
  62645. var b = this._bone2Length;
  62646. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62647. };
  62648. BoneIKController.prototype.update = function () {
  62649. var bone1 = this._bone1;
  62650. if (!bone1) {
  62651. return;
  62652. }
  62653. var target = this.targetPosition;
  62654. var poleTarget = this.poleTargetPosition;
  62655. var mat1 = BoneIKController._tmpMats[0];
  62656. var mat2 = BoneIKController._tmpMats[1];
  62657. if (this.targetMesh) {
  62658. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62659. }
  62660. if (this.poleTargetBone) {
  62661. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62662. }
  62663. else if (this.poleTargetMesh) {
  62664. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62665. }
  62666. var bonePos = BoneIKController._tmpVecs[0];
  62667. var zaxis = BoneIKController._tmpVecs[1];
  62668. var xaxis = BoneIKController._tmpVecs[2];
  62669. var yaxis = BoneIKController._tmpVecs[3];
  62670. var upAxis = BoneIKController._tmpVecs[4];
  62671. var _tmpQuat = BoneIKController._tmpQuat;
  62672. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62673. poleTarget.subtractToRef(bonePos, upAxis);
  62674. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62675. upAxis.y = 1;
  62676. }
  62677. else {
  62678. upAxis.normalize();
  62679. }
  62680. target.subtractToRef(bonePos, yaxis);
  62681. yaxis.normalize();
  62682. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62683. zaxis.normalize();
  62684. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62685. xaxis.normalize();
  62686. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62687. var a = this._bone1Length;
  62688. var b = this._bone2Length;
  62689. var c = BABYLON.Vector3.Distance(bonePos, target);
  62690. if (this._maxReach > 0) {
  62691. c = Math.min(this._maxReach, c);
  62692. }
  62693. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62694. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62695. if (acosa > 1) {
  62696. acosa = 1;
  62697. }
  62698. if (acosb > 1) {
  62699. acosb = 1;
  62700. }
  62701. if (acosa < -1) {
  62702. acosa = -1;
  62703. }
  62704. if (acosb < -1) {
  62705. acosb = -1;
  62706. }
  62707. var angA = Math.acos(acosa);
  62708. var angB = Math.acos(acosb);
  62709. var angC = -angA - angB;
  62710. if (this._rightHandedSystem) {
  62711. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62712. mat2.multiplyToRef(mat1, mat1);
  62713. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62714. mat2.multiplyToRef(mat1, mat1);
  62715. }
  62716. else {
  62717. var _tmpVec = BoneIKController._tmpVecs[5];
  62718. _tmpVec.copyFrom(this._bendAxis);
  62719. _tmpVec.x *= -1;
  62720. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62721. mat2.multiplyToRef(mat1, mat1);
  62722. }
  62723. if (this.poleAngle) {
  62724. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62725. mat1.multiplyToRef(mat2, mat1);
  62726. }
  62727. if (this._bone1) {
  62728. if (this.slerpAmount < 1) {
  62729. if (!this._slerping) {
  62730. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62731. }
  62732. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62733. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62734. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62735. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62736. this._slerping = true;
  62737. }
  62738. else {
  62739. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62740. this._bone1Mat.copyFrom(mat1);
  62741. this._slerping = false;
  62742. }
  62743. }
  62744. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62745. this._bone2Ang = angC;
  62746. };
  62747. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62748. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62749. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62750. return BoneIKController;
  62751. }());
  62752. BABYLON.BoneIKController = BoneIKController;
  62753. })(BABYLON || (BABYLON = {}));
  62754. //# sourceMappingURL=babylon.boneIKController.js.map
  62755. var BABYLON;
  62756. (function (BABYLON) {
  62757. var BoneLookController = /** @class */ (function () {
  62758. /**
  62759. * Create a BoneLookController
  62760. * @param mesh the mesh that the bone belongs to
  62761. * @param bone the bone that will be looking to the target
  62762. * @param target the target Vector3 to look at
  62763. * @param settings optional settings:
  62764. * - maxYaw: the maximum angle the bone will yaw to
  62765. * - minYaw: the minimum angle the bone will yaw to
  62766. * - maxPitch: the maximum angle the bone will pitch to
  62767. * - minPitch: the minimum angle the bone will yaw to
  62768. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62769. * - upAxis: the up axis of the coordinate system
  62770. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62771. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62772. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62773. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62774. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62775. * - adjustRoll: used to make an adjustment to the roll of the bone
  62776. **/
  62777. function BoneLookController(mesh, bone, target, options) {
  62778. /**
  62779. * The up axis of the coordinate system that is used when the bone is rotated.
  62780. */
  62781. this.upAxis = BABYLON.Vector3.Up();
  62782. /**
  62783. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62784. */
  62785. this.upAxisSpace = BABYLON.Space.LOCAL;
  62786. /**
  62787. * Used to make an adjustment to the yaw of the bone.
  62788. */
  62789. this.adjustYaw = 0;
  62790. /**
  62791. * Used to make an adjustment to the pitch of the bone.
  62792. */
  62793. this.adjustPitch = 0;
  62794. /**
  62795. * Used to make an adjustment to the roll of the bone.
  62796. */
  62797. this.adjustRoll = 0;
  62798. /**
  62799. * 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).
  62800. */
  62801. this.slerpAmount = 1;
  62802. this._boneQuat = BABYLON.Quaternion.Identity();
  62803. this._slerping = false;
  62804. this._firstFrameSkipped = false;
  62805. this._fowardAxis = BABYLON.Vector3.Forward();
  62806. this.mesh = mesh;
  62807. this.bone = bone;
  62808. this.target = target;
  62809. if (options) {
  62810. if (options.adjustYaw) {
  62811. this.adjustYaw = options.adjustYaw;
  62812. }
  62813. if (options.adjustPitch) {
  62814. this.adjustPitch = options.adjustPitch;
  62815. }
  62816. if (options.adjustRoll) {
  62817. this.adjustRoll = options.adjustRoll;
  62818. }
  62819. if (options.maxYaw != null) {
  62820. this.maxYaw = options.maxYaw;
  62821. }
  62822. else {
  62823. this.maxYaw = Math.PI;
  62824. }
  62825. if (options.minYaw != null) {
  62826. this.minYaw = options.minYaw;
  62827. }
  62828. else {
  62829. this.minYaw = -Math.PI;
  62830. }
  62831. if (options.maxPitch != null) {
  62832. this.maxPitch = options.maxPitch;
  62833. }
  62834. else {
  62835. this.maxPitch = Math.PI;
  62836. }
  62837. if (options.minPitch != null) {
  62838. this.minPitch = options.minPitch;
  62839. }
  62840. else {
  62841. this.minPitch = -Math.PI;
  62842. }
  62843. if (options.slerpAmount != null) {
  62844. this.slerpAmount = options.slerpAmount;
  62845. }
  62846. if (options.upAxis != null) {
  62847. this.upAxis = options.upAxis;
  62848. }
  62849. if (options.upAxisSpace != null) {
  62850. this.upAxisSpace = options.upAxisSpace;
  62851. }
  62852. if (options.yawAxis != null || options.pitchAxis != null) {
  62853. var newYawAxis = BABYLON.Axis.Y;
  62854. var newPitchAxis = BABYLON.Axis.X;
  62855. if (options.yawAxis != null) {
  62856. newYawAxis = options.yawAxis.clone();
  62857. newYawAxis.normalize();
  62858. }
  62859. if (options.pitchAxis != null) {
  62860. newPitchAxis = options.pitchAxis.clone();
  62861. newPitchAxis.normalize();
  62862. }
  62863. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62864. this._transformYawPitch = BABYLON.Matrix.Identity();
  62865. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62866. this._transformYawPitchInv = this._transformYawPitch.clone();
  62867. this._transformYawPitch.invert();
  62868. }
  62869. }
  62870. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62871. this.upAxisSpace = BABYLON.Space.LOCAL;
  62872. }
  62873. }
  62874. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62875. /**
  62876. * Get/set the minimum yaw angle that the bone can look to.
  62877. */
  62878. get: function () {
  62879. return this._minYaw;
  62880. },
  62881. set: function (value) {
  62882. this._minYaw = value;
  62883. this._minYawSin = Math.sin(value);
  62884. this._minYawCos = Math.cos(value);
  62885. if (this._maxYaw != null) {
  62886. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62887. this._yawRange = this._maxYaw - this._minYaw;
  62888. }
  62889. },
  62890. enumerable: true,
  62891. configurable: true
  62892. });
  62893. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62894. /**
  62895. * Get/set the maximum yaw angle that the bone can look to.
  62896. */
  62897. get: function () {
  62898. return this._maxYaw;
  62899. },
  62900. set: function (value) {
  62901. this._maxYaw = value;
  62902. this._maxYawSin = Math.sin(value);
  62903. this._maxYawCos = Math.cos(value);
  62904. if (this._minYaw != null) {
  62905. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62906. this._yawRange = this._maxYaw - this._minYaw;
  62907. }
  62908. },
  62909. enumerable: true,
  62910. configurable: true
  62911. });
  62912. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62913. /**
  62914. * Get/set the minimum pitch angle that the bone can look to.
  62915. */
  62916. get: function () {
  62917. return this._minPitch;
  62918. },
  62919. set: function (value) {
  62920. this._minPitch = value;
  62921. this._minPitchTan = Math.tan(value);
  62922. },
  62923. enumerable: true,
  62924. configurable: true
  62925. });
  62926. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62927. /**
  62928. * Get/set the maximum pitch angle that the bone can look to.
  62929. */
  62930. get: function () {
  62931. return this._maxPitch;
  62932. },
  62933. set: function (value) {
  62934. this._maxPitch = value;
  62935. this._maxPitchTan = Math.tan(value);
  62936. },
  62937. enumerable: true,
  62938. configurable: true
  62939. });
  62940. /**
  62941. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62942. */
  62943. BoneLookController.prototype.update = function () {
  62944. //skip the first frame when slerping so that the mesh rotation is correct
  62945. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62946. this._firstFrameSkipped = true;
  62947. return;
  62948. }
  62949. var bone = this.bone;
  62950. var bonePos = BoneLookController._tmpVecs[0];
  62951. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62952. var target = this.target;
  62953. var _tmpMat1 = BoneLookController._tmpMats[0];
  62954. var _tmpMat2 = BoneLookController._tmpMats[1];
  62955. var mesh = this.mesh;
  62956. var parentBone = bone.getParent();
  62957. var upAxis = BoneLookController._tmpVecs[1];
  62958. upAxis.copyFrom(this.upAxis);
  62959. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62960. if (this._transformYawPitch) {
  62961. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62962. }
  62963. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62964. }
  62965. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62966. mesh.getDirectionToRef(upAxis, upAxis);
  62967. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62968. upAxis.normalize();
  62969. }
  62970. }
  62971. var checkYaw = false;
  62972. var checkPitch = false;
  62973. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62974. checkYaw = true;
  62975. }
  62976. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62977. checkPitch = true;
  62978. }
  62979. if (checkYaw || checkPitch) {
  62980. var spaceMat = BoneLookController._tmpMats[2];
  62981. var spaceMatInv = BoneLookController._tmpMats[3];
  62982. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62983. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62984. }
  62985. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62986. spaceMat.copyFrom(mesh.getWorldMatrix());
  62987. }
  62988. else {
  62989. var forwardAxis = BoneLookController._tmpVecs[2];
  62990. forwardAxis.copyFrom(this._fowardAxis);
  62991. if (this._transformYawPitch) {
  62992. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62993. }
  62994. if (parentBone) {
  62995. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62996. }
  62997. else {
  62998. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62999. }
  63000. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  63001. rightAxis.normalize();
  63002. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  63003. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  63004. }
  63005. spaceMat.invertToRef(spaceMatInv);
  63006. var xzlen = null;
  63007. if (checkPitch) {
  63008. var localTarget = BoneLookController._tmpVecs[3];
  63009. target.subtractToRef(bonePos, localTarget);
  63010. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63011. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63012. var pitch = Math.atan2(localTarget.y, xzlen);
  63013. var newPitch = pitch;
  63014. if (pitch > this._maxPitch) {
  63015. localTarget.y = this._maxPitchTan * xzlen;
  63016. newPitch = this._maxPitch;
  63017. }
  63018. else if (pitch < this._minPitch) {
  63019. localTarget.y = this._minPitchTan * xzlen;
  63020. newPitch = this._minPitch;
  63021. }
  63022. if (pitch != newPitch) {
  63023. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63024. localTarget.addInPlace(bonePos);
  63025. target = localTarget;
  63026. }
  63027. }
  63028. if (checkYaw) {
  63029. var localTarget = BoneLookController._tmpVecs[4];
  63030. target.subtractToRef(bonePos, localTarget);
  63031. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63032. var yaw = Math.atan2(localTarget.x, localTarget.z);
  63033. var newYaw = yaw;
  63034. if (yaw > this._maxYaw || yaw < this._minYaw) {
  63035. if (xzlen == null) {
  63036. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63037. }
  63038. if (this._yawRange > Math.PI) {
  63039. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  63040. localTarget.z = this._maxYawCos * xzlen;
  63041. localTarget.x = this._maxYawSin * xzlen;
  63042. newYaw = this._maxYaw;
  63043. }
  63044. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  63045. localTarget.z = this._minYawCos * xzlen;
  63046. localTarget.x = this._minYawSin * xzlen;
  63047. newYaw = this._minYaw;
  63048. }
  63049. }
  63050. else {
  63051. if (yaw > this._maxYaw) {
  63052. localTarget.z = this._maxYawCos * xzlen;
  63053. localTarget.x = this._maxYawSin * xzlen;
  63054. newYaw = this._maxYaw;
  63055. }
  63056. else if (yaw < this._minYaw) {
  63057. localTarget.z = this._minYawCos * xzlen;
  63058. localTarget.x = this._minYawSin * xzlen;
  63059. newYaw = this._minYaw;
  63060. }
  63061. }
  63062. }
  63063. if (this._slerping && this._yawRange > Math.PI) {
  63064. //are we going to be crossing into the min/max region?
  63065. var boneFwd = BoneLookController._tmpVecs[8];
  63066. boneFwd.copyFrom(BABYLON.Axis.Z);
  63067. if (this._transformYawPitch) {
  63068. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  63069. }
  63070. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  63071. this._boneQuat.toRotationMatrix(boneRotMat);
  63072. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  63073. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  63074. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  63075. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  63076. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  63077. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  63078. if (angBtwTar > angBtwMidYaw) {
  63079. if (xzlen == null) {
  63080. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63081. }
  63082. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  63083. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  63084. if (angBtwMin < angBtwMax) {
  63085. newYaw = boneYaw + Math.PI * .75;
  63086. localTarget.z = Math.cos(newYaw) * xzlen;
  63087. localTarget.x = Math.sin(newYaw) * xzlen;
  63088. }
  63089. else {
  63090. newYaw = boneYaw - Math.PI * .75;
  63091. localTarget.z = Math.cos(newYaw) * xzlen;
  63092. localTarget.x = Math.sin(newYaw) * xzlen;
  63093. }
  63094. }
  63095. }
  63096. if (yaw != newYaw) {
  63097. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63098. localTarget.addInPlace(bonePos);
  63099. target = localTarget;
  63100. }
  63101. }
  63102. }
  63103. var zaxis = BoneLookController._tmpVecs[5];
  63104. var xaxis = BoneLookController._tmpVecs[6];
  63105. var yaxis = BoneLookController._tmpVecs[7];
  63106. var _tmpQuat = BoneLookController._tmpQuat;
  63107. target.subtractToRef(bonePos, zaxis);
  63108. zaxis.normalize();
  63109. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  63110. xaxis.normalize();
  63111. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  63112. yaxis.normalize();
  63113. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  63114. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  63115. return;
  63116. }
  63117. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  63118. return;
  63119. }
  63120. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  63121. return;
  63122. }
  63123. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  63124. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  63125. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  63126. }
  63127. if (this.slerpAmount < 1) {
  63128. if (!this._slerping) {
  63129. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  63130. }
  63131. if (this._transformYawPitch) {
  63132. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63133. }
  63134. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  63135. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  63136. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  63137. this._slerping = true;
  63138. }
  63139. else {
  63140. if (this._transformYawPitch) {
  63141. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63142. }
  63143. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  63144. this._slerping = false;
  63145. }
  63146. };
  63147. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  63148. var angDiff = ang2 - ang1;
  63149. angDiff %= Math.PI * 2;
  63150. if (angDiff > Math.PI) {
  63151. angDiff -= Math.PI * 2;
  63152. }
  63153. else if (angDiff < -Math.PI) {
  63154. angDiff += Math.PI * 2;
  63155. }
  63156. return angDiff;
  63157. };
  63158. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  63159. ang1 %= (2 * Math.PI);
  63160. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63161. ang2 %= (2 * Math.PI);
  63162. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63163. var ab = 0;
  63164. if (ang1 < ang2) {
  63165. ab = ang2 - ang1;
  63166. }
  63167. else {
  63168. ab = ang1 - ang2;
  63169. }
  63170. if (ab > Math.PI) {
  63171. ab = Math.PI * 2 - ab;
  63172. }
  63173. return ab;
  63174. };
  63175. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  63176. ang %= (2 * Math.PI);
  63177. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  63178. ang1 %= (2 * Math.PI);
  63179. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63180. ang2 %= (2 * Math.PI);
  63181. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63182. if (ang1 < ang2) {
  63183. if (ang > ang1 && ang < ang2) {
  63184. return true;
  63185. }
  63186. }
  63187. else {
  63188. if (ang > ang2 && ang < ang1) {
  63189. return true;
  63190. }
  63191. }
  63192. return false;
  63193. };
  63194. 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()];
  63195. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  63196. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63197. return BoneLookController;
  63198. }());
  63199. BABYLON.BoneLookController = BoneLookController;
  63200. })(BABYLON || (BABYLON = {}));
  63201. //# sourceMappingURL=babylon.boneLookController.js.map
  63202. var BABYLON;
  63203. (function (BABYLON) {
  63204. var Skeleton = /** @class */ (function () {
  63205. function Skeleton(name, id, scene) {
  63206. this.name = name;
  63207. this.id = id;
  63208. this.bones = new Array();
  63209. this.needInitialSkinMatrix = false;
  63210. this._isDirty = true;
  63211. this._meshesWithPoseMatrix = new Array();
  63212. this._identity = BABYLON.Matrix.Identity();
  63213. this._ranges = {};
  63214. this._lastAbsoluteTransformsUpdateId = -1;
  63215. // Events
  63216. /**
  63217. * An event triggered before computing the skeleton's matrices
  63218. * @type {BABYLON.Observable}
  63219. */
  63220. this.onBeforeComputeObservable = new BABYLON.Observable();
  63221. this.bones = [];
  63222. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63223. scene.skeletons.push(this);
  63224. //make sure it will recalculate the matrix next time prepare is called.
  63225. this._isDirty = true;
  63226. }
  63227. // Members
  63228. Skeleton.prototype.getTransformMatrices = function (mesh) {
  63229. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  63230. return mesh._bonesTransformMatrices;
  63231. }
  63232. if (!this._transformMatrices) {
  63233. this.prepare();
  63234. }
  63235. return this._transformMatrices;
  63236. };
  63237. Skeleton.prototype.getScene = function () {
  63238. return this._scene;
  63239. };
  63240. // Methods
  63241. /**
  63242. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  63243. */
  63244. Skeleton.prototype.toString = function (fullDetails) {
  63245. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  63246. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  63247. if (fullDetails) {
  63248. ret += ", Ranges: {";
  63249. var first = true;
  63250. for (var name_1 in this._ranges) {
  63251. if (first) {
  63252. ret += ", ";
  63253. first = false;
  63254. }
  63255. ret += name_1;
  63256. }
  63257. ret += "}";
  63258. }
  63259. return ret;
  63260. };
  63261. /**
  63262. * Get bone's index searching by name
  63263. * @param {string} name is bone's name to search for
  63264. * @return {number} Indice of the bone. Returns -1 if not found
  63265. */
  63266. Skeleton.prototype.getBoneIndexByName = function (name) {
  63267. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  63268. if (this.bones[boneIndex].name === name) {
  63269. return boneIndex;
  63270. }
  63271. }
  63272. return -1;
  63273. };
  63274. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  63275. // check name not already in use
  63276. if (!this._ranges[name]) {
  63277. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  63278. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63279. if (this.bones[i].animations[0]) {
  63280. this.bones[i].animations[0].createRange(name, from, to);
  63281. }
  63282. }
  63283. }
  63284. };
  63285. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  63286. if (deleteFrames === void 0) { deleteFrames = true; }
  63287. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63288. if (this.bones[i].animations[0]) {
  63289. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  63290. }
  63291. }
  63292. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  63293. };
  63294. Skeleton.prototype.getAnimationRange = function (name) {
  63295. return this._ranges[name];
  63296. };
  63297. /**
  63298. * Returns as an Array, all AnimationRanges defined on this skeleton
  63299. */
  63300. Skeleton.prototype.getAnimationRanges = function () {
  63301. var animationRanges = [];
  63302. var name;
  63303. var i = 0;
  63304. for (name in this._ranges) {
  63305. animationRanges[i] = this._ranges[name];
  63306. i++;
  63307. }
  63308. return animationRanges;
  63309. };
  63310. /**
  63311. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  63312. */
  63313. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  63314. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63315. if (this._ranges[name] || !source.getAnimationRange(name)) {
  63316. return false;
  63317. }
  63318. var ret = true;
  63319. var frameOffset = this._getHighestAnimationFrame() + 1;
  63320. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  63321. var boneDict = {};
  63322. var sourceBones = source.bones;
  63323. var nBones;
  63324. var i;
  63325. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  63326. boneDict[sourceBones[i].name] = sourceBones[i];
  63327. }
  63328. if (this.bones.length !== sourceBones.length) {
  63329. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  63330. ret = false;
  63331. }
  63332. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  63333. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  63334. var boneName = this.bones[i].name;
  63335. var sourceBone = boneDict[boneName];
  63336. if (sourceBone) {
  63337. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  63338. }
  63339. else {
  63340. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  63341. ret = false;
  63342. }
  63343. }
  63344. // do not call createAnimationRange(), since it also is done to bones, which was already done
  63345. var range = source.getAnimationRange(name);
  63346. if (range) {
  63347. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  63348. }
  63349. return ret;
  63350. };
  63351. Skeleton.prototype.returnToRest = function () {
  63352. for (var index = 0; index < this.bones.length; index++) {
  63353. this.bones[index].returnToRest();
  63354. }
  63355. };
  63356. Skeleton.prototype._getHighestAnimationFrame = function () {
  63357. var ret = 0;
  63358. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  63359. if (this.bones[i].animations[0]) {
  63360. var highest = this.bones[i].animations[0].getHighestFrame();
  63361. if (ret < highest) {
  63362. ret = highest;
  63363. }
  63364. }
  63365. }
  63366. return ret;
  63367. };
  63368. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  63369. var range = this.getAnimationRange(name);
  63370. if (!range) {
  63371. return null;
  63372. }
  63373. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  63374. };
  63375. Skeleton.prototype._markAsDirty = function () {
  63376. this._isDirty = true;
  63377. };
  63378. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  63379. this._meshesWithPoseMatrix.push(mesh);
  63380. };
  63381. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  63382. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  63383. if (index > -1) {
  63384. this._meshesWithPoseMatrix.splice(index, 1);
  63385. }
  63386. };
  63387. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  63388. this.onBeforeComputeObservable.notifyObservers(this);
  63389. for (var index = 0; index < this.bones.length; index++) {
  63390. var bone = this.bones[index];
  63391. var parentBone = bone.getParent();
  63392. if (parentBone) {
  63393. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  63394. }
  63395. else {
  63396. if (initialSkinMatrix) {
  63397. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  63398. }
  63399. else {
  63400. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  63401. }
  63402. }
  63403. if (bone._index !== -1) {
  63404. var mappedIndex = bone._index === null ? index : bone._index;
  63405. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  63406. }
  63407. }
  63408. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  63409. };
  63410. Skeleton.prototype.prepare = function () {
  63411. if (!this._isDirty) {
  63412. return;
  63413. }
  63414. if (this.needInitialSkinMatrix) {
  63415. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  63416. var mesh = this._meshesWithPoseMatrix[index];
  63417. var poseMatrix = mesh.getPoseMatrix();
  63418. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  63419. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63420. }
  63421. if (this._synchronizedWithMesh !== mesh) {
  63422. this._synchronizedWithMesh = mesh;
  63423. // Prepare bones
  63424. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  63425. var bone = this.bones[boneIndex];
  63426. if (!bone.getParent()) {
  63427. var matrix = bone.getBaseMatrix();
  63428. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  63429. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  63430. }
  63431. }
  63432. }
  63433. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  63434. }
  63435. }
  63436. else {
  63437. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  63438. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  63439. }
  63440. this._computeTransformMatrices(this._transformMatrices, null);
  63441. }
  63442. this._isDirty = false;
  63443. this._scene._activeBones.addCount(this.bones.length, false);
  63444. };
  63445. Skeleton.prototype.getAnimatables = function () {
  63446. if (!this._animatables || this._animatables.length !== this.bones.length) {
  63447. this._animatables = [];
  63448. for (var index = 0; index < this.bones.length; index++) {
  63449. this._animatables.push(this.bones[index]);
  63450. }
  63451. }
  63452. return this._animatables;
  63453. };
  63454. Skeleton.prototype.clone = function (name, id) {
  63455. var result = new Skeleton(name, id || name, this._scene);
  63456. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63457. for (var index = 0; index < this.bones.length; index++) {
  63458. var source = this.bones[index];
  63459. var parentBone = null;
  63460. var parent_1 = source.getParent();
  63461. if (parent_1) {
  63462. var parentIndex = this.bones.indexOf(parent_1);
  63463. parentBone = result.bones[parentIndex];
  63464. }
  63465. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  63466. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  63467. }
  63468. if (this._ranges) {
  63469. result._ranges = {};
  63470. for (var rangeName in this._ranges) {
  63471. var range = this._ranges[rangeName];
  63472. if (range) {
  63473. result._ranges[rangeName] = range.clone();
  63474. }
  63475. }
  63476. }
  63477. this._isDirty = true;
  63478. return result;
  63479. };
  63480. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  63481. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  63482. this.bones.forEach(function (bone) {
  63483. bone.animations.forEach(function (animation) {
  63484. animation.enableBlending = true;
  63485. animation.blendingSpeed = blendingSpeed;
  63486. });
  63487. });
  63488. };
  63489. Skeleton.prototype.dispose = function () {
  63490. this._meshesWithPoseMatrix = [];
  63491. // Animations
  63492. this.getScene().stopAnimation(this);
  63493. // Remove from scene
  63494. this.getScene().removeSkeleton(this);
  63495. };
  63496. Skeleton.prototype.serialize = function () {
  63497. var serializationObject = {};
  63498. serializationObject.name = this.name;
  63499. serializationObject.id = this.id;
  63500. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  63501. serializationObject.bones = [];
  63502. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  63503. for (var index = 0; index < this.bones.length; index++) {
  63504. var bone = this.bones[index];
  63505. var parent_2 = bone.getParent();
  63506. var serializedBone = {
  63507. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  63508. name: bone.name,
  63509. matrix: bone.getBaseMatrix().toArray(),
  63510. rest: bone.getRestPose().toArray()
  63511. };
  63512. serializationObject.bones.push(serializedBone);
  63513. if (bone.length) {
  63514. serializedBone.length = bone.length;
  63515. }
  63516. if (bone.animations && bone.animations.length > 0) {
  63517. serializedBone.animation = bone.animations[0].serialize();
  63518. }
  63519. serializationObject.ranges = [];
  63520. for (var name in this._ranges) {
  63521. var source = this._ranges[name];
  63522. if (!source) {
  63523. continue;
  63524. }
  63525. var range = {};
  63526. range.name = name;
  63527. range.from = source.from;
  63528. range.to = source.to;
  63529. serializationObject.ranges.push(range);
  63530. }
  63531. }
  63532. return serializationObject;
  63533. };
  63534. Skeleton.Parse = function (parsedSkeleton, scene) {
  63535. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  63536. if (parsedSkeleton.dimensionsAtRest) {
  63537. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  63538. }
  63539. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  63540. var index;
  63541. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  63542. var parsedBone = parsedSkeleton.bones[index];
  63543. var parentBone = null;
  63544. if (parsedBone.parentBoneIndex > -1) {
  63545. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  63546. }
  63547. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  63548. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  63549. if (parsedBone.length) {
  63550. bone.length = parsedBone.length;
  63551. }
  63552. if (parsedBone.animation) {
  63553. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  63554. }
  63555. }
  63556. // placed after bones, so createAnimationRange can cascade down
  63557. if (parsedSkeleton.ranges) {
  63558. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  63559. var data = parsedSkeleton.ranges[index];
  63560. skeleton.createAnimationRange(data.name, data.from, data.to);
  63561. }
  63562. }
  63563. return skeleton;
  63564. };
  63565. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  63566. if (forceUpdate === void 0) { forceUpdate = false; }
  63567. var renderId = this._scene.getRenderId();
  63568. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  63569. this.bones[0].computeAbsoluteTransforms();
  63570. this._lastAbsoluteTransformsUpdateId = renderId;
  63571. }
  63572. };
  63573. Skeleton.prototype.getPoseMatrix = function () {
  63574. var poseMatrix = null;
  63575. if (this._meshesWithPoseMatrix.length > 0) {
  63576. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  63577. }
  63578. return poseMatrix;
  63579. };
  63580. Skeleton.prototype.sortBones = function () {
  63581. var bones = new Array();
  63582. var visited = new Array(this.bones.length);
  63583. for (var index = 0; index < this.bones.length; index++) {
  63584. this._sortBones(index, bones, visited);
  63585. }
  63586. this.bones = bones;
  63587. };
  63588. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63589. if (visited[index]) {
  63590. return;
  63591. }
  63592. visited[index] = true;
  63593. var bone = this.bones[index];
  63594. if (bone._index === undefined) {
  63595. bone._index = index;
  63596. }
  63597. var parentBone = bone.getParent();
  63598. if (parentBone) {
  63599. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63600. }
  63601. bones.push(bone);
  63602. };
  63603. return Skeleton;
  63604. }());
  63605. BABYLON.Skeleton = Skeleton;
  63606. })(BABYLON || (BABYLON = {}));
  63607. //# sourceMappingURL=babylon.skeleton.js.map
  63608. var BABYLON;
  63609. (function (BABYLON) {
  63610. var SphericalPolynomial = /** @class */ (function () {
  63611. function SphericalPolynomial() {
  63612. this.x = BABYLON.Vector3.Zero();
  63613. this.y = BABYLON.Vector3.Zero();
  63614. this.z = BABYLON.Vector3.Zero();
  63615. this.xx = BABYLON.Vector3.Zero();
  63616. this.yy = BABYLON.Vector3.Zero();
  63617. this.zz = BABYLON.Vector3.Zero();
  63618. this.xy = BABYLON.Vector3.Zero();
  63619. this.yz = BABYLON.Vector3.Zero();
  63620. this.zx = BABYLON.Vector3.Zero();
  63621. }
  63622. SphericalPolynomial.prototype.addAmbient = function (color) {
  63623. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63624. this.xx = this.xx.add(colorVector);
  63625. this.yy = this.yy.add(colorVector);
  63626. this.zz = this.zz.add(colorVector);
  63627. };
  63628. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63629. var result = new SphericalPolynomial();
  63630. result.x = harmonics.L11.scale(1.02333);
  63631. result.y = harmonics.L1_1.scale(1.02333);
  63632. result.z = harmonics.L10.scale(1.02333);
  63633. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63634. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63635. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63636. result.yz = harmonics.L2_1.scale(0.858086);
  63637. result.zx = harmonics.L21.scale(0.858086);
  63638. result.xy = harmonics.L2_2.scale(0.858086);
  63639. result.scale(1.0 / Math.PI);
  63640. return result;
  63641. };
  63642. SphericalPolynomial.prototype.scale = function (scale) {
  63643. this.x = this.x.scale(scale);
  63644. this.y = this.y.scale(scale);
  63645. this.z = this.z.scale(scale);
  63646. this.xx = this.xx.scale(scale);
  63647. this.yy = this.yy.scale(scale);
  63648. this.zz = this.zz.scale(scale);
  63649. this.yz = this.yz.scale(scale);
  63650. this.zx = this.zx.scale(scale);
  63651. this.xy = this.xy.scale(scale);
  63652. };
  63653. return SphericalPolynomial;
  63654. }());
  63655. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63656. var SphericalHarmonics = /** @class */ (function () {
  63657. function SphericalHarmonics() {
  63658. this.L00 = BABYLON.Vector3.Zero();
  63659. this.L1_1 = BABYLON.Vector3.Zero();
  63660. this.L10 = BABYLON.Vector3.Zero();
  63661. this.L11 = BABYLON.Vector3.Zero();
  63662. this.L2_2 = BABYLON.Vector3.Zero();
  63663. this.L2_1 = BABYLON.Vector3.Zero();
  63664. this.L20 = BABYLON.Vector3.Zero();
  63665. this.L21 = BABYLON.Vector3.Zero();
  63666. this.L22 = BABYLON.Vector3.Zero();
  63667. }
  63668. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63669. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63670. var c = colorVector.scale(deltaSolidAngle);
  63671. this.L00 = this.L00.add(c.scale(0.282095));
  63672. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63673. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63674. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63675. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63676. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63677. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63678. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63679. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63680. };
  63681. SphericalHarmonics.prototype.scale = function (scale) {
  63682. this.L00 = this.L00.scale(scale);
  63683. this.L1_1 = this.L1_1.scale(scale);
  63684. this.L10 = this.L10.scale(scale);
  63685. this.L11 = this.L11.scale(scale);
  63686. this.L2_2 = this.L2_2.scale(scale);
  63687. this.L2_1 = this.L2_1.scale(scale);
  63688. this.L20 = this.L20.scale(scale);
  63689. this.L21 = this.L21.scale(scale);
  63690. this.L22 = this.L22.scale(scale);
  63691. };
  63692. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63693. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63694. //
  63695. // E_lm = A_l * L_lm
  63696. //
  63697. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63698. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63699. // the scaling factors are given in equation 9.
  63700. // Constant (Band 0)
  63701. this.L00 = this.L00.scale(3.141593);
  63702. // Linear (Band 1)
  63703. this.L1_1 = this.L1_1.scale(2.094395);
  63704. this.L10 = this.L10.scale(2.094395);
  63705. this.L11 = this.L11.scale(2.094395);
  63706. // Quadratic (Band 2)
  63707. this.L2_2 = this.L2_2.scale(0.785398);
  63708. this.L2_1 = this.L2_1.scale(0.785398);
  63709. this.L20 = this.L20.scale(0.785398);
  63710. this.L21 = this.L21.scale(0.785398);
  63711. this.L22 = this.L22.scale(0.785398);
  63712. };
  63713. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63714. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63715. // L = (1/pi) * E * rho
  63716. //
  63717. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63718. this.scale(1.0 / Math.PI);
  63719. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63720. // (The pixel shader must apply albedo after texture fetches, etc).
  63721. };
  63722. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63723. var result = new SphericalHarmonics();
  63724. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63725. result.L1_1 = polynomial.y.scale(0.977204);
  63726. result.L10 = polynomial.z.scale(0.977204);
  63727. result.L11 = polynomial.x.scale(0.977204);
  63728. result.L2_2 = polynomial.xy.scale(1.16538);
  63729. result.L2_1 = polynomial.yz.scale(1.16538);
  63730. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63731. result.L21 = polynomial.zx.scale(1.16538);
  63732. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63733. result.scale(Math.PI);
  63734. return result;
  63735. };
  63736. return SphericalHarmonics;
  63737. }());
  63738. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63739. })(BABYLON || (BABYLON = {}));
  63740. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63741. var BABYLON;
  63742. (function (BABYLON) {
  63743. var Internals;
  63744. (function (Internals) {
  63745. var FileFaceOrientation = /** @class */ (function () {
  63746. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63747. this.name = name;
  63748. this.worldAxisForNormal = worldAxisForNormal;
  63749. this.worldAxisForFileX = worldAxisForFileX;
  63750. this.worldAxisForFileY = worldAxisForFileY;
  63751. }
  63752. return FileFaceOrientation;
  63753. }());
  63754. ;
  63755. /**
  63756. * Helper class dealing with the extraction of spherical polynomial dataArray
  63757. * from a cube map.
  63758. */
  63759. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63760. function CubeMapToSphericalPolynomialTools() {
  63761. }
  63762. /**
  63763. * Converts a texture to the according Spherical Polynomial data.
  63764. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63765. *
  63766. * @param texture The texture to extract the information from.
  63767. * @return The Spherical Polynomial data.
  63768. */
  63769. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63770. if (!texture.isCube) {
  63771. // Only supports cube Textures currently.
  63772. return null;
  63773. }
  63774. var size = texture.getSize().width;
  63775. var right = texture.readPixels(0);
  63776. var left = texture.readPixels(1);
  63777. var up;
  63778. var down;
  63779. if (texture.isRenderTarget) {
  63780. up = texture.readPixels(3);
  63781. down = texture.readPixels(2);
  63782. }
  63783. else {
  63784. up = texture.readPixels(2);
  63785. down = texture.readPixels(3);
  63786. }
  63787. var front = texture.readPixels(4);
  63788. var back = texture.readPixels(5);
  63789. var gammaSpace = texture.gammaSpace;
  63790. // Always read as RGBA.
  63791. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63792. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63793. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63794. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63795. }
  63796. var cubeInfo = {
  63797. size: size,
  63798. right: right,
  63799. left: left,
  63800. up: up,
  63801. down: down,
  63802. front: front,
  63803. back: back,
  63804. format: format,
  63805. type: type,
  63806. gammaSpace: gammaSpace,
  63807. };
  63808. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63809. };
  63810. /**
  63811. * Converts a cubemap to the according Spherical Polynomial data.
  63812. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63813. *
  63814. * @param cubeInfo The Cube map to extract the information from.
  63815. * @return The Spherical Polynomial data.
  63816. */
  63817. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63818. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63819. var totalSolidAngle = 0.0;
  63820. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63821. var du = 2.0 / cubeInfo.size;
  63822. var dv = du;
  63823. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63824. var minUV = du * 0.5 - 1.0;
  63825. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63826. var fileFace = this.FileFaces[faceIndex];
  63827. var dataArray = cubeInfo[fileFace.name];
  63828. var v = minUV;
  63829. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63830. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63831. // Because SP is still linear, so summation is fine in that basis.
  63832. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63833. for (var y = 0; y < cubeInfo.size; y++) {
  63834. var u = minUV;
  63835. for (var x = 0; x < cubeInfo.size; x++) {
  63836. // World direction (not normalised)
  63837. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63838. worldDirection.normalize();
  63839. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63840. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63841. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63842. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63843. // Handle Integer types.
  63844. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63845. r /= 255;
  63846. g /= 255;
  63847. b /= 255;
  63848. }
  63849. // Handle Gamma space textures.
  63850. if (cubeInfo.gammaSpace) {
  63851. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63852. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63853. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63854. }
  63855. var color = new BABYLON.Color3(r, g, b);
  63856. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63857. totalSolidAngle += deltaSolidAngle;
  63858. u += du;
  63859. }
  63860. v += dv;
  63861. }
  63862. }
  63863. // Solid angle for entire sphere is 4*pi
  63864. var sphereSolidAngle = 4.0 * Math.PI;
  63865. // Adjust the solid angle to allow for how many faces we processed.
  63866. var facesProcessed = 6.0;
  63867. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63868. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63869. // This is needed because the numerical integration over the cube uses a
  63870. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63871. // and also to compensate for accumulative error due to float precision in the summation.
  63872. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63873. sphericalHarmonics.scale(correctionFactor);
  63874. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63875. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63876. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63877. };
  63878. CubeMapToSphericalPolynomialTools.FileFaces = [
  63879. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63880. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63881. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63882. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63883. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63884. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63885. ];
  63886. return CubeMapToSphericalPolynomialTools;
  63887. }());
  63888. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63889. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63890. })(BABYLON || (BABYLON = {}));
  63891. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63892. var BABYLON;
  63893. (function (BABYLON) {
  63894. var Internals;
  63895. (function (Internals) {
  63896. /**
  63897. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63898. */
  63899. var PanoramaToCubeMapTools = /** @class */ (function () {
  63900. function PanoramaToCubeMapTools() {
  63901. }
  63902. /**
  63903. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63904. *
  63905. * @param float32Array The source data.
  63906. * @param inputWidth The width of the input panorama.
  63907. * @param inputhHeight The height of the input panorama.
  63908. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63909. * @return The cubemap data
  63910. */
  63911. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63912. if (!float32Array) {
  63913. throw "ConvertPanoramaToCubemap: input cannot be null";
  63914. }
  63915. if (float32Array.length != inputWidth * inputHeight * 3) {
  63916. throw "ConvertPanoramaToCubemap: input size is wrong";
  63917. }
  63918. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63919. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63920. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63921. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63922. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63923. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63924. return {
  63925. front: textureFront,
  63926. back: textureBack,
  63927. left: textureLeft,
  63928. right: textureRight,
  63929. up: textureUp,
  63930. down: textureDown,
  63931. size: size,
  63932. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63933. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63934. gammaSpace: false,
  63935. };
  63936. };
  63937. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63938. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63939. var textureArray = new Float32Array(buffer);
  63940. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63941. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63942. var dy = 1 / texSize;
  63943. var fy = 0;
  63944. for (var y = 0; y < texSize; y++) {
  63945. var xv1 = faceData[0];
  63946. var xv2 = faceData[2];
  63947. for (var x = 0; x < texSize; x++) {
  63948. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63949. v.normalize();
  63950. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63951. // 3 channels per pixels
  63952. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63953. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63954. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63955. xv1 = xv1.add(rotDX1);
  63956. xv2 = xv2.add(rotDX2);
  63957. }
  63958. fy += dy;
  63959. }
  63960. return textureArray;
  63961. };
  63962. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63963. var theta = Math.atan2(vDir.z, vDir.x);
  63964. var phi = Math.acos(vDir.y);
  63965. while (theta < -Math.PI)
  63966. theta += 2 * Math.PI;
  63967. while (theta > Math.PI)
  63968. theta -= 2 * Math.PI;
  63969. var dx = theta / Math.PI;
  63970. var dy = phi / Math.PI;
  63971. // recenter.
  63972. dx = dx * 0.5 + 0.5;
  63973. var px = Math.round(dx * inputWidth);
  63974. if (px < 0)
  63975. px = 0;
  63976. else if (px >= inputWidth)
  63977. px = inputWidth - 1;
  63978. var py = Math.round(dy * inputHeight);
  63979. if (py < 0)
  63980. py = 0;
  63981. else if (py >= inputHeight)
  63982. py = inputHeight - 1;
  63983. var inputY = (inputHeight - py - 1);
  63984. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63985. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63986. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63987. return {
  63988. r: r,
  63989. g: g,
  63990. b: b
  63991. };
  63992. };
  63993. PanoramaToCubeMapTools.FACE_FRONT = [
  63994. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63995. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63996. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63997. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63998. ];
  63999. PanoramaToCubeMapTools.FACE_BACK = [
  64000. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64001. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64002. new BABYLON.Vector3(1.0, 1.0, 1.0),
  64003. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  64004. ];
  64005. PanoramaToCubeMapTools.FACE_RIGHT = [
  64006. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64007. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64008. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64009. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64010. ];
  64011. PanoramaToCubeMapTools.FACE_LEFT = [
  64012. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64013. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64014. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64015. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  64016. ];
  64017. PanoramaToCubeMapTools.FACE_DOWN = [
  64018. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64019. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64020. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64021. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64022. ];
  64023. PanoramaToCubeMapTools.FACE_UP = [
  64024. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64025. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64026. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64027. new BABYLON.Vector3(1.0, -1.0, -1.0)
  64028. ];
  64029. return PanoramaToCubeMapTools;
  64030. }());
  64031. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  64032. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64033. })(BABYLON || (BABYLON = {}));
  64034. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  64035. var BABYLON;
  64036. (function (BABYLON) {
  64037. var Internals;
  64038. (function (Internals) {
  64039. ;
  64040. /**
  64041. * This groups tools to convert HDR texture to native colors array.
  64042. */
  64043. var HDRTools = /** @class */ (function () {
  64044. function HDRTools() {
  64045. }
  64046. HDRTools.Ldexp = function (mantissa, exponent) {
  64047. if (exponent > 1023) {
  64048. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  64049. }
  64050. if (exponent < -1074) {
  64051. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  64052. }
  64053. return mantissa * Math.pow(2, exponent);
  64054. };
  64055. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  64056. if (exponent > 0) {
  64057. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  64058. float32array[index + 0] = red * exponent;
  64059. float32array[index + 1] = green * exponent;
  64060. float32array[index + 2] = blue * exponent;
  64061. }
  64062. else {
  64063. float32array[index + 0] = 0;
  64064. float32array[index + 1] = 0;
  64065. float32array[index + 2] = 0;
  64066. }
  64067. };
  64068. HDRTools.readStringLine = function (uint8array, startIndex) {
  64069. var line = "";
  64070. var character = "";
  64071. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  64072. character = String.fromCharCode(uint8array[i]);
  64073. if (character == "\n") {
  64074. break;
  64075. }
  64076. line += character;
  64077. }
  64078. return line;
  64079. };
  64080. /**
  64081. * Reads header information from an RGBE texture stored in a native array.
  64082. * More information on this format are available here:
  64083. * https://en.wikipedia.org/wiki/RGBE_image_format
  64084. *
  64085. * @param uint8array The binary file stored in native array.
  64086. * @return The header information.
  64087. */
  64088. HDRTools.RGBE_ReadHeader = function (uint8array) {
  64089. var height = 0;
  64090. var width = 0;
  64091. var line = this.readStringLine(uint8array, 0);
  64092. if (line[0] != '#' || line[1] != '?') {
  64093. throw "Bad HDR Format.";
  64094. }
  64095. var endOfHeader = false;
  64096. var findFormat = false;
  64097. var lineIndex = 0;
  64098. do {
  64099. lineIndex += (line.length + 1);
  64100. line = this.readStringLine(uint8array, lineIndex);
  64101. if (line == "FORMAT=32-bit_rle_rgbe") {
  64102. findFormat = true;
  64103. }
  64104. else if (line.length == 0) {
  64105. endOfHeader = true;
  64106. }
  64107. } while (!endOfHeader);
  64108. if (!findFormat) {
  64109. throw "HDR Bad header format, unsupported FORMAT";
  64110. }
  64111. lineIndex += (line.length + 1);
  64112. line = this.readStringLine(uint8array, lineIndex);
  64113. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  64114. var match = sizeRegexp.exec(line);
  64115. // TODO. Support +Y and -X if needed.
  64116. if (!match || match.length < 3) {
  64117. throw "HDR Bad header format, no size";
  64118. }
  64119. width = parseInt(match[2]);
  64120. height = parseInt(match[1]);
  64121. if (width < 8 || width > 0x7fff) {
  64122. throw "HDR Bad header format, unsupported size";
  64123. }
  64124. lineIndex += (line.length + 1);
  64125. return {
  64126. height: height,
  64127. width: width,
  64128. dataPosition: lineIndex
  64129. };
  64130. };
  64131. /**
  64132. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  64133. * This RGBE texture needs to store the information as a panorama.
  64134. *
  64135. * More information on this format are available here:
  64136. * https://en.wikipedia.org/wiki/RGBE_image_format
  64137. *
  64138. * @param buffer The binary file stored in an array buffer.
  64139. * @param size The expected size of the extracted cubemap.
  64140. * @return The Cube Map information.
  64141. */
  64142. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  64143. var uint8array = new Uint8Array(buffer);
  64144. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  64145. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64146. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  64147. return cubeMapData;
  64148. };
  64149. /**
  64150. * Returns the pixels data extracted from an RGBE texture.
  64151. * This pixels will be stored left to right up to down in the R G B order in one array.
  64152. *
  64153. * More information on this format are available here:
  64154. * https://en.wikipedia.org/wiki/RGBE_image_format
  64155. *
  64156. * @param uint8array The binary file stored in an array buffer.
  64157. * @param hdrInfo The header information of the file.
  64158. * @return The pixels data in RGB right to left up to down order.
  64159. */
  64160. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  64161. // Keep for multi format supports.
  64162. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64163. };
  64164. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  64165. var num_scanlines = hdrInfo.height;
  64166. var scanline_width = hdrInfo.width;
  64167. var a, b, c, d, count;
  64168. var dataIndex = hdrInfo.dataPosition;
  64169. var index = 0, endIndex = 0, i = 0;
  64170. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  64171. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  64172. // 3 channels of 4 bytes per pixel in float.
  64173. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  64174. var resultArray = new Float32Array(resultBuffer);
  64175. // read in each successive scanline
  64176. while (num_scanlines > 0) {
  64177. a = uint8array[dataIndex++];
  64178. b = uint8array[dataIndex++];
  64179. c = uint8array[dataIndex++];
  64180. d = uint8array[dataIndex++];
  64181. if (a != 2 || b != 2 || (c & 0x80)) {
  64182. // this file is not run length encoded
  64183. throw "HDR Bad header format, not RLE";
  64184. }
  64185. if (((c << 8) | d) != scanline_width) {
  64186. throw "HDR Bad header format, wrong scan line width";
  64187. }
  64188. index = 0;
  64189. // read each of the four channels for the scanline into the buffer
  64190. for (i = 0; i < 4; i++) {
  64191. endIndex = (i + 1) * scanline_width;
  64192. while (index < endIndex) {
  64193. a = uint8array[dataIndex++];
  64194. b = uint8array[dataIndex++];
  64195. if (a > 128) {
  64196. // a run of the same value
  64197. count = a - 128;
  64198. if ((count == 0) || (count > endIndex - index)) {
  64199. throw "HDR Bad Format, bad scanline data (run)";
  64200. }
  64201. while (count-- > 0) {
  64202. scanLineArray[index++] = b;
  64203. }
  64204. }
  64205. else {
  64206. // a non-run
  64207. count = a;
  64208. if ((count == 0) || (count > endIndex - index)) {
  64209. throw "HDR Bad Format, bad scanline data (non-run)";
  64210. }
  64211. scanLineArray[index++] = b;
  64212. if (--count > 0) {
  64213. for (var j = 0; j < count; j++) {
  64214. scanLineArray[index++] = uint8array[dataIndex++];
  64215. }
  64216. }
  64217. }
  64218. }
  64219. }
  64220. // now convert data from buffer into floats
  64221. for (i = 0; i < scanline_width; i++) {
  64222. a = scanLineArray[i];
  64223. b = scanLineArray[i + scanline_width];
  64224. c = scanLineArray[i + 2 * scanline_width];
  64225. d = scanLineArray[i + 3 * scanline_width];
  64226. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  64227. }
  64228. num_scanlines--;
  64229. }
  64230. return resultArray;
  64231. };
  64232. return HDRTools;
  64233. }());
  64234. Internals.HDRTools = HDRTools;
  64235. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64236. })(BABYLON || (BABYLON = {}));
  64237. //# sourceMappingURL=babylon.hdr.js.map
  64238. var BABYLON;
  64239. (function (BABYLON) {
  64240. /**
  64241. * This represents a texture coming from an HDR input.
  64242. *
  64243. * The only supported format is currently panorama picture stored in RGBE format.
  64244. * Example of such files can be found on HDRLib: http://hdrlib.com/
  64245. */
  64246. var HDRCubeTexture = /** @class */ (function (_super) {
  64247. __extends(HDRCubeTexture, _super);
  64248. /**
  64249. * Instantiates an HDRTexture from the following parameters.
  64250. *
  64251. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  64252. * @param scene The scene the texture will be used in
  64253. * @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.
  64254. * @param noMipmap Forces to not generate the mipmap if true
  64255. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  64256. * @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)
  64257. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  64258. */
  64259. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  64260. if (noMipmap === void 0) { noMipmap = false; }
  64261. if (generateHarmonics === void 0) { generateHarmonics = true; }
  64262. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  64263. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  64264. if (onLoad === void 0) { onLoad = null; }
  64265. if (onError === void 0) { onError = null; }
  64266. var _this = _super.call(this, scene) || this;
  64267. _this._useInGammaSpace = false;
  64268. _this._generateHarmonics = true;
  64269. _this._isBABYLONPreprocessed = false;
  64270. _this._onLoad = null;
  64271. _this._onError = null;
  64272. /**
  64273. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  64274. */
  64275. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64276. /**
  64277. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  64278. * This is usefull at run time to apply the good shader.
  64279. */
  64280. _this.isPMREM = false;
  64281. _this._isBlocking = true;
  64282. if (!url) {
  64283. return _this;
  64284. }
  64285. _this.name = url;
  64286. _this.url = url;
  64287. _this.hasAlpha = false;
  64288. _this.isCube = true;
  64289. _this._textureMatrix = BABYLON.Matrix.Identity();
  64290. _this._onLoad = onLoad;
  64291. _this._onError = onError;
  64292. _this.gammaSpace = false;
  64293. var caps = scene.getEngine().getCaps();
  64294. if (size) {
  64295. _this._isBABYLONPreprocessed = false;
  64296. _this._noMipmap = noMipmap;
  64297. _this._size = size;
  64298. _this._useInGammaSpace = useInGammaSpace;
  64299. _this._usePMREMGenerator = usePMREMGenerator &&
  64300. caps.textureLOD &&
  64301. caps.textureFloat &&
  64302. !_this._useInGammaSpace;
  64303. }
  64304. else {
  64305. _this._isBABYLONPreprocessed = true;
  64306. _this._noMipmap = false;
  64307. _this._useInGammaSpace = false;
  64308. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  64309. !_this._useInGammaSpace;
  64310. }
  64311. _this.isPMREM = _this._usePMREMGenerator;
  64312. _this._texture = _this._getFromCache(url, _this._noMipmap);
  64313. if (!_this._texture) {
  64314. if (!scene.useDelayedTextureLoading) {
  64315. _this.loadTexture();
  64316. }
  64317. else {
  64318. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64319. }
  64320. }
  64321. return _this;
  64322. }
  64323. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  64324. /**
  64325. * Gets wether or not the texture is blocking during loading.
  64326. */
  64327. get: function () {
  64328. return this._isBlocking;
  64329. },
  64330. /**
  64331. * Sets wether or not the texture is blocking during loading.
  64332. */
  64333. set: function (value) {
  64334. this._isBlocking = value;
  64335. },
  64336. enumerable: true,
  64337. configurable: true
  64338. });
  64339. /**
  64340. * Occurs when the file is a preprocessed .babylon.hdr file.
  64341. */
  64342. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  64343. var _this = this;
  64344. var mipLevels = 0;
  64345. var floatArrayView = null;
  64346. var scene = this.getScene();
  64347. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  64348. var mips = new Array();
  64349. if (!floatArrayView) {
  64350. return mips;
  64351. }
  64352. var startIndex = 30;
  64353. for (var level = 0; level < mipLevels; level++) {
  64354. mips.push([]);
  64355. // Fill each pixel of the mip level.
  64356. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  64357. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64358. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  64359. mips[level].push(faceData);
  64360. startIndex += faceSize;
  64361. }
  64362. }
  64363. return mips;
  64364. } : null;
  64365. var callback = function (buffer) {
  64366. var scene = _this.getScene();
  64367. if (!scene) {
  64368. return null;
  64369. }
  64370. // Create Native Array Views
  64371. var intArrayView = new Int32Array(buffer);
  64372. floatArrayView = new Float32Array(buffer);
  64373. // Fill header.
  64374. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  64375. _this._size = intArrayView[1]; // CubeMap max mip face size.
  64376. // Update Texture Information.
  64377. if (!_this._texture) {
  64378. return null;
  64379. }
  64380. _this._texture.updateSize(_this._size, _this._size);
  64381. // Fill polynomial information.
  64382. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  64383. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  64384. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  64385. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  64386. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  64387. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  64388. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  64389. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  64390. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  64391. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  64392. _this.sphericalPolynomial = sphericalPolynomial;
  64393. // Fill pixel data.
  64394. mipLevels = intArrayView[29]; // Number of mip levels.
  64395. var startIndex = 30;
  64396. var data = [];
  64397. var faceSize = Math.pow(_this._size, 2) * 3;
  64398. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64399. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  64400. startIndex += faceSize;
  64401. }
  64402. var results = [];
  64403. var byteArray = null;
  64404. // Push each faces.
  64405. for (var k = 0; k < 6; k++) {
  64406. var dataFace = null;
  64407. // To be deprecated.
  64408. if (version === 1) {
  64409. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  64410. dataFace = data[j];
  64411. }
  64412. // If special cases.
  64413. if (!mipmapGenerator && dataFace) {
  64414. if (!scene.getEngine().getCaps().textureFloat) {
  64415. // 3 channels of 1 bytes per pixel in bytes.
  64416. var byteBuffer = new ArrayBuffer(faceSize);
  64417. byteArray = new Uint8Array(byteBuffer);
  64418. }
  64419. for (var i = 0; i < _this._size * _this._size; i++) {
  64420. // Put in gamma space if requested.
  64421. if (_this._useInGammaSpace) {
  64422. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64423. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64424. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64425. }
  64426. // Convert to int texture for fallback.
  64427. if (byteArray) {
  64428. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64429. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64430. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64431. // May use luminance instead if the result is not accurate.
  64432. var max = Math.max(Math.max(r, g), b);
  64433. if (max > 255) {
  64434. var scale = 255 / max;
  64435. r *= scale;
  64436. g *= scale;
  64437. b *= scale;
  64438. }
  64439. byteArray[(i * 3) + 0] = r;
  64440. byteArray[(i * 3) + 1] = g;
  64441. byteArray[(i * 3) + 2] = b;
  64442. }
  64443. }
  64444. }
  64445. // Fill the array accordingly.
  64446. if (byteArray) {
  64447. results.push(byteArray);
  64448. }
  64449. else {
  64450. results.push(dataFace);
  64451. }
  64452. }
  64453. return results;
  64454. };
  64455. if (scene) {
  64456. 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);
  64457. }
  64458. };
  64459. /**
  64460. * Occurs when the file is raw .hdr file.
  64461. */
  64462. HDRCubeTexture.prototype.loadHDRTexture = function () {
  64463. var _this = this;
  64464. var callback = function (buffer) {
  64465. var scene = _this.getScene();
  64466. if (!scene) {
  64467. return null;
  64468. }
  64469. // Extract the raw linear data.
  64470. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  64471. // Generate harmonics if needed.
  64472. if (_this._generateHarmonics) {
  64473. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  64474. _this.sphericalPolynomial = sphericalPolynomial;
  64475. }
  64476. var results = [];
  64477. var byteArray = null;
  64478. // Push each faces.
  64479. for (var j = 0; j < 6; j++) {
  64480. // Create uintarray fallback.
  64481. if (!scene.getEngine().getCaps().textureFloat) {
  64482. // 3 channels of 1 bytes per pixel in bytes.
  64483. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  64484. byteArray = new Uint8Array(byteBuffer);
  64485. }
  64486. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  64487. // If special cases.
  64488. if (_this._useInGammaSpace || byteArray) {
  64489. for (var i = 0; i < _this._size * _this._size; i++) {
  64490. // Put in gamma space if requested.
  64491. if (_this._useInGammaSpace) {
  64492. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  64493. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  64494. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  64495. }
  64496. // Convert to int texture for fallback.
  64497. if (byteArray) {
  64498. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  64499. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  64500. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  64501. // May use luminance instead if the result is not accurate.
  64502. var max = Math.max(Math.max(r, g), b);
  64503. if (max > 255) {
  64504. var scale = 255 / max;
  64505. r *= scale;
  64506. g *= scale;
  64507. b *= scale;
  64508. }
  64509. byteArray[(i * 3) + 0] = r;
  64510. byteArray[(i * 3) + 1] = g;
  64511. byteArray[(i * 3) + 2] = b;
  64512. }
  64513. }
  64514. }
  64515. if (byteArray) {
  64516. results.push(byteArray);
  64517. }
  64518. else {
  64519. results.push(dataFace);
  64520. }
  64521. }
  64522. return results;
  64523. };
  64524. var mipmapGenerator = null;
  64525. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  64526. // if (!this._noMipmap &&
  64527. // this._usePMREMGenerator) {
  64528. // mipmapGenerator = (data: ArrayBufferView[]) => {
  64529. // // Custom setup of the generator matching with the PBR shader values.
  64530. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  64531. // this._size,
  64532. // this._size,
  64533. // 0,
  64534. // 3,
  64535. // this.getScene().getEngine().getCaps().textureFloat,
  64536. // 2048,
  64537. // 0.25,
  64538. // false,
  64539. // true);
  64540. // return generator.filterCubeMap();
  64541. // };
  64542. // }
  64543. var scene = this.getScene();
  64544. if (scene) {
  64545. 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);
  64546. }
  64547. };
  64548. /**
  64549. * Starts the loading process of the texture.
  64550. */
  64551. HDRCubeTexture.prototype.loadTexture = function () {
  64552. if (this._isBABYLONPreprocessed) {
  64553. this.loadBabylonTexture();
  64554. }
  64555. else {
  64556. this.loadHDRTexture();
  64557. }
  64558. };
  64559. HDRCubeTexture.prototype.clone = function () {
  64560. var scene = this.getScene();
  64561. if (!scene) {
  64562. return this;
  64563. }
  64564. var size = (this._isBABYLONPreprocessed ? null : this._size);
  64565. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  64566. // Base texture
  64567. newTexture.level = this.level;
  64568. newTexture.wrapU = this.wrapU;
  64569. newTexture.wrapV = this.wrapV;
  64570. newTexture.coordinatesIndex = this.coordinatesIndex;
  64571. newTexture.coordinatesMode = this.coordinatesMode;
  64572. return newTexture;
  64573. };
  64574. // Methods
  64575. HDRCubeTexture.prototype.delayLoad = function () {
  64576. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64577. return;
  64578. }
  64579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64580. this._texture = this._getFromCache(this.url, this._noMipmap);
  64581. if (!this._texture) {
  64582. this.loadTexture();
  64583. }
  64584. };
  64585. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64586. return this._textureMatrix;
  64587. };
  64588. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64589. this._textureMatrix = value;
  64590. };
  64591. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64592. var texture = null;
  64593. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64594. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64595. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64596. texture.name = parsedTexture.name;
  64597. texture.hasAlpha = parsedTexture.hasAlpha;
  64598. texture.level = parsedTexture.level;
  64599. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64600. texture.isBlocking = parsedTexture.isBlocking;
  64601. }
  64602. return texture;
  64603. };
  64604. HDRCubeTexture.prototype.serialize = function () {
  64605. if (!this.name) {
  64606. return null;
  64607. }
  64608. var serializationObject = {};
  64609. serializationObject.name = this.name;
  64610. serializationObject.hasAlpha = this.hasAlpha;
  64611. serializationObject.isCube = true;
  64612. serializationObject.level = this.level;
  64613. serializationObject.size = this._size;
  64614. serializationObject.coordinatesMode = this.coordinatesMode;
  64615. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64616. serializationObject.generateHarmonics = this._generateHarmonics;
  64617. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64618. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64619. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64620. serializationObject.noMipmap = this._noMipmap;
  64621. serializationObject.isBlocking = this._isBlocking;
  64622. return serializationObject;
  64623. };
  64624. /**
  64625. * Saves as a file the data contained in the texture in a binary format.
  64626. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64627. * as the spherical used in the lighting.
  64628. * @param url The HDR file url.
  64629. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64630. * @param onError Method called if any error happens during download.
  64631. * @return The packed binary data.
  64632. */
  64633. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64634. if (onError === void 0) { onError = null; }
  64635. var callback = function (buffer) {
  64636. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64637. // Returns a URL you can use as a href.
  64638. var objUrl = window.URL.createObjectURL(data);
  64639. // Simulates a link to it and click to dowload.
  64640. var a = document.createElement("a");
  64641. document.body.appendChild(a);
  64642. a.style.display = "none";
  64643. a.href = objUrl;
  64644. a.download = "envmap.babylon.hdr";
  64645. a.click();
  64646. };
  64647. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64648. };
  64649. /**
  64650. * Serializes the data contained in the texture in a binary format.
  64651. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64652. * as the spherical used in the lighting.
  64653. * @param url The HDR file url.
  64654. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64655. * @param onError Method called if any error happens during download.
  64656. * @return The packed binary data.
  64657. */
  64658. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64659. if (onError === void 0) { onError = null; }
  64660. // Needs the url tho create the texture.
  64661. if (!url) {
  64662. return;
  64663. }
  64664. // Check Power of two size.
  64665. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64666. return;
  64667. }
  64668. // Coming Back in 3.x.
  64669. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  64670. };
  64671. HDRCubeTexture._facesMapping = [
  64672. "right",
  64673. "left",
  64674. "up",
  64675. "down",
  64676. "front",
  64677. "back"
  64678. ];
  64679. return HDRCubeTexture;
  64680. }(BABYLON.BaseTexture));
  64681. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64682. })(BABYLON || (BABYLON = {}));
  64683. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64684. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64685. // Huge respect for a such great lib.
  64686. // Earcut license:
  64687. // Copyright (c) 2016, Mapbox
  64688. //
  64689. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64690. // with or without fee is hereby granted, provided that the above copyright notice
  64691. // and this permission notice appear in all copies.
  64692. //
  64693. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64694. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64695. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64696. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64697. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64698. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64699. // THIS SOFTWARE.
  64700. var Earcut;
  64701. (function (Earcut) {
  64702. /**
  64703. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64704. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64705. * @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).
  64706. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64707. */
  64708. function earcut(data, holeIndices, dim) {
  64709. dim = dim || 2;
  64710. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64711. if (!outerNode)
  64712. return triangles;
  64713. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64714. if (hasHoles)
  64715. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64716. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64717. if (data.length > 80 * dim) {
  64718. minX = maxX = data[0];
  64719. minY = maxY = data[1];
  64720. for (var i = dim; i < outerLen; i += dim) {
  64721. x = data[i];
  64722. y = data[i + 1];
  64723. if (x < minX)
  64724. minX = x;
  64725. if (y < minY)
  64726. minY = y;
  64727. if (x > maxX)
  64728. maxX = x;
  64729. if (y > maxY)
  64730. maxY = y;
  64731. }
  64732. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64733. size = Math.max(maxX - minX, maxY - minY);
  64734. }
  64735. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64736. return triangles;
  64737. }
  64738. Earcut.earcut = earcut;
  64739. var Node = /** @class */ (function () {
  64740. function Node(i, x, y) {
  64741. this.i = i;
  64742. this.x = x;
  64743. this.y = y;
  64744. this.prev = null;
  64745. this.next = null;
  64746. this.z = null;
  64747. this.prevZ = null;
  64748. this.nextZ = null;
  64749. this.steiner = false;
  64750. }
  64751. return Node;
  64752. }());
  64753. // create a circular doubly linked list from polygon points in the specified winding order
  64754. function linkedList(data, start, end, dim, clockwise) {
  64755. var i, last = null;
  64756. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64757. for (i = start; i < end; i += dim)
  64758. last = insertNode(i, data[i], data[i + 1], last);
  64759. }
  64760. else {
  64761. for (i = end - dim; i >= start; i -= dim)
  64762. last = insertNode(i, data[i], data[i + 1], last);
  64763. }
  64764. if (last && equals(last, last.next)) {
  64765. removeNode(last);
  64766. last = last.next;
  64767. }
  64768. return last;
  64769. }
  64770. // eliminate colinear or duplicate points
  64771. function filterPoints(start, end) {
  64772. if (!start)
  64773. return start;
  64774. if (!end)
  64775. end = start;
  64776. var p = start, again;
  64777. do {
  64778. again = false;
  64779. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64780. removeNode(p);
  64781. p = end = p.prev;
  64782. if (p === p.next)
  64783. return undefined;
  64784. again = true;
  64785. }
  64786. else {
  64787. p = p.next;
  64788. }
  64789. } while (again || p !== end);
  64790. return end;
  64791. }
  64792. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64793. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64794. if (!ear)
  64795. return;
  64796. // interlink polygon nodes in z-order
  64797. if (!pass && size)
  64798. indexCurve(ear, minX, minY, size);
  64799. var stop = ear, prev, next;
  64800. // iterate through ears, slicing them one by one
  64801. while (ear.prev !== ear.next) {
  64802. prev = ear.prev;
  64803. next = ear.next;
  64804. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64805. // cut off the triangle
  64806. triangles.push(prev.i / dim);
  64807. triangles.push(ear.i / dim);
  64808. triangles.push(next.i / dim);
  64809. removeNode(ear);
  64810. // skipping the next vertice leads to less sliver triangles
  64811. ear = next.next;
  64812. stop = next.next;
  64813. continue;
  64814. }
  64815. ear = next;
  64816. // if we looped through the whole remaining polygon and can't find any more ears
  64817. if (ear === stop) {
  64818. // try filtering points and slicing again
  64819. if (!pass) {
  64820. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64821. // if this didn't work, try curing all small self-intersections locally
  64822. }
  64823. else if (pass === 1) {
  64824. ear = cureLocalIntersections(ear, triangles, dim);
  64825. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64826. // as a last resort, try splitting the remaining polygon into two
  64827. }
  64828. else if (pass === 2) {
  64829. splitEarcut(ear, triangles, dim, minX, minY, size);
  64830. }
  64831. break;
  64832. }
  64833. }
  64834. }
  64835. // check whether a polygon node forms a valid ear with adjacent nodes
  64836. function isEar(ear) {
  64837. var a = ear.prev, b = ear, c = ear.next;
  64838. if (area(a, b, c) >= 0)
  64839. return false; // reflex, can't be an ear
  64840. // now make sure we don't have other points inside the potential ear
  64841. var p = ear.next.next;
  64842. while (p !== ear.prev) {
  64843. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64844. area(p.prev, p, p.next) >= 0)
  64845. return false;
  64846. p = p.next;
  64847. }
  64848. return true;
  64849. }
  64850. function isEarHashed(ear, minX, minY, size) {
  64851. var a = ear.prev, b = ear, c = ear.next;
  64852. if (area(a, b, c) >= 0)
  64853. return false; // reflex, can't be an ear
  64854. // triangle bbox; min & max are calculated like this for speed
  64855. 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);
  64856. // z-order range for the current triangle bbox;
  64857. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64858. // first look for points inside the triangle in increasing z-order
  64859. var p = ear.nextZ;
  64860. while (p && p.z <= maxZ) {
  64861. if (p !== ear.prev &&
  64862. p !== ear.next &&
  64863. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64864. area(p.prev, p, p.next) >= 0)
  64865. return false;
  64866. p = p.nextZ;
  64867. }
  64868. // then look for points in decreasing z-order
  64869. p = ear.prevZ;
  64870. while (p && p.z >= minZ) {
  64871. if (p !== ear.prev &&
  64872. p !== ear.next &&
  64873. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64874. area(p.prev, p, p.next) >= 0)
  64875. return false;
  64876. p = p.prevZ;
  64877. }
  64878. return true;
  64879. }
  64880. // go through all polygon nodes and cure small local self-intersections
  64881. function cureLocalIntersections(start, triangles, dim) {
  64882. var p = start;
  64883. do {
  64884. var a = p.prev, b = p.next.next;
  64885. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64886. triangles.push(a.i / dim);
  64887. triangles.push(p.i / dim);
  64888. triangles.push(b.i / dim);
  64889. // remove two nodes involved
  64890. removeNode(p);
  64891. removeNode(p.next);
  64892. p = start = b;
  64893. }
  64894. p = p.next;
  64895. } while (p !== start);
  64896. return p;
  64897. }
  64898. // try splitting polygon into two and triangulate them independently
  64899. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64900. // look for a valid diagonal that divides the polygon into two
  64901. var a = start;
  64902. do {
  64903. var b = a.next.next;
  64904. while (b !== a.prev) {
  64905. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64906. // split the polygon in two by the diagonal
  64907. var c = splitPolygon(a, b);
  64908. // filter colinear points around the cuts
  64909. a = filterPoints(a, a.next);
  64910. c = filterPoints(c, c.next);
  64911. // run earcut on each half
  64912. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64913. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64914. return;
  64915. }
  64916. b = b.next;
  64917. }
  64918. a = a.next;
  64919. } while (a !== start);
  64920. }
  64921. // link every hole into the outer loop, producing a single-ring polygon without holes
  64922. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64923. var queue = [], i, len, start, end, list;
  64924. for (i = 0, len = holeIndices.length; i < len; i++) {
  64925. start = holeIndices[i] * dim;
  64926. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64927. list = linkedList(data, start, end, dim, false);
  64928. if (list === list.next)
  64929. list.steiner = true;
  64930. queue.push(getLeftmost(list));
  64931. }
  64932. queue.sort(compareX);
  64933. // process holes from left to right
  64934. for (i = 0; i < queue.length; i++) {
  64935. eliminateHole(queue[i], outerNode);
  64936. outerNode = filterPoints(outerNode, outerNode.next);
  64937. }
  64938. return outerNode;
  64939. }
  64940. function compareX(a, b) {
  64941. return a.x - b.x;
  64942. }
  64943. // find a bridge between vertices that connects hole with an outer ring and and link it
  64944. function eliminateHole(hole, outerNode) {
  64945. outerNode = findHoleBridge(hole, outerNode);
  64946. if (outerNode) {
  64947. var b = splitPolygon(outerNode, hole);
  64948. filterPoints(b, b.next);
  64949. }
  64950. }
  64951. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64952. function findHoleBridge(hole, outerNode) {
  64953. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64954. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64955. // segment's endpoint with lesser x will be potential connection point
  64956. do {
  64957. if (hy <= p.y && hy >= p.next.y) {
  64958. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64959. if (x <= hx && x > qx) {
  64960. qx = x;
  64961. if (x === hx) {
  64962. if (hy === p.y)
  64963. return p;
  64964. if (hy === p.next.y)
  64965. return p.next;
  64966. }
  64967. m = p.x < p.next.x ? p : p.next;
  64968. }
  64969. }
  64970. p = p.next;
  64971. } while (p !== outerNode);
  64972. if (!m)
  64973. return null;
  64974. if (hx === qx)
  64975. return m.prev; // hole touches outer segment; pick lower endpoint
  64976. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64977. // if there are no points found, we have a valid connection;
  64978. // otherwise choose the point of the minimum angle with the ray as connection point
  64979. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64980. p = m.next;
  64981. while (p !== stop) {
  64982. if (hx >= p.x &&
  64983. p.x >= mx &&
  64984. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64985. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64986. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64987. m = p;
  64988. tanMin = tan;
  64989. }
  64990. }
  64991. p = p.next;
  64992. }
  64993. return m;
  64994. }
  64995. // interlink polygon nodes in z-order
  64996. function indexCurve(start, minX, minY, size) {
  64997. var p = start;
  64998. do {
  64999. if (p.z === null)
  65000. p.z = zOrder(p.x, p.y, minX, minY, size);
  65001. p.prevZ = p.prev;
  65002. p.nextZ = p.next;
  65003. p = p.next;
  65004. } while (p !== start);
  65005. p.prevZ.nextZ = null;
  65006. p.prevZ = null;
  65007. sortLinked(p);
  65008. }
  65009. // Simon Tatham's linked list merge sort algorithm
  65010. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  65011. function sortLinked(list) {
  65012. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  65013. do {
  65014. p = list;
  65015. list = null;
  65016. tail = null;
  65017. numMerges = 0;
  65018. while (p) {
  65019. numMerges++;
  65020. q = p;
  65021. pSize = 0;
  65022. for (i = 0; i < inSize; i++) {
  65023. pSize++;
  65024. q = q.nextZ;
  65025. if (!q)
  65026. break;
  65027. }
  65028. qSize = inSize;
  65029. while (pSize > 0 || (qSize > 0 && q)) {
  65030. if (pSize === 0) {
  65031. e = q;
  65032. q = q.nextZ;
  65033. qSize--;
  65034. }
  65035. else if (qSize === 0 || !q) {
  65036. e = p;
  65037. p = p.nextZ;
  65038. pSize--;
  65039. }
  65040. else if (p.z <= q.z) {
  65041. e = p;
  65042. p = p.nextZ;
  65043. pSize--;
  65044. }
  65045. else {
  65046. e = q;
  65047. q = q.nextZ;
  65048. qSize--;
  65049. }
  65050. if (tail)
  65051. tail.nextZ = e;
  65052. else
  65053. list = e;
  65054. e.prevZ = tail;
  65055. tail = e;
  65056. }
  65057. p = q;
  65058. }
  65059. tail.nextZ = null;
  65060. inSize *= 2;
  65061. } while (numMerges > 1);
  65062. return list;
  65063. }
  65064. // z-order of a point given coords and size of the data bounding box
  65065. function zOrder(x, y, minX, minY, size) {
  65066. // coords are transformed into non-negative 15-bit integer range
  65067. x = 32767 * (x - minX) / size;
  65068. y = 32767 * (y - minY) / size;
  65069. x = (x | (x << 8)) & 0x00FF00FF;
  65070. x = (x | (x << 4)) & 0x0F0F0F0F;
  65071. x = (x | (x << 2)) & 0x33333333;
  65072. x = (x | (x << 1)) & 0x55555555;
  65073. y = (y | (y << 8)) & 0x00FF00FF;
  65074. y = (y | (y << 4)) & 0x0F0F0F0F;
  65075. y = (y | (y << 2)) & 0x33333333;
  65076. y = (y | (y << 1)) & 0x55555555;
  65077. return x | (y << 1);
  65078. }
  65079. // find the leftmost node of a polygon ring
  65080. function getLeftmost(start) {
  65081. var p = start, leftmost = start;
  65082. do {
  65083. if (p.x < leftmost.x)
  65084. leftmost = p;
  65085. p = p.next;
  65086. } while (p !== start);
  65087. return leftmost;
  65088. }
  65089. // check if a point lies within a convex triangle
  65090. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  65091. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  65092. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  65093. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  65094. }
  65095. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  65096. function isValidDiagonal(a, b) {
  65097. return a.next.i !== b.i &&
  65098. a.prev.i !== b.i &&
  65099. !intersectsPolygon(a, b) &&
  65100. locallyInside(a, b) &&
  65101. locallyInside(b, a) &&
  65102. middleInside(a, b);
  65103. }
  65104. // signed area of a triangle
  65105. function area(p, q, r) {
  65106. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  65107. }
  65108. // check if two points are equal
  65109. function equals(p1, p2) {
  65110. return p1.x === p2.x && p1.y === p2.y;
  65111. }
  65112. // check if two segments intersect
  65113. function intersects(p1, q1, p2, q2) {
  65114. if ((equals(p1, q1) && equals(p2, q2)) ||
  65115. (equals(p1, q2) && equals(p2, q1)))
  65116. return true;
  65117. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  65118. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  65119. }
  65120. // check if a polygon diagonal intersects any polygon segments
  65121. function intersectsPolygon(a, b) {
  65122. var p = a;
  65123. do {
  65124. if (p.i !== a.i &&
  65125. p.next.i !== a.i &&
  65126. p.i !== b.i &&
  65127. p.next.i !== b.i &&
  65128. intersects(p, p.next, a, b))
  65129. return true;
  65130. p = p.next;
  65131. } while (p !== a);
  65132. return false;
  65133. }
  65134. // check if a polygon diagonal is locally inside the polygon
  65135. function locallyInside(a, b) {
  65136. return area(a.prev, a, a.next) < 0
  65137. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  65138. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  65139. }
  65140. // check if the middle point of a polygon diagonal is inside the polygon
  65141. function middleInside(a, b) {
  65142. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  65143. do {
  65144. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  65145. inside = !inside;
  65146. p = p.next;
  65147. } while (p !== a);
  65148. return inside;
  65149. }
  65150. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  65151. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  65152. function splitPolygon(a, b) {
  65153. 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;
  65154. a.next = b;
  65155. b.prev = a;
  65156. a2.next = an;
  65157. an.prev = a2;
  65158. b2.next = a2;
  65159. a2.prev = b2;
  65160. bp.next = b2;
  65161. b2.prev = bp;
  65162. return b2;
  65163. }
  65164. // create a node and optionally link it with previous one (in a circular doubly linked list)
  65165. function insertNode(i, x, y, last) {
  65166. var p = new Node(i, x, y);
  65167. if (!last) {
  65168. p.prev = p;
  65169. p.next = p;
  65170. }
  65171. else {
  65172. p.next = last.next;
  65173. p.prev = last;
  65174. last.next.prev = p;
  65175. last.next = p;
  65176. }
  65177. return p;
  65178. }
  65179. function removeNode(p) {
  65180. p.next.prev = p.prev;
  65181. p.prev.next = p.next;
  65182. if (p.prevZ)
  65183. p.prevZ.nextZ = p.nextZ;
  65184. if (p.nextZ)
  65185. p.nextZ.prevZ = p.prevZ;
  65186. }
  65187. /**
  65188. * return a percentage difference between the polygon area and its triangulation area;
  65189. * used to verify correctness of triangulation
  65190. */
  65191. function deviation(data, holeIndices, dim, triangles) {
  65192. var hasHoles = holeIndices && holeIndices.length;
  65193. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  65194. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  65195. if (hasHoles) {
  65196. for (var i = 0, len = holeIndices.length; i < len; i++) {
  65197. var start = holeIndices[i] * dim;
  65198. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65199. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  65200. }
  65201. }
  65202. var trianglesArea = 0;
  65203. for (i = 0; i < triangles.length; i += 3) {
  65204. var a = triangles[i] * dim;
  65205. var b = triangles[i + 1] * dim;
  65206. var c = triangles[i + 2] * dim;
  65207. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  65208. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  65209. }
  65210. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  65211. }
  65212. Earcut.deviation = deviation;
  65213. ;
  65214. function signedArea(data, start, end, dim) {
  65215. var sum = 0;
  65216. for (var i = start, j = end - dim; i < end; i += dim) {
  65217. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  65218. j = i;
  65219. }
  65220. return sum;
  65221. }
  65222. /**
  65223. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  65224. */
  65225. function flatten(data) {
  65226. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  65227. for (var i = 0; i < data.length; i++) {
  65228. for (var j = 0; j < data[i].length; j++) {
  65229. for (var d = 0; d < dim; d++)
  65230. result.vertices.push(data[i][j][d]);
  65231. }
  65232. if (i > 0) {
  65233. holeIndex += data[i - 1].length;
  65234. result.holes.push(holeIndex);
  65235. }
  65236. }
  65237. return result;
  65238. }
  65239. Earcut.flatten = flatten;
  65240. ;
  65241. })(Earcut || (Earcut = {}));
  65242. //# sourceMappingURL=babylon.earcut.js.map
  65243. var BABYLON;
  65244. (function (BABYLON) {
  65245. var IndexedVector2 = /** @class */ (function (_super) {
  65246. __extends(IndexedVector2, _super);
  65247. function IndexedVector2(original, index) {
  65248. var _this = _super.call(this, original.x, original.y) || this;
  65249. _this.index = index;
  65250. return _this;
  65251. }
  65252. return IndexedVector2;
  65253. }(BABYLON.Vector2));
  65254. var PolygonPoints = /** @class */ (function () {
  65255. function PolygonPoints() {
  65256. this.elements = new Array();
  65257. }
  65258. PolygonPoints.prototype.add = function (originalPoints) {
  65259. var _this = this;
  65260. var result = new Array();
  65261. originalPoints.forEach(function (point) {
  65262. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  65263. var newPoint = new IndexedVector2(point, _this.elements.length);
  65264. result.push(newPoint);
  65265. _this.elements.push(newPoint);
  65266. }
  65267. });
  65268. return result;
  65269. };
  65270. PolygonPoints.prototype.computeBounds = function () {
  65271. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65272. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  65273. this.elements.forEach(function (point) {
  65274. // x
  65275. if (point.x < lmin.x) {
  65276. lmin.x = point.x;
  65277. }
  65278. else if (point.x > lmax.x) {
  65279. lmax.x = point.x;
  65280. }
  65281. // y
  65282. if (point.y < lmin.y) {
  65283. lmin.y = point.y;
  65284. }
  65285. else if (point.y > lmax.y) {
  65286. lmax.y = point.y;
  65287. }
  65288. });
  65289. return {
  65290. min: lmin,
  65291. max: lmax,
  65292. width: lmax.x - lmin.x,
  65293. height: lmax.y - lmin.y
  65294. };
  65295. };
  65296. return PolygonPoints;
  65297. }());
  65298. var Polygon = /** @class */ (function () {
  65299. function Polygon() {
  65300. }
  65301. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  65302. return [
  65303. new BABYLON.Vector2(xmin, ymin),
  65304. new BABYLON.Vector2(xmax, ymin),
  65305. new BABYLON.Vector2(xmax, ymax),
  65306. new BABYLON.Vector2(xmin, ymax)
  65307. ];
  65308. };
  65309. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  65310. if (cx === void 0) { cx = 0; }
  65311. if (cy === void 0) { cy = 0; }
  65312. if (numberOfSides === void 0) { numberOfSides = 32; }
  65313. var result = new Array();
  65314. var angle = 0;
  65315. var increment = (Math.PI * 2) / numberOfSides;
  65316. for (var i = 0; i < numberOfSides; i++) {
  65317. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  65318. angle -= increment;
  65319. }
  65320. return result;
  65321. };
  65322. Polygon.Parse = function (input) {
  65323. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  65324. var i, result = [];
  65325. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  65326. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  65327. }
  65328. return result;
  65329. };
  65330. Polygon.StartingAt = function (x, y) {
  65331. return BABYLON.Path2.StartingAt(x, y);
  65332. };
  65333. return Polygon;
  65334. }());
  65335. BABYLON.Polygon = Polygon;
  65336. var PolygonMeshBuilder = /** @class */ (function () {
  65337. function PolygonMeshBuilder(name, contours, scene) {
  65338. this._points = new PolygonPoints();
  65339. this._outlinepoints = new PolygonPoints();
  65340. this._holes = new Array();
  65341. this._epoints = new Array();
  65342. this._eholes = new Array();
  65343. this._name = name;
  65344. this._scene = scene;
  65345. var points;
  65346. if (contours instanceof BABYLON.Path2) {
  65347. points = contours.getPoints();
  65348. }
  65349. else {
  65350. points = contours;
  65351. }
  65352. this._addToepoint(points);
  65353. this._points.add(points);
  65354. this._outlinepoints.add(points);
  65355. }
  65356. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  65357. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  65358. var p = points_1[_i];
  65359. this._epoints.push(p.x, p.y);
  65360. }
  65361. };
  65362. PolygonMeshBuilder.prototype.addHole = function (hole) {
  65363. this._points.add(hole);
  65364. var holepoints = new PolygonPoints();
  65365. holepoints.add(hole);
  65366. this._holes.push(holepoints);
  65367. this._eholes.push(this._epoints.length / 2);
  65368. this._addToepoint(hole);
  65369. return this;
  65370. };
  65371. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  65372. var _this = this;
  65373. if (updatable === void 0) { updatable = false; }
  65374. if (depth === void 0) { depth = 0; }
  65375. var result = new BABYLON.Mesh(this._name, this._scene);
  65376. var normals = new Array();
  65377. var positions = new Array();
  65378. var uvs = new Array();
  65379. var bounds = this._points.computeBounds();
  65380. this._points.elements.forEach(function (p) {
  65381. normals.push(0, 1.0, 0);
  65382. positions.push(p.x, 0, p.y);
  65383. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  65384. });
  65385. var indices = new Array();
  65386. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  65387. for (var i = 0; i < res.length; i++) {
  65388. indices.push(res[i]);
  65389. }
  65390. if (depth > 0) {
  65391. var positionscount = (positions.length / 3); //get the current pointcount
  65392. this._points.elements.forEach(function (p) {
  65393. normals.push(0, -1.0, 0);
  65394. positions.push(p.x, -depth, p.y);
  65395. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  65396. });
  65397. var totalCount = indices.length;
  65398. for (var i = 0; i < totalCount; i += 3) {
  65399. var i0 = indices[i + 0];
  65400. var i1 = indices[i + 1];
  65401. var i2 = indices[i + 2];
  65402. indices.push(i2 + positionscount);
  65403. indices.push(i1 + positionscount);
  65404. indices.push(i0 + positionscount);
  65405. }
  65406. //Add the sides
  65407. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  65408. this._holes.forEach(function (hole) {
  65409. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  65410. });
  65411. }
  65412. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  65413. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  65414. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  65415. result.setIndices(indices);
  65416. return result;
  65417. };
  65418. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  65419. var StartIndex = positions.length / 3;
  65420. var ulength = 0;
  65421. for (var i = 0; i < points.elements.length; i++) {
  65422. var p = points.elements[i];
  65423. var p1;
  65424. if ((i + 1) > points.elements.length - 1) {
  65425. p1 = points.elements[0];
  65426. }
  65427. else {
  65428. p1 = points.elements[i + 1];
  65429. }
  65430. positions.push(p.x, 0, p.y);
  65431. positions.push(p.x, -depth, p.y);
  65432. positions.push(p1.x, 0, p1.y);
  65433. positions.push(p1.x, -depth, p1.y);
  65434. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  65435. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  65436. var v3 = v2.subtract(v1);
  65437. var v4 = new BABYLON.Vector3(0, 1, 0);
  65438. var vn = BABYLON.Vector3.Cross(v3, v4);
  65439. vn = vn.normalize();
  65440. uvs.push(ulength / bounds.width, 0);
  65441. uvs.push(ulength / bounds.width, 1);
  65442. ulength += v3.length();
  65443. uvs.push((ulength / bounds.width), 0);
  65444. uvs.push((ulength / bounds.width), 1);
  65445. if (!flip) {
  65446. normals.push(-vn.x, -vn.y, -vn.z);
  65447. normals.push(-vn.x, -vn.y, -vn.z);
  65448. normals.push(-vn.x, -vn.y, -vn.z);
  65449. normals.push(-vn.x, -vn.y, -vn.z);
  65450. indices.push(StartIndex);
  65451. indices.push(StartIndex + 1);
  65452. indices.push(StartIndex + 2);
  65453. indices.push(StartIndex + 1);
  65454. indices.push(StartIndex + 3);
  65455. indices.push(StartIndex + 2);
  65456. }
  65457. else {
  65458. normals.push(vn.x, vn.y, vn.z);
  65459. normals.push(vn.x, vn.y, vn.z);
  65460. normals.push(vn.x, vn.y, vn.z);
  65461. normals.push(vn.x, vn.y, vn.z);
  65462. indices.push(StartIndex);
  65463. indices.push(StartIndex + 2);
  65464. indices.push(StartIndex + 1);
  65465. indices.push(StartIndex + 1);
  65466. indices.push(StartIndex + 2);
  65467. indices.push(StartIndex + 3);
  65468. }
  65469. StartIndex += 4;
  65470. }
  65471. ;
  65472. };
  65473. return PolygonMeshBuilder;
  65474. }());
  65475. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  65476. })(BABYLON || (BABYLON = {}));
  65477. //# sourceMappingURL=babylon.polygonMesh.js.map
  65478. var BABYLON;
  65479. (function (BABYLON) {
  65480. // Unique ID when we import meshes from Babylon to CSG
  65481. var currentCSGMeshId = 0;
  65482. // # class Vertex
  65483. // Represents a vertex of a polygon. Use your own vertex class instead of this
  65484. // one to provide additional features like texture coordinates and vertex
  65485. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  65486. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  65487. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  65488. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  65489. // is not used anywhere else.
  65490. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  65491. var Vertex = /** @class */ (function () {
  65492. function Vertex(pos, normal, uv) {
  65493. this.pos = pos;
  65494. this.normal = normal;
  65495. this.uv = uv;
  65496. }
  65497. Vertex.prototype.clone = function () {
  65498. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  65499. };
  65500. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  65501. // orientation of a polygon is flipped.
  65502. Vertex.prototype.flip = function () {
  65503. this.normal = this.normal.scale(-1);
  65504. };
  65505. // Create a new vertex between this vertex and `other` by linearly
  65506. // interpolating all properties using a parameter of `t`. Subclasses should
  65507. // override this to interpolate additional properties.
  65508. Vertex.prototype.interpolate = function (other, t) {
  65509. 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));
  65510. };
  65511. return Vertex;
  65512. }());
  65513. // # class Plane
  65514. // Represents a plane in 3D space.
  65515. var Plane = /** @class */ (function () {
  65516. function Plane(normal, w) {
  65517. this.normal = normal;
  65518. this.w = w;
  65519. }
  65520. Plane.FromPoints = function (a, b, c) {
  65521. var v0 = c.subtract(a);
  65522. var v1 = b.subtract(a);
  65523. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  65524. return null;
  65525. }
  65526. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  65527. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  65528. };
  65529. Plane.prototype.clone = function () {
  65530. return new Plane(this.normal.clone(), this.w);
  65531. };
  65532. Plane.prototype.flip = function () {
  65533. this.normal.scaleInPlace(-1);
  65534. this.w = -this.w;
  65535. };
  65536. // Split `polygon` by this plane if needed, then put the polygon or polygon
  65537. // fragments in the appropriate lists. Coplanar polygons go into either
  65538. // `coplanarFront` or `coplanarBack` depending on their orientation with
  65539. // respect to this plane. Polygons in front or in back of this plane go into
  65540. // either `front` or `back`.
  65541. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  65542. var COPLANAR = 0;
  65543. var FRONT = 1;
  65544. var BACK = 2;
  65545. var SPANNING = 3;
  65546. // Classify each point as well as the entire polygon into one of the above
  65547. // four classes.
  65548. var polygonType = 0;
  65549. var types = [];
  65550. var i;
  65551. var t;
  65552. for (i = 0; i < polygon.vertices.length; i++) {
  65553. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  65554. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  65555. polygonType |= type;
  65556. types.push(type);
  65557. }
  65558. // Put the polygon in the correct list, splitting it when necessary.
  65559. switch (polygonType) {
  65560. case COPLANAR:
  65561. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  65562. break;
  65563. case FRONT:
  65564. front.push(polygon);
  65565. break;
  65566. case BACK:
  65567. back.push(polygon);
  65568. break;
  65569. case SPANNING:
  65570. var f = [], b = [];
  65571. for (i = 0; i < polygon.vertices.length; i++) {
  65572. var j = (i + 1) % polygon.vertices.length;
  65573. var ti = types[i], tj = types[j];
  65574. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  65575. if (ti !== BACK)
  65576. f.push(vi);
  65577. if (ti !== FRONT)
  65578. b.push(ti !== BACK ? vi.clone() : vi);
  65579. if ((ti | tj) === SPANNING) {
  65580. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65581. var v = vi.interpolate(vj, t);
  65582. f.push(v);
  65583. b.push(v.clone());
  65584. }
  65585. }
  65586. var poly;
  65587. if (f.length >= 3) {
  65588. poly = new Polygon(f, polygon.shared);
  65589. if (poly.plane)
  65590. front.push(poly);
  65591. }
  65592. if (b.length >= 3) {
  65593. poly = new Polygon(b, polygon.shared);
  65594. if (poly.plane)
  65595. back.push(poly);
  65596. }
  65597. break;
  65598. }
  65599. };
  65600. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65601. // point is on the plane.
  65602. Plane.EPSILON = 1e-5;
  65603. return Plane;
  65604. }());
  65605. // # class Polygon
  65606. // Represents a convex polygon. The vertices used to initialize a polygon must
  65607. // be coplanar and form a convex loop.
  65608. //
  65609. // Each convex polygon has a `shared` property, which is shared between all
  65610. // polygons that are clones of each other or were split from the same polygon.
  65611. // This can be used to define per-polygon properties (such as surface color).
  65612. var Polygon = /** @class */ (function () {
  65613. function Polygon(vertices, shared) {
  65614. this.vertices = vertices;
  65615. this.shared = shared;
  65616. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65617. }
  65618. Polygon.prototype.clone = function () {
  65619. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65620. return new Polygon(vertices, this.shared);
  65621. };
  65622. Polygon.prototype.flip = function () {
  65623. this.vertices.reverse().map(function (v) { v.flip(); });
  65624. this.plane.flip();
  65625. };
  65626. return Polygon;
  65627. }());
  65628. // # class Node
  65629. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65630. // by picking a polygon to split along. That polygon (and all other coplanar
  65631. // polygons) are added directly to that node and the other polygons are added to
  65632. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65633. // no distinction between internal and leaf nodes.
  65634. var Node = /** @class */ (function () {
  65635. function Node(polygons) {
  65636. this.plane = null;
  65637. this.front = null;
  65638. this.back = null;
  65639. this.polygons = new Array();
  65640. if (polygons) {
  65641. this.build(polygons);
  65642. }
  65643. }
  65644. Node.prototype.clone = function () {
  65645. var node = new Node();
  65646. node.plane = this.plane && this.plane.clone();
  65647. node.front = this.front && this.front.clone();
  65648. node.back = this.back && this.back.clone();
  65649. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65650. return node;
  65651. };
  65652. // Convert solid space to empty space and empty space to solid space.
  65653. Node.prototype.invert = function () {
  65654. for (var i = 0; i < this.polygons.length; i++) {
  65655. this.polygons[i].flip();
  65656. }
  65657. if (this.plane) {
  65658. this.plane.flip();
  65659. }
  65660. if (this.front) {
  65661. this.front.invert();
  65662. }
  65663. if (this.back) {
  65664. this.back.invert();
  65665. }
  65666. var temp = this.front;
  65667. this.front = this.back;
  65668. this.back = temp;
  65669. };
  65670. // Recursively remove all polygons in `polygons` that are inside this BSP
  65671. // tree.
  65672. Node.prototype.clipPolygons = function (polygons) {
  65673. if (!this.plane)
  65674. return polygons.slice();
  65675. var front = new Array(), back = new Array();
  65676. for (var i = 0; i < polygons.length; i++) {
  65677. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65678. }
  65679. if (this.front) {
  65680. front = this.front.clipPolygons(front);
  65681. }
  65682. if (this.back) {
  65683. back = this.back.clipPolygons(back);
  65684. }
  65685. else {
  65686. back = [];
  65687. }
  65688. return front.concat(back);
  65689. };
  65690. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65691. // `bsp`.
  65692. Node.prototype.clipTo = function (bsp) {
  65693. this.polygons = bsp.clipPolygons(this.polygons);
  65694. if (this.front)
  65695. this.front.clipTo(bsp);
  65696. if (this.back)
  65697. this.back.clipTo(bsp);
  65698. };
  65699. // Return a list of all polygons in this BSP tree.
  65700. Node.prototype.allPolygons = function () {
  65701. var polygons = this.polygons.slice();
  65702. if (this.front)
  65703. polygons = polygons.concat(this.front.allPolygons());
  65704. if (this.back)
  65705. polygons = polygons.concat(this.back.allPolygons());
  65706. return polygons;
  65707. };
  65708. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65709. // new polygons are filtered down to the bottom of the tree and become new
  65710. // nodes there. Each set of polygons is partitioned using the first polygon
  65711. // (no heuristic is used to pick a good split).
  65712. Node.prototype.build = function (polygons) {
  65713. if (!polygons.length)
  65714. return;
  65715. if (!this.plane)
  65716. this.plane = polygons[0].plane.clone();
  65717. var front = new Array(), back = new Array();
  65718. for (var i = 0; i < polygons.length; i++) {
  65719. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65720. }
  65721. if (front.length) {
  65722. if (!this.front)
  65723. this.front = new Node();
  65724. this.front.build(front);
  65725. }
  65726. if (back.length) {
  65727. if (!this.back)
  65728. this.back = new Node();
  65729. this.back.build(back);
  65730. }
  65731. };
  65732. return Node;
  65733. }());
  65734. var CSG = /** @class */ (function () {
  65735. function CSG() {
  65736. this.polygons = new Array();
  65737. }
  65738. // Convert BABYLON.Mesh to BABYLON.CSG
  65739. CSG.FromMesh = function (mesh) {
  65740. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65741. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65742. if (mesh instanceof BABYLON.Mesh) {
  65743. mesh.computeWorldMatrix(true);
  65744. matrix = mesh.getWorldMatrix();
  65745. meshPosition = mesh.position.clone();
  65746. meshRotation = mesh.rotation.clone();
  65747. if (mesh.rotationQuaternion) {
  65748. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65749. }
  65750. meshScaling = mesh.scaling.clone();
  65751. }
  65752. else {
  65753. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65754. }
  65755. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65756. var subMeshes = mesh.subMeshes;
  65757. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65758. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65759. vertices = [];
  65760. for (var j = 0; j < 3; j++) {
  65761. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65762. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65763. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65764. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65765. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65766. vertex = new Vertex(position, normal, uv);
  65767. vertices.push(vertex);
  65768. }
  65769. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65770. // To handle the case of degenerated triangle
  65771. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65772. if (polygon.plane)
  65773. polygons.push(polygon);
  65774. }
  65775. }
  65776. var csg = CSG.FromPolygons(polygons);
  65777. csg.matrix = matrix;
  65778. csg.position = meshPosition;
  65779. csg.rotation = meshRotation;
  65780. csg.scaling = meshScaling;
  65781. csg.rotationQuaternion = meshRotationQuaternion;
  65782. currentCSGMeshId++;
  65783. return csg;
  65784. };
  65785. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65786. CSG.FromPolygons = function (polygons) {
  65787. var csg = new CSG();
  65788. csg.polygons = polygons;
  65789. return csg;
  65790. };
  65791. CSG.prototype.clone = function () {
  65792. var csg = new CSG();
  65793. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65794. csg.copyTransformAttributes(this);
  65795. return csg;
  65796. };
  65797. CSG.prototype.union = function (csg) {
  65798. var a = new Node(this.clone().polygons);
  65799. var b = new Node(csg.clone().polygons);
  65800. a.clipTo(b);
  65801. b.clipTo(a);
  65802. b.invert();
  65803. b.clipTo(a);
  65804. b.invert();
  65805. a.build(b.allPolygons());
  65806. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65807. };
  65808. CSG.prototype.unionInPlace = function (csg) {
  65809. var a = new Node(this.polygons);
  65810. var b = new Node(csg.polygons);
  65811. a.clipTo(b);
  65812. b.clipTo(a);
  65813. b.invert();
  65814. b.clipTo(a);
  65815. b.invert();
  65816. a.build(b.allPolygons());
  65817. this.polygons = a.allPolygons();
  65818. };
  65819. CSG.prototype.subtract = function (csg) {
  65820. var a = new Node(this.clone().polygons);
  65821. var b = new Node(csg.clone().polygons);
  65822. a.invert();
  65823. a.clipTo(b);
  65824. b.clipTo(a);
  65825. b.invert();
  65826. b.clipTo(a);
  65827. b.invert();
  65828. a.build(b.allPolygons());
  65829. a.invert();
  65830. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65831. };
  65832. CSG.prototype.subtractInPlace = function (csg) {
  65833. var a = new Node(this.polygons);
  65834. var b = new Node(csg.polygons);
  65835. a.invert();
  65836. a.clipTo(b);
  65837. b.clipTo(a);
  65838. b.invert();
  65839. b.clipTo(a);
  65840. b.invert();
  65841. a.build(b.allPolygons());
  65842. a.invert();
  65843. this.polygons = a.allPolygons();
  65844. };
  65845. CSG.prototype.intersect = function (csg) {
  65846. var a = new Node(this.clone().polygons);
  65847. var b = new Node(csg.clone().polygons);
  65848. a.invert();
  65849. b.clipTo(a);
  65850. b.invert();
  65851. a.clipTo(b);
  65852. b.clipTo(a);
  65853. a.build(b.allPolygons());
  65854. a.invert();
  65855. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65856. };
  65857. CSG.prototype.intersectInPlace = function (csg) {
  65858. var a = new Node(this.polygons);
  65859. var b = new Node(csg.polygons);
  65860. a.invert();
  65861. b.clipTo(a);
  65862. b.invert();
  65863. a.clipTo(b);
  65864. b.clipTo(a);
  65865. a.build(b.allPolygons());
  65866. a.invert();
  65867. this.polygons = a.allPolygons();
  65868. };
  65869. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65870. // not modified.
  65871. CSG.prototype.inverse = function () {
  65872. var csg = this.clone();
  65873. csg.inverseInPlace();
  65874. return csg;
  65875. };
  65876. CSG.prototype.inverseInPlace = function () {
  65877. this.polygons.map(function (p) { p.flip(); });
  65878. };
  65879. // This is used to keep meshes transformations so they can be restored
  65880. // when we build back a Babylon Mesh
  65881. // NB : All CSG operations are performed in world coordinates
  65882. CSG.prototype.copyTransformAttributes = function (csg) {
  65883. this.matrix = csg.matrix;
  65884. this.position = csg.position;
  65885. this.rotation = csg.rotation;
  65886. this.scaling = csg.scaling;
  65887. this.rotationQuaternion = csg.rotationQuaternion;
  65888. return this;
  65889. };
  65890. // Build Raw mesh from CSG
  65891. // Coordinates here are in world space
  65892. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65893. var matrix = this.matrix.clone();
  65894. matrix.invert();
  65895. 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;
  65896. if (keepSubMeshes) {
  65897. // Sort Polygons, since subMeshes are indices range
  65898. polygons.sort(function (a, b) {
  65899. if (a.shared.meshId === b.shared.meshId) {
  65900. return a.shared.subMeshId - b.shared.subMeshId;
  65901. }
  65902. else {
  65903. return a.shared.meshId - b.shared.meshId;
  65904. }
  65905. });
  65906. }
  65907. for (var i = 0, il = polygons.length; i < il; i++) {
  65908. polygon = polygons[i];
  65909. // Building SubMeshes
  65910. if (!subMesh_dict[polygon.shared.meshId]) {
  65911. subMesh_dict[polygon.shared.meshId] = {};
  65912. }
  65913. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65914. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65915. indexStart: +Infinity,
  65916. indexEnd: -Infinity,
  65917. materialIndex: polygon.shared.materialIndex
  65918. };
  65919. }
  65920. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65921. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65922. polygonIndices[0] = 0;
  65923. polygonIndices[1] = j - 1;
  65924. polygonIndices[2] = j;
  65925. for (var k = 0; k < 3; k++) {
  65926. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65927. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65928. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65929. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65930. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65931. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65932. // Check if 2 points can be merged
  65933. if (!(typeof vertex_idx !== 'undefined' &&
  65934. normals[vertex_idx * 3] === localNormal.x &&
  65935. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65936. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65937. uvs[vertex_idx * 2] === uv.x &&
  65938. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65939. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65940. uvs.push(uv.x, uv.y);
  65941. normals.push(normal.x, normal.y, normal.z);
  65942. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65943. }
  65944. indices.push(vertex_idx);
  65945. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65946. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65947. currentIndex++;
  65948. }
  65949. }
  65950. }
  65951. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65952. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65953. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65954. mesh.setIndices(indices, null);
  65955. if (keepSubMeshes) {
  65956. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65957. var materialIndexOffset = 0, materialMaxIndex;
  65958. mesh.subMeshes = new Array();
  65959. for (var m in subMesh_dict) {
  65960. materialMaxIndex = -1;
  65961. for (var sm in subMesh_dict[m]) {
  65962. subMesh_obj = subMesh_dict[m][sm];
  65963. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65964. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65965. }
  65966. materialIndexOffset += ++materialMaxIndex;
  65967. }
  65968. }
  65969. return mesh;
  65970. };
  65971. // Build Mesh from CSG taking material and transforms into account
  65972. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65973. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65974. mesh.material = material;
  65975. mesh.position.copyFrom(this.position);
  65976. mesh.rotation.copyFrom(this.rotation);
  65977. if (this.rotationQuaternion) {
  65978. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65979. }
  65980. mesh.scaling.copyFrom(this.scaling);
  65981. mesh.computeWorldMatrix(true);
  65982. return mesh;
  65983. };
  65984. return CSG;
  65985. }());
  65986. BABYLON.CSG = CSG;
  65987. })(BABYLON || (BABYLON = {}));
  65988. //# sourceMappingURL=babylon.csg.js.map
  65989. var BABYLON;
  65990. (function (BABYLON) {
  65991. var LensFlare = /** @class */ (function () {
  65992. function LensFlare(size, position, color, imgUrl, system) {
  65993. this.size = size;
  65994. this.position = position;
  65995. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65996. this.color = color || new BABYLON.Color3(1, 1, 1);
  65997. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65998. this._system = system;
  65999. system.lensFlares.push(this);
  66000. }
  66001. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  66002. return new LensFlare(size, position, color, imgUrl, system);
  66003. };
  66004. LensFlare.prototype.dispose = function () {
  66005. if (this.texture) {
  66006. this.texture.dispose();
  66007. }
  66008. // Remove from scene
  66009. var index = this._system.lensFlares.indexOf(this);
  66010. this._system.lensFlares.splice(index, 1);
  66011. };
  66012. ;
  66013. return LensFlare;
  66014. }());
  66015. BABYLON.LensFlare = LensFlare;
  66016. })(BABYLON || (BABYLON = {}));
  66017. //# sourceMappingURL=babylon.lensFlare.js.map
  66018. var BABYLON;
  66019. (function (BABYLON) {
  66020. var LensFlareSystem = /** @class */ (function () {
  66021. function LensFlareSystem(name, emitter, scene) {
  66022. this.name = name;
  66023. this.lensFlares = new Array();
  66024. this.borderLimit = 300;
  66025. this.viewportBorder = 0;
  66026. this.layerMask = 0x0FFFFFFF;
  66027. this._vertexBuffers = {};
  66028. this._isEnabled = true;
  66029. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66030. this._emitter = emitter;
  66031. this.id = name;
  66032. scene.lensFlareSystems.push(this);
  66033. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  66034. var engine = scene.getEngine();
  66035. // VBO
  66036. var vertices = [];
  66037. vertices.push(1, 1);
  66038. vertices.push(-1, 1);
  66039. vertices.push(-1, -1);
  66040. vertices.push(1, -1);
  66041. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66042. // Indices
  66043. var indices = [];
  66044. indices.push(0);
  66045. indices.push(1);
  66046. indices.push(2);
  66047. indices.push(0);
  66048. indices.push(2);
  66049. indices.push(3);
  66050. this._indexBuffer = engine.createIndexBuffer(indices);
  66051. // Effects
  66052. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  66053. }
  66054. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  66055. get: function () {
  66056. return this._isEnabled;
  66057. },
  66058. set: function (value) {
  66059. this._isEnabled = value;
  66060. },
  66061. enumerable: true,
  66062. configurable: true
  66063. });
  66064. LensFlareSystem.prototype.getScene = function () {
  66065. return this._scene;
  66066. };
  66067. LensFlareSystem.prototype.getEmitter = function () {
  66068. return this._emitter;
  66069. };
  66070. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  66071. this._emitter = newEmitter;
  66072. };
  66073. LensFlareSystem.prototype.getEmitterPosition = function () {
  66074. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  66075. };
  66076. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  66077. var position = this.getEmitterPosition();
  66078. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  66079. this._positionX = position.x;
  66080. this._positionY = position.y;
  66081. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  66082. if (this.viewportBorder > 0) {
  66083. globalViewport.x -= this.viewportBorder;
  66084. globalViewport.y -= this.viewportBorder;
  66085. globalViewport.width += this.viewportBorder * 2;
  66086. globalViewport.height += this.viewportBorder * 2;
  66087. position.x += this.viewportBorder;
  66088. position.y += this.viewportBorder;
  66089. this._positionX += this.viewportBorder;
  66090. this._positionY += this.viewportBorder;
  66091. }
  66092. if (position.z > 0) {
  66093. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  66094. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  66095. return true;
  66096. }
  66097. return true;
  66098. }
  66099. return false;
  66100. };
  66101. LensFlareSystem.prototype._isVisible = function () {
  66102. if (!this._isEnabled || !this._scene.activeCamera) {
  66103. return false;
  66104. }
  66105. var emitterPosition = this.getEmitterPosition();
  66106. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  66107. var distance = direction.length();
  66108. direction.normalize();
  66109. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  66110. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  66111. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  66112. };
  66113. LensFlareSystem.prototype.render = function () {
  66114. if (!this._effect.isReady() || !this._scene.activeCamera)
  66115. return false;
  66116. var engine = this._scene.getEngine();
  66117. var viewport = this._scene.activeCamera.viewport;
  66118. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  66119. // Position
  66120. if (!this.computeEffectivePosition(globalViewport)) {
  66121. return false;
  66122. }
  66123. // Visibility
  66124. if (!this._isVisible()) {
  66125. return false;
  66126. }
  66127. // Intensity
  66128. var awayX;
  66129. var awayY;
  66130. if (this._positionX < this.borderLimit + globalViewport.x) {
  66131. awayX = this.borderLimit + globalViewport.x - this._positionX;
  66132. }
  66133. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  66134. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  66135. }
  66136. else {
  66137. awayX = 0;
  66138. }
  66139. if (this._positionY < this.borderLimit + globalViewport.y) {
  66140. awayY = this.borderLimit + globalViewport.y - this._positionY;
  66141. }
  66142. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  66143. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  66144. }
  66145. else {
  66146. awayY = 0;
  66147. }
  66148. var away = (awayX > awayY) ? awayX : awayY;
  66149. away -= this.viewportBorder;
  66150. if (away > this.borderLimit) {
  66151. away = this.borderLimit;
  66152. }
  66153. var intensity = 1.0 - (away / this.borderLimit);
  66154. if (intensity < 0) {
  66155. return false;
  66156. }
  66157. if (intensity > 1.0) {
  66158. intensity = 1.0;
  66159. }
  66160. if (this.viewportBorder > 0) {
  66161. globalViewport.x += this.viewportBorder;
  66162. globalViewport.y += this.viewportBorder;
  66163. globalViewport.width -= this.viewportBorder * 2;
  66164. globalViewport.height -= this.viewportBorder * 2;
  66165. this._positionX -= this.viewportBorder;
  66166. this._positionY -= this.viewportBorder;
  66167. }
  66168. // Position
  66169. var centerX = globalViewport.x + globalViewport.width / 2;
  66170. var centerY = globalViewport.y + globalViewport.height / 2;
  66171. var distX = centerX - this._positionX;
  66172. var distY = centerY - this._positionY;
  66173. // Effects
  66174. engine.enableEffect(this._effect);
  66175. engine.setState(false);
  66176. engine.setDepthBuffer(false);
  66177. // VBOs
  66178. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66179. // Flares
  66180. for (var index = 0; index < this.lensFlares.length; index++) {
  66181. var flare = this.lensFlares[index];
  66182. engine.setAlphaMode(flare.alphaMode);
  66183. var x = centerX - (distX * flare.position);
  66184. var y = centerY - (distY * flare.position);
  66185. var cw = flare.size;
  66186. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  66187. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  66188. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  66189. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  66190. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  66191. // Texture
  66192. this._effect.setTexture("textureSampler", flare.texture);
  66193. // Color
  66194. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  66195. // Draw order
  66196. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66197. }
  66198. engine.setDepthBuffer(true);
  66199. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66200. return true;
  66201. };
  66202. LensFlareSystem.prototype.dispose = function () {
  66203. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66204. if (vertexBuffer) {
  66205. vertexBuffer.dispose();
  66206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66207. }
  66208. if (this._indexBuffer) {
  66209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66210. this._indexBuffer = null;
  66211. }
  66212. while (this.lensFlares.length) {
  66213. this.lensFlares[0].dispose();
  66214. }
  66215. // Remove from scene
  66216. var index = this._scene.lensFlareSystems.indexOf(this);
  66217. this._scene.lensFlareSystems.splice(index, 1);
  66218. };
  66219. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  66220. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  66221. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  66222. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  66223. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  66224. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  66225. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  66226. var parsedFlare = parsedLensFlareSystem.flares[index];
  66227. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  66228. }
  66229. return lensFlareSystem;
  66230. };
  66231. LensFlareSystem.prototype.serialize = function () {
  66232. var serializationObject = {};
  66233. serializationObject.id = this.id;
  66234. serializationObject.name = this.name;
  66235. serializationObject.emitterId = this.getEmitter().id;
  66236. serializationObject.borderLimit = this.borderLimit;
  66237. serializationObject.flares = [];
  66238. for (var index = 0; index < this.lensFlares.length; index++) {
  66239. var flare = this.lensFlares[index];
  66240. serializationObject.flares.push({
  66241. size: flare.size,
  66242. position: flare.position,
  66243. color: flare.color.asArray(),
  66244. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  66245. });
  66246. }
  66247. return serializationObject;
  66248. };
  66249. return LensFlareSystem;
  66250. }());
  66251. BABYLON.LensFlareSystem = LensFlareSystem;
  66252. })(BABYLON || (BABYLON = {}));
  66253. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  66254. var BABYLON;
  66255. (function (BABYLON) {
  66256. /**
  66257. * This is a holder class for the physics joint created by the physics plugin.
  66258. * It holds a set of functions to control the underlying joint.
  66259. */
  66260. var PhysicsJoint = /** @class */ (function () {
  66261. function PhysicsJoint(type, jointData) {
  66262. this.type = type;
  66263. this.jointData = jointData;
  66264. jointData.nativeParams = jointData.nativeParams || {};
  66265. }
  66266. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  66267. get: function () {
  66268. return this._physicsJoint;
  66269. },
  66270. set: function (newJoint) {
  66271. if (this._physicsJoint) {
  66272. //remove from the wolrd
  66273. }
  66274. this._physicsJoint = newJoint;
  66275. },
  66276. enumerable: true,
  66277. configurable: true
  66278. });
  66279. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  66280. set: function (physicsPlugin) {
  66281. this._physicsPlugin = physicsPlugin;
  66282. },
  66283. enumerable: true,
  66284. configurable: true
  66285. });
  66286. /**
  66287. * Execute a function that is physics-plugin specific.
  66288. * @param {Function} func the function that will be executed.
  66289. * It accepts two parameters: the physics world and the physics joint.
  66290. */
  66291. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  66292. func(this._physicsPlugin.world, this._physicsJoint);
  66293. };
  66294. //TODO check if the native joints are the same
  66295. //Joint Types
  66296. PhysicsJoint.DistanceJoint = 0;
  66297. PhysicsJoint.HingeJoint = 1;
  66298. PhysicsJoint.BallAndSocketJoint = 2;
  66299. PhysicsJoint.WheelJoint = 3;
  66300. PhysicsJoint.SliderJoint = 4;
  66301. //OIMO
  66302. PhysicsJoint.PrismaticJoint = 5;
  66303. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  66304. PhysicsJoint.UniversalJoint = 6;
  66305. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  66306. //Cannon
  66307. //Similar to a Ball-Joint. Different in params
  66308. PhysicsJoint.PointToPointJoint = 8;
  66309. //Cannon only at the moment
  66310. PhysicsJoint.SpringJoint = 9;
  66311. PhysicsJoint.LockJoint = 10;
  66312. return PhysicsJoint;
  66313. }());
  66314. BABYLON.PhysicsJoint = PhysicsJoint;
  66315. /**
  66316. * A class representing a physics distance joint.
  66317. */
  66318. var DistanceJoint = /** @class */ (function (_super) {
  66319. __extends(DistanceJoint, _super);
  66320. function DistanceJoint(jointData) {
  66321. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  66322. }
  66323. /**
  66324. * Update the predefined distance.
  66325. */
  66326. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  66327. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  66328. };
  66329. return DistanceJoint;
  66330. }(PhysicsJoint));
  66331. BABYLON.DistanceJoint = DistanceJoint;
  66332. var MotorEnabledJoint = /** @class */ (function (_super) {
  66333. __extends(MotorEnabledJoint, _super);
  66334. function MotorEnabledJoint(type, jointData) {
  66335. return _super.call(this, type, jointData) || this;
  66336. }
  66337. /**
  66338. * Set the motor values.
  66339. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66340. * @param {number} force the force to apply
  66341. * @param {number} maxForce max force for this motor.
  66342. */
  66343. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  66344. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66345. };
  66346. /**
  66347. * Set the motor's limits.
  66348. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66349. */
  66350. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66351. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66352. };
  66353. return MotorEnabledJoint;
  66354. }(PhysicsJoint));
  66355. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  66356. /**
  66357. * This class represents a single hinge physics joint
  66358. */
  66359. var HingeJoint = /** @class */ (function (_super) {
  66360. __extends(HingeJoint, _super);
  66361. function HingeJoint(jointData) {
  66362. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  66363. }
  66364. /**
  66365. * Set the motor values.
  66366. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66367. * @param {number} force the force to apply
  66368. * @param {number} maxForce max force for this motor.
  66369. */
  66370. HingeJoint.prototype.setMotor = function (force, maxForce) {
  66371. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  66372. };
  66373. /**
  66374. * Set the motor's limits.
  66375. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66376. */
  66377. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  66378. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  66379. };
  66380. return HingeJoint;
  66381. }(MotorEnabledJoint));
  66382. BABYLON.HingeJoint = HingeJoint;
  66383. /**
  66384. * This class represents a dual hinge physics joint (same as wheel joint)
  66385. */
  66386. var Hinge2Joint = /** @class */ (function (_super) {
  66387. __extends(Hinge2Joint, _super);
  66388. function Hinge2Joint(jointData) {
  66389. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  66390. }
  66391. /**
  66392. * Set the motor values.
  66393. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66394. * @param {number} force the force to apply
  66395. * @param {number} maxForce max force for this motor.
  66396. * @param {motorIndex} the motor's index, 0 or 1.
  66397. */
  66398. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  66399. if (motorIndex === void 0) { motorIndex = 0; }
  66400. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  66401. };
  66402. /**
  66403. * Set the motor limits.
  66404. * Attention, this function is plugin specific. Engines won't react 100% the same.
  66405. * @param {number} upperLimit the upper limit
  66406. * @param {number} lowerLimit lower limit
  66407. * @param {motorIndex} the motor's index, 0 or 1.
  66408. */
  66409. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  66410. if (motorIndex === void 0) { motorIndex = 0; }
  66411. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  66412. };
  66413. return Hinge2Joint;
  66414. }(MotorEnabledJoint));
  66415. BABYLON.Hinge2Joint = Hinge2Joint;
  66416. })(BABYLON || (BABYLON = {}));
  66417. //# sourceMappingURL=babylon.physicsJoint.js.map
  66418. var BABYLON;
  66419. (function (BABYLON) {
  66420. var PhysicsImpostor = /** @class */ (function () {
  66421. function PhysicsImpostor(object, type, _options, _scene) {
  66422. if (_options === void 0) { _options = { mass: 0 }; }
  66423. var _this = this;
  66424. this.object = object;
  66425. this.type = type;
  66426. this._options = _options;
  66427. this._scene = _scene;
  66428. this._bodyUpdateRequired = false;
  66429. this._onBeforePhysicsStepCallbacks = new Array();
  66430. this._onAfterPhysicsStepCallbacks = new Array();
  66431. this._onPhysicsCollideCallbacks = [];
  66432. this._deltaPosition = BABYLON.Vector3.Zero();
  66433. this._isDisposed = false;
  66434. //temp variables for parent rotation calculations
  66435. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  66436. this._tmpQuat = new BABYLON.Quaternion();
  66437. this._tmpQuat2 = new BABYLON.Quaternion();
  66438. /**
  66439. * this function is executed by the physics engine.
  66440. */
  66441. this.beforeStep = function () {
  66442. if (!_this._physicsEngine) {
  66443. return;
  66444. }
  66445. _this.object.translate(_this._deltaPosition, -1);
  66446. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  66447. _this.object.computeWorldMatrix(false);
  66448. if (_this.object.parent && _this.object.rotationQuaternion) {
  66449. _this.getParentsRotation();
  66450. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  66451. }
  66452. else {
  66453. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  66454. }
  66455. if (!_this._options.disableBidirectionalTransformation) {
  66456. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  66457. }
  66458. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  66459. func(_this);
  66460. });
  66461. };
  66462. /**
  66463. * this function is executed by the physics engine.
  66464. */
  66465. this.afterStep = function () {
  66466. if (!_this._physicsEngine) {
  66467. return;
  66468. }
  66469. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  66470. func(_this);
  66471. });
  66472. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  66473. // object has now its world rotation. needs to be converted to local.
  66474. if (_this.object.parent && _this.object.rotationQuaternion) {
  66475. _this.getParentsRotation();
  66476. _this._tmpQuat.conjugateInPlace();
  66477. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  66478. }
  66479. // take the position set and make it the absolute position of this object.
  66480. _this.object.setAbsolutePosition(_this.object.position);
  66481. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  66482. _this.object.translate(_this._deltaPosition, 1);
  66483. };
  66484. /**
  66485. * Legacy collision detection event support
  66486. */
  66487. this.onCollideEvent = null;
  66488. //event and body object due to cannon's event-based architecture.
  66489. this.onCollide = function (e) {
  66490. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  66491. return;
  66492. }
  66493. if (!_this._physicsEngine) {
  66494. return;
  66495. }
  66496. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  66497. if (otherImpostor) {
  66498. // Legacy collision detection event support
  66499. if (_this.onCollideEvent) {
  66500. _this.onCollideEvent(_this, otherImpostor);
  66501. }
  66502. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  66503. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  66504. }).forEach(function (obj) {
  66505. obj.callback(_this, otherImpostor);
  66506. });
  66507. }
  66508. };
  66509. //sanity check!
  66510. if (!this.object) {
  66511. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  66512. return;
  66513. }
  66514. //legacy support for old syntax.
  66515. if (!this._scene && object.getScene) {
  66516. this._scene = object.getScene();
  66517. }
  66518. if (!this._scene) {
  66519. return;
  66520. }
  66521. this._physicsEngine = this._scene.getPhysicsEngine();
  66522. if (!this._physicsEngine) {
  66523. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  66524. }
  66525. else {
  66526. //set the object's quaternion, if not set
  66527. if (!this.object.rotationQuaternion) {
  66528. if (this.object.rotation) {
  66529. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  66530. }
  66531. else {
  66532. this.object.rotationQuaternion = new BABYLON.Quaternion();
  66533. }
  66534. }
  66535. //default options params
  66536. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  66537. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  66538. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  66539. this._joints = [];
  66540. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  66541. if (!this.object.parent || this._options.ignoreParent) {
  66542. this._init();
  66543. }
  66544. else if (this.object.parent.physicsImpostor) {
  66545. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  66546. }
  66547. }
  66548. }
  66549. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  66550. get: function () {
  66551. return this._isDisposed;
  66552. },
  66553. enumerable: true,
  66554. configurable: true
  66555. });
  66556. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  66557. get: function () {
  66558. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  66559. },
  66560. set: function (value) {
  66561. this.setMass(value);
  66562. },
  66563. enumerable: true,
  66564. configurable: true
  66565. });
  66566. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  66567. get: function () {
  66568. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  66569. },
  66570. set: function (value) {
  66571. if (!this._physicsEngine) {
  66572. return;
  66573. }
  66574. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  66575. },
  66576. enumerable: true,
  66577. configurable: true
  66578. });
  66579. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66580. get: function () {
  66581. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66582. },
  66583. set: function (value) {
  66584. if (!this._physicsEngine) {
  66585. return;
  66586. }
  66587. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66588. },
  66589. enumerable: true,
  66590. configurable: true
  66591. });
  66592. /**
  66593. * This function will completly initialize this impostor.
  66594. * It will create a new body - but only if this mesh has no parent.
  66595. * If it has, this impostor will not be used other than to define the impostor
  66596. * of the child mesh.
  66597. */
  66598. PhysicsImpostor.prototype._init = function () {
  66599. if (!this._physicsEngine) {
  66600. return;
  66601. }
  66602. this._physicsEngine.removeImpostor(this);
  66603. this.physicsBody = null;
  66604. this._parent = this._parent || this._getPhysicsParent();
  66605. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  66606. this._physicsEngine.addImpostor(this);
  66607. }
  66608. };
  66609. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66610. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66611. var parentMesh = this.object.parent;
  66612. return parentMesh.physicsImpostor;
  66613. }
  66614. return null;
  66615. };
  66616. /**
  66617. * Should a new body be generated.
  66618. */
  66619. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66620. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66621. };
  66622. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66623. this.forceUpdate();
  66624. };
  66625. /**
  66626. * Force a regeneration of this or the parent's impostor's body.
  66627. * Use under cautious - This will remove all joints already implemented.
  66628. */
  66629. PhysicsImpostor.prototype.forceUpdate = function () {
  66630. this._init();
  66631. if (this.parent && !this._options.ignoreParent) {
  66632. this.parent.forceUpdate();
  66633. }
  66634. };
  66635. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66636. /*public get mesh(): AbstractMesh {
  66637. return this._mesh;
  66638. }*/
  66639. /**
  66640. * Gets the body that holds this impostor. Either its own, or its parent.
  66641. */
  66642. get: function () {
  66643. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66644. },
  66645. /**
  66646. * Set the physics body. Used mainly by the physics engine/plugin
  66647. */
  66648. set: function (physicsBody) {
  66649. if (this._physicsBody && this._physicsEngine) {
  66650. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66651. }
  66652. this._physicsBody = physicsBody;
  66653. this.resetUpdateFlags();
  66654. },
  66655. enumerable: true,
  66656. configurable: true
  66657. });
  66658. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66659. get: function () {
  66660. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66661. },
  66662. set: function (value) {
  66663. this._parent = value;
  66664. },
  66665. enumerable: true,
  66666. configurable: true
  66667. });
  66668. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66669. this._bodyUpdateRequired = false;
  66670. };
  66671. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66672. if (this.object.getBoundingInfo) {
  66673. var q = this.object.rotationQuaternion;
  66674. //reset rotation
  66675. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66676. //calculate the world matrix with no rotation
  66677. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66678. var boundingInfo = this.object.getBoundingInfo();
  66679. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66680. //bring back the rotation
  66681. this.object.rotationQuaternion = q;
  66682. //calculate the world matrix with the new rotation
  66683. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66684. return size;
  66685. }
  66686. else {
  66687. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66688. }
  66689. };
  66690. PhysicsImpostor.prototype.getObjectCenter = function () {
  66691. if (this.object.getBoundingInfo) {
  66692. var boundingInfo = this.object.getBoundingInfo();
  66693. return boundingInfo.boundingBox.centerWorld;
  66694. }
  66695. else {
  66696. return this.object.position;
  66697. }
  66698. };
  66699. /**
  66700. * Get a specific parametes from the options parameter.
  66701. */
  66702. PhysicsImpostor.prototype.getParam = function (paramName) {
  66703. return this._options[paramName];
  66704. };
  66705. /**
  66706. * Sets a specific parameter in the options given to the physics plugin
  66707. */
  66708. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66709. this._options[paramName] = value;
  66710. this._bodyUpdateRequired = true;
  66711. };
  66712. /**
  66713. * Specifically change the body's mass option. Won't recreate the physics body object
  66714. */
  66715. PhysicsImpostor.prototype.setMass = function (mass) {
  66716. if (this.getParam("mass") !== mass) {
  66717. this.setParam("mass", mass);
  66718. }
  66719. if (this._physicsEngine) {
  66720. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66721. }
  66722. };
  66723. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66724. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66725. };
  66726. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66727. if (this._physicsEngine) {
  66728. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66729. }
  66730. };
  66731. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66732. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66733. };
  66734. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66735. if (this._physicsEngine) {
  66736. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66737. }
  66738. };
  66739. /**
  66740. * Execute a function with the physics plugin native code.
  66741. * Provide a function the will have two variables - the world object and the physics body object.
  66742. */
  66743. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66744. if (this._physicsEngine) {
  66745. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66746. }
  66747. };
  66748. /**
  66749. * Register a function that will be executed before the physics world is stepping forward.
  66750. */
  66751. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66752. this._onBeforePhysicsStepCallbacks.push(func);
  66753. };
  66754. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66755. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66756. if (index > -1) {
  66757. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66758. }
  66759. else {
  66760. BABYLON.Tools.Warn("Function to remove was not found");
  66761. }
  66762. };
  66763. /**
  66764. * Register a function that will be executed after the physics step
  66765. */
  66766. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66767. this._onAfterPhysicsStepCallbacks.push(func);
  66768. };
  66769. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66770. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66771. if (index > -1) {
  66772. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66773. }
  66774. else {
  66775. BABYLON.Tools.Warn("Function to remove was not found");
  66776. }
  66777. };
  66778. /**
  66779. * register a function that will be executed when this impostor collides against a different body.
  66780. */
  66781. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66782. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66783. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66784. };
  66785. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66786. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66787. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66788. if (index > -1) {
  66789. this._onPhysicsCollideCallbacks.splice(index, 1);
  66790. }
  66791. else {
  66792. BABYLON.Tools.Warn("Function to remove was not found");
  66793. }
  66794. };
  66795. PhysicsImpostor.prototype.getParentsRotation = function () {
  66796. var parent = this.object.parent;
  66797. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66798. while (parent) {
  66799. if (parent.rotationQuaternion) {
  66800. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66801. }
  66802. else {
  66803. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66804. }
  66805. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66806. parent = parent.parent;
  66807. }
  66808. return this._tmpQuat;
  66809. };
  66810. /**
  66811. * Apply a force
  66812. */
  66813. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66814. if (this._physicsEngine) {
  66815. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66816. }
  66817. return this;
  66818. };
  66819. /**
  66820. * Apply an impulse
  66821. */
  66822. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66823. if (this._physicsEngine) {
  66824. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66825. }
  66826. return this;
  66827. };
  66828. /**
  66829. * A help function to create a joint.
  66830. */
  66831. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66832. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66833. this.addJoint(otherImpostor, joint);
  66834. return this;
  66835. };
  66836. /**
  66837. * Add a joint to this impostor with a different impostor.
  66838. */
  66839. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66840. this._joints.push({
  66841. otherImpostor: otherImpostor,
  66842. joint: joint
  66843. });
  66844. if (this._physicsEngine) {
  66845. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66846. }
  66847. return this;
  66848. };
  66849. /**
  66850. * Will keep this body still, in a sleep mode.
  66851. */
  66852. PhysicsImpostor.prototype.sleep = function () {
  66853. if (this._physicsEngine) {
  66854. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66855. }
  66856. return this;
  66857. };
  66858. /**
  66859. * Wake the body up.
  66860. */
  66861. PhysicsImpostor.prototype.wakeUp = function () {
  66862. if (this._physicsEngine) {
  66863. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66864. }
  66865. return this;
  66866. };
  66867. PhysicsImpostor.prototype.clone = function (newObject) {
  66868. if (!newObject)
  66869. return null;
  66870. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66871. };
  66872. PhysicsImpostor.prototype.dispose = function () {
  66873. var _this = this;
  66874. //no dispose if no physics engine is available.
  66875. if (!this._physicsEngine) {
  66876. return;
  66877. }
  66878. this._joints.forEach(function (j) {
  66879. if (_this._physicsEngine) {
  66880. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66881. }
  66882. });
  66883. //dispose the physics body
  66884. this._physicsEngine.removeImpostor(this);
  66885. if (this.parent) {
  66886. this.parent.forceUpdate();
  66887. }
  66888. else {
  66889. /*this._object.getChildMeshes().forEach(function(mesh) {
  66890. if (mesh.physicsImpostor) {
  66891. if (disposeChildren) {
  66892. mesh.physicsImpostor.dispose();
  66893. mesh.physicsImpostor = null;
  66894. }
  66895. }
  66896. })*/
  66897. }
  66898. this._isDisposed = true;
  66899. };
  66900. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66901. this._deltaPosition.copyFrom(position);
  66902. };
  66903. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66904. if (!this._deltaRotation) {
  66905. this._deltaRotation = new BABYLON.Quaternion();
  66906. }
  66907. this._deltaRotation.copyFrom(rotation);
  66908. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66909. };
  66910. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66911. if (this._physicsEngine) {
  66912. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66913. }
  66914. return this;
  66915. };
  66916. PhysicsImpostor.prototype.getRadius = function () {
  66917. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66918. };
  66919. /**
  66920. * Sync a bone with this impostor
  66921. * @param bone The bone to sync to the impostor.
  66922. * @param boneMesh The mesh that the bone is influencing.
  66923. * @param jointPivot The pivot of the joint / bone in local space.
  66924. * @param distToJoint Optional distance from the impostor to the joint.
  66925. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66926. */
  66927. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66928. var tempVec = PhysicsImpostor._tmpVecs[0];
  66929. var mesh = this.object;
  66930. if (mesh.rotationQuaternion) {
  66931. if (adjustRotation) {
  66932. var tempQuat = PhysicsImpostor._tmpQuat;
  66933. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66934. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66935. }
  66936. else {
  66937. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66938. }
  66939. }
  66940. tempVec.x = 0;
  66941. tempVec.y = 0;
  66942. tempVec.z = 0;
  66943. if (jointPivot) {
  66944. tempVec.x = jointPivot.x;
  66945. tempVec.y = jointPivot.y;
  66946. tempVec.z = jointPivot.z;
  66947. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66948. if (distToJoint === undefined || distToJoint === null) {
  66949. distToJoint = jointPivot.length();
  66950. }
  66951. tempVec.x *= distToJoint;
  66952. tempVec.y *= distToJoint;
  66953. tempVec.z *= distToJoint;
  66954. }
  66955. if (bone.getParent()) {
  66956. tempVec.addInPlace(mesh.getAbsolutePosition());
  66957. bone.setAbsolutePosition(tempVec, boneMesh);
  66958. }
  66959. else {
  66960. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66961. boneMesh.position.x -= tempVec.x;
  66962. boneMesh.position.y -= tempVec.y;
  66963. boneMesh.position.z -= tempVec.z;
  66964. }
  66965. };
  66966. /**
  66967. * Sync impostor to a bone
  66968. * @param bone The bone that the impostor will be synced to.
  66969. * @param boneMesh The mesh that the bone is influencing.
  66970. * @param jointPivot The pivot of the joint / bone in local space.
  66971. * @param distToJoint Optional distance from the impostor to the joint.
  66972. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66973. * @param boneAxis Optional vector3 axis the bone is aligned with
  66974. */
  66975. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66976. var mesh = this.object;
  66977. if (mesh.rotationQuaternion) {
  66978. if (adjustRotation) {
  66979. var tempQuat = PhysicsImpostor._tmpQuat;
  66980. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66981. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66982. }
  66983. else {
  66984. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66985. }
  66986. }
  66987. var pos = PhysicsImpostor._tmpVecs[0];
  66988. var boneDir = PhysicsImpostor._tmpVecs[1];
  66989. if (!boneAxis) {
  66990. boneAxis = PhysicsImpostor._tmpVecs[2];
  66991. boneAxis.x = 0;
  66992. boneAxis.y = 1;
  66993. boneAxis.z = 0;
  66994. }
  66995. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66996. bone.getAbsolutePositionToRef(boneMesh, pos);
  66997. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66998. distToJoint = jointPivot.length();
  66999. }
  67000. if (distToJoint !== undefined && distToJoint !== null) {
  67001. pos.x += boneDir.x * distToJoint;
  67002. pos.y += boneDir.y * distToJoint;
  67003. pos.z += boneDir.z * distToJoint;
  67004. }
  67005. mesh.setAbsolutePosition(pos);
  67006. };
  67007. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  67008. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  67009. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67010. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  67011. //Impostor types
  67012. PhysicsImpostor.NoImpostor = 0;
  67013. PhysicsImpostor.SphereImpostor = 1;
  67014. PhysicsImpostor.BoxImpostor = 2;
  67015. PhysicsImpostor.PlaneImpostor = 3;
  67016. PhysicsImpostor.MeshImpostor = 4;
  67017. PhysicsImpostor.CylinderImpostor = 7;
  67018. PhysicsImpostor.ParticleImpostor = 8;
  67019. PhysicsImpostor.HeightmapImpostor = 9;
  67020. return PhysicsImpostor;
  67021. }());
  67022. BABYLON.PhysicsImpostor = PhysicsImpostor;
  67023. })(BABYLON || (BABYLON = {}));
  67024. //# sourceMappingURL=babylon.physicsImpostor.js.map
  67025. var BABYLON;
  67026. (function (BABYLON) {
  67027. var PhysicsEngine = /** @class */ (function () {
  67028. function PhysicsEngine(gravity, _physicsPlugin) {
  67029. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  67030. this._physicsPlugin = _physicsPlugin;
  67031. //new methods and parameters
  67032. this._impostors = [];
  67033. this._joints = [];
  67034. if (!this._physicsPlugin.isSupported()) {
  67035. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  67036. + "Please make sure it is included.");
  67037. }
  67038. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  67039. this.setGravity(gravity);
  67040. this.setTimeStep();
  67041. }
  67042. PhysicsEngine.prototype.setGravity = function (gravity) {
  67043. this.gravity = gravity;
  67044. this._physicsPlugin.setGravity(this.gravity);
  67045. };
  67046. /**
  67047. * Set the time step of the physics engine.
  67048. * default is 1/60.
  67049. * To slow it down, enter 1/600 for example.
  67050. * To speed it up, 1/30
  67051. * @param {number} newTimeStep the new timestep to apply to this world.
  67052. */
  67053. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  67054. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  67055. this._physicsPlugin.setTimeStep(newTimeStep);
  67056. };
  67057. /**
  67058. * Get the time step of the physics engine.
  67059. */
  67060. PhysicsEngine.prototype.getTimeStep = function () {
  67061. return this._physicsPlugin.getTimeStep();
  67062. };
  67063. PhysicsEngine.prototype.dispose = function () {
  67064. this._impostors.forEach(function (impostor) {
  67065. impostor.dispose();
  67066. });
  67067. this._physicsPlugin.dispose();
  67068. };
  67069. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  67070. return this._physicsPlugin.name;
  67071. };
  67072. /**
  67073. * Adding a new impostor for the impostor tracking.
  67074. * This will be done by the impostor itself.
  67075. * @param {PhysicsImpostor} impostor the impostor to add
  67076. */
  67077. PhysicsEngine.prototype.addImpostor = function (impostor) {
  67078. impostor.uniqueId = this._impostors.push(impostor);
  67079. //if no parent, generate the body
  67080. if (!impostor.parent) {
  67081. this._physicsPlugin.generatePhysicsBody(impostor);
  67082. }
  67083. };
  67084. /**
  67085. * Remove an impostor from the engine.
  67086. * This impostor and its mesh will not longer be updated by the physics engine.
  67087. * @param {PhysicsImpostor} impostor the impostor to remove
  67088. */
  67089. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  67090. var index = this._impostors.indexOf(impostor);
  67091. if (index > -1) {
  67092. var removed = this._impostors.splice(index, 1);
  67093. //Is it needed?
  67094. if (removed.length) {
  67095. //this will also remove it from the world.
  67096. removed[0].physicsBody = null;
  67097. }
  67098. }
  67099. };
  67100. /**
  67101. * Add a joint to the physics engine
  67102. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  67103. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  67104. * @param {PhysicsJoint} the joint that will connect both impostors.
  67105. */
  67106. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  67107. var impostorJoint = {
  67108. mainImpostor: mainImpostor,
  67109. connectedImpostor: connectedImpostor,
  67110. joint: joint
  67111. };
  67112. joint.physicsPlugin = this._physicsPlugin;
  67113. this._joints.push(impostorJoint);
  67114. this._physicsPlugin.generateJoint(impostorJoint);
  67115. };
  67116. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  67117. var matchingJoints = this._joints.filter(function (impostorJoint) {
  67118. return (impostorJoint.connectedImpostor === connectedImpostor
  67119. && impostorJoint.joint === joint
  67120. && impostorJoint.mainImpostor === mainImpostor);
  67121. });
  67122. if (matchingJoints.length) {
  67123. this._physicsPlugin.removeJoint(matchingJoints[0]);
  67124. //TODO remove it from the list as well
  67125. }
  67126. };
  67127. /**
  67128. * Called by the scene. no need to call it.
  67129. */
  67130. PhysicsEngine.prototype._step = function (delta) {
  67131. var _this = this;
  67132. //check if any mesh has no body / requires an update
  67133. this._impostors.forEach(function (impostor) {
  67134. if (impostor.isBodyInitRequired()) {
  67135. _this._physicsPlugin.generatePhysicsBody(impostor);
  67136. }
  67137. });
  67138. if (delta > 0.1) {
  67139. delta = 0.1;
  67140. }
  67141. else if (delta <= 0) {
  67142. delta = 1.0 / 60.0;
  67143. }
  67144. this._physicsPlugin.executeStep(delta, this._impostors);
  67145. };
  67146. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  67147. return this._physicsPlugin;
  67148. };
  67149. PhysicsEngine.prototype.getImpostors = function () {
  67150. return this._impostors;
  67151. };
  67152. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  67153. for (var i = 0; i < this._impostors.length; ++i) {
  67154. if (this._impostors[i].object === object) {
  67155. return this._impostors[i];
  67156. }
  67157. }
  67158. return null;
  67159. };
  67160. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  67161. for (var i = 0; i < this._impostors.length; ++i) {
  67162. if (this._impostors[i].physicsBody === body) {
  67163. return this._impostors[i];
  67164. }
  67165. }
  67166. return null;
  67167. };
  67168. // Statics
  67169. PhysicsEngine.Epsilon = 0.001;
  67170. return PhysicsEngine;
  67171. }());
  67172. BABYLON.PhysicsEngine = PhysicsEngine;
  67173. })(BABYLON || (BABYLON = {}));
  67174. //# sourceMappingURL=babylon.physicsEngine.js.map
  67175. var BABYLON;
  67176. (function (BABYLON) {
  67177. /**
  67178. * The strenght of the force in correspondence to the distance of the affected object
  67179. */
  67180. var PhysicsRadialImpulseFalloff;
  67181. (function (PhysicsRadialImpulseFalloff) {
  67182. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  67183. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  67184. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  67185. /**
  67186. * The strenght of the force in correspondence to the distance of the affected object
  67187. */
  67188. var PhysicsUpdraftMode;
  67189. (function (PhysicsUpdraftMode) {
  67190. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  67191. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  67192. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  67193. var PhysicsHelper = /** @class */ (function () {
  67194. function PhysicsHelper(scene) {
  67195. this._scene = scene;
  67196. this._physicsEngine = this._scene.getPhysicsEngine();
  67197. if (!this._physicsEngine) {
  67198. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  67199. }
  67200. }
  67201. /**
  67202. * @param {Vector3} origin the origin of the explosion
  67203. * @param {number} radius the explosion radius
  67204. * @param {number} strength the explosion strength
  67205. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67206. */
  67207. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  67208. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67209. if (!this._physicsEngine) {
  67210. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  67211. return null;
  67212. }
  67213. var impostors = this._physicsEngine.getImpostors();
  67214. if (impostors.length === 0) {
  67215. return null;
  67216. }
  67217. var event = new PhysicsRadialExplosionEvent(this._scene);
  67218. impostors.forEach(function (impostor) {
  67219. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67220. if (!impostorForceAndContactPoint) {
  67221. return;
  67222. }
  67223. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67224. });
  67225. event.dispose(false);
  67226. return event;
  67227. };
  67228. /**
  67229. * @param {Vector3} origin the origin of the explosion
  67230. * @param {number} radius the explosion radius
  67231. * @param {number} strength the explosion strength
  67232. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67233. */
  67234. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  67235. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67236. if (!this._physicsEngine) {
  67237. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67238. return null;
  67239. }
  67240. var impostors = this._physicsEngine.getImpostors();
  67241. if (impostors.length === 0) {
  67242. return null;
  67243. }
  67244. var event = new PhysicsRadialExplosionEvent(this._scene);
  67245. impostors.forEach(function (impostor) {
  67246. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  67247. if (!impostorForceAndContactPoint) {
  67248. return;
  67249. }
  67250. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67251. });
  67252. event.dispose(false);
  67253. return event;
  67254. };
  67255. /**
  67256. * @param {Vector3} origin the origin of the explosion
  67257. * @param {number} radius the explosion radius
  67258. * @param {number} strength the explosion strength
  67259. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67260. */
  67261. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  67262. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67263. if (!this._physicsEngine) {
  67264. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67265. return null;
  67266. }
  67267. var impostors = this._physicsEngine.getImpostors();
  67268. if (impostors.length === 0) {
  67269. return null;
  67270. }
  67271. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  67272. event.dispose(false);
  67273. return event;
  67274. };
  67275. /**
  67276. * @param {Vector3} origin the origin of the updraft
  67277. * @param {number} radius the radius of the updraft
  67278. * @param {number} strength the strength of the updraft
  67279. * @param {number} height the height of the updraft
  67280. */
  67281. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  67282. if (!this._physicsEngine) {
  67283. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  67284. return null;
  67285. }
  67286. if (this._physicsEngine.getImpostors().length === 0) {
  67287. return null;
  67288. }
  67289. var event = new PhysicsUpdraftEvent(this._physicsEngine, this._scene, origin, radius, strength, height, updraftMode);
  67290. event.dispose(false);
  67291. return event;
  67292. };
  67293. return PhysicsHelper;
  67294. }());
  67295. BABYLON.PhysicsHelper = PhysicsHelper;
  67296. /***** Radial explosion *****/
  67297. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  67298. function PhysicsRadialExplosionEvent(scene) {
  67299. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  67300. this._rays = [];
  67301. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  67302. this._scene = scene;
  67303. }
  67304. /**
  67305. * Returns the data related to the radial explosion event (sphere & rays).
  67306. * @returns {PhysicsRadialExplosionEventData}
  67307. */
  67308. PhysicsRadialExplosionEvent.prototype.getData = function () {
  67309. this._dataFetched = true;
  67310. return {
  67311. sphere: this._sphere,
  67312. rays: this._rays,
  67313. };
  67314. };
  67315. /**
  67316. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  67317. * @param impostor
  67318. * @param {Vector3} origin the origin of the explosion
  67319. * @param {number} radius the explosion radius
  67320. * @param {number} strength the explosion strength
  67321. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  67322. * @returns {Nullable<PhysicsForceAndContactPoint>}
  67323. */
  67324. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  67325. if (impostor.mass === 0) {
  67326. return null;
  67327. }
  67328. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  67329. return null;
  67330. }
  67331. var impostorObject = impostor.object;
  67332. var impostorObjectCenter = impostor.getObjectCenter();
  67333. var direction = impostorObjectCenter.subtract(origin);
  67334. var ray = new BABYLON.Ray(origin, direction, radius);
  67335. this._rays.push(ray);
  67336. var hit = ray.intersectsMesh(impostorObject);
  67337. var contactPoint = hit.pickedPoint;
  67338. if (!contactPoint) {
  67339. return null;
  67340. }
  67341. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  67342. if (distanceFromOrigin > radius) {
  67343. return null;
  67344. }
  67345. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  67346. ? strength
  67347. : strength * (1 - (distanceFromOrigin / radius));
  67348. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67349. return { force: force, contactPoint: contactPoint };
  67350. };
  67351. /**
  67352. * Disposes the sphere.
  67353. * @param {bolean} force
  67354. */
  67355. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  67356. var _this = this;
  67357. if (force === void 0) { force = true; }
  67358. if (force) {
  67359. this._sphere.dispose();
  67360. }
  67361. else {
  67362. setTimeout(function () {
  67363. if (!_this._dataFetched) {
  67364. _this._sphere.dispose();
  67365. }
  67366. }, 0);
  67367. }
  67368. };
  67369. /*** Helpers ***/
  67370. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  67371. if (!this._sphere) {
  67372. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  67373. this._sphere.isVisible = false;
  67374. }
  67375. };
  67376. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  67377. var impostorObject = impostor.object;
  67378. this._prepareSphere();
  67379. this._sphere.position = origin;
  67380. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  67381. this._sphere._updateBoundingInfo();
  67382. this._sphere.computeWorldMatrix(true);
  67383. return this._sphere.intersectsMesh(impostorObject, true);
  67384. };
  67385. return PhysicsRadialExplosionEvent;
  67386. }());
  67387. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  67388. /***** Gravitational Field *****/
  67389. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  67390. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  67391. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  67392. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67393. this._physicsHelper = physicsHelper;
  67394. this._scene = scene;
  67395. this._origin = origin;
  67396. this._radius = radius;
  67397. this._strength = strength;
  67398. this._falloff = falloff;
  67399. this._tickCallback = this._tick.bind(this);
  67400. }
  67401. /**
  67402. * Returns the data related to the gravitational field event (sphere).
  67403. * @returns {PhysicsGravitationalFieldEventData}
  67404. */
  67405. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  67406. this._dataFetched = true;
  67407. return {
  67408. sphere: this._sphere,
  67409. };
  67410. };
  67411. /**
  67412. * Enables the gravitational field.
  67413. */
  67414. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  67415. this._tickCallback.call(this);
  67416. this._scene.registerBeforeRender(this._tickCallback);
  67417. };
  67418. /**
  67419. * Disables the gravitational field.
  67420. */
  67421. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  67422. this._scene.unregisterBeforeRender(this._tickCallback);
  67423. };
  67424. /**
  67425. * Disposes the sphere.
  67426. * @param {bolean} force
  67427. */
  67428. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  67429. var _this = this;
  67430. if (force === void 0) { force = true; }
  67431. if (force) {
  67432. this._sphere.dispose();
  67433. }
  67434. else {
  67435. setTimeout(function () {
  67436. if (!_this._dataFetched) {
  67437. _this._sphere.dispose();
  67438. }
  67439. }, 0);
  67440. }
  67441. };
  67442. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  67443. // Since the params won't change, we fetch the event only once
  67444. if (this._sphere) {
  67445. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67446. }
  67447. else {
  67448. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  67449. if (radialExplosionEvent) {
  67450. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  67451. }
  67452. }
  67453. };
  67454. return PhysicsGravitationalFieldEvent;
  67455. }());
  67456. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  67457. /***** Updraft *****/
  67458. var PhysicsUpdraftEvent = /** @class */ (function () {
  67459. function PhysicsUpdraftEvent(physicsEngine, scene, origin, radius, strength, height, updraftMode) {
  67460. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  67461. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  67462. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  67463. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  67464. this._physicsEngine = physicsEngine;
  67465. this._scene = scene;
  67466. this._origin = origin;
  67467. this._radius = radius;
  67468. this._strength = strength;
  67469. this._height = height;
  67470. this._updraftMode = updraftMode;
  67471. // TODO: for this._cylinderPosition & this._originTop, take rotation into account
  67472. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  67473. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  67474. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67475. this._originDirection = this._origin.subtract(this._originTop).normalize();
  67476. }
  67477. this._tickCallback = this._tick.bind(this);
  67478. }
  67479. /**
  67480. * Returns the data related to the updraft event (cylinder).
  67481. * @returns {PhysicsGravitationalFieldEventData}
  67482. */
  67483. PhysicsUpdraftEvent.prototype.getData = function () {
  67484. this._dataFetched = true;
  67485. return {
  67486. cylinder: this._cylinder,
  67487. };
  67488. };
  67489. /**
  67490. * Enables the updraft.
  67491. */
  67492. PhysicsUpdraftEvent.prototype.enable = function () {
  67493. this._tickCallback.call(this);
  67494. this._scene.registerBeforeRender(this._tickCallback);
  67495. };
  67496. /**
  67497. * Disables the cortex.
  67498. */
  67499. PhysicsUpdraftEvent.prototype.disable = function () {
  67500. this._scene.unregisterBeforeRender(this._tickCallback);
  67501. };
  67502. /**
  67503. * Disposes the sphere.
  67504. * @param {bolean} force
  67505. */
  67506. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  67507. var _this = this;
  67508. if (force === void 0) { force = true; }
  67509. if (force) {
  67510. this._cylinder.dispose();
  67511. }
  67512. else {
  67513. setTimeout(function () {
  67514. if (!_this._dataFetched) {
  67515. _this._cylinder.dispose();
  67516. }
  67517. }, 0);
  67518. }
  67519. };
  67520. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  67521. if (impostor.mass === 0) {
  67522. return null;
  67523. }
  67524. if (!this._intersectsWithCylinder(impostor)) {
  67525. return null;
  67526. }
  67527. var impostorObjectCenter = impostor.getObjectCenter();
  67528. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  67529. var direction = this._originDirection;
  67530. }
  67531. else {
  67532. var direction = impostorObjectCenter.subtract(this._originTop);
  67533. }
  67534. var multiplier = this._strength * -1;
  67535. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  67536. return { force: force, contactPoint: impostorObjectCenter };
  67537. };
  67538. PhysicsUpdraftEvent.prototype._tick = function () {
  67539. var _this = this;
  67540. this._physicsEngine.getImpostors().forEach(function (impostor) {
  67541. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  67542. if (!impostorForceAndContactPoint) {
  67543. return;
  67544. }
  67545. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  67546. });
  67547. };
  67548. /*** Helpers ***/
  67549. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  67550. if (!this._cylinder) {
  67551. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  67552. height: this._height,
  67553. diameter: this._radius * 2,
  67554. }, this._scene);
  67555. this._cylinder.isVisible = false;
  67556. }
  67557. };
  67558. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  67559. var impostorObject = impostor.object;
  67560. this._prepareCylinder();
  67561. this._cylinder.position = this._cylinderPosition;
  67562. return this._cylinder.intersectsMesh(impostorObject, true);
  67563. };
  67564. return PhysicsUpdraftEvent;
  67565. }());
  67566. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  67567. })(BABYLON || (BABYLON = {}));
  67568. //# sourceMappingURL=babylon.physicsHelper.js.map
  67569. var BABYLON;
  67570. (function (BABYLON) {
  67571. var CannonJSPlugin = /** @class */ (function () {
  67572. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  67573. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  67574. if (iterations === void 0) { iterations = 10; }
  67575. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  67576. this.name = "CannonJSPlugin";
  67577. this._physicsMaterials = new Array();
  67578. this._fixedTimeStep = 1 / 60;
  67579. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  67580. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  67581. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  67582. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  67583. this._tmpPosition = BABYLON.Vector3.Zero();
  67584. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  67585. this._tmpUnityRotation = new BABYLON.Quaternion();
  67586. if (!this.isSupported()) {
  67587. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  67588. return;
  67589. }
  67590. this._extendNamespace();
  67591. this.world = new this.BJSCANNON.World();
  67592. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  67593. this.world.solver.iterations = iterations;
  67594. }
  67595. CannonJSPlugin.prototype.setGravity = function (gravity) {
  67596. this.world.gravity.copy(gravity);
  67597. };
  67598. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  67599. this._fixedTimeStep = timeStep;
  67600. };
  67601. CannonJSPlugin.prototype.getTimeStep = function () {
  67602. return this._fixedTimeStep;
  67603. };
  67604. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  67605. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  67606. };
  67607. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67608. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67609. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67610. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  67611. };
  67612. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67613. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  67614. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  67615. impostor.physicsBody.applyForce(impulse, worldPoint);
  67616. };
  67617. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67618. //parent-child relationship. Does this impostor has a parent impostor?
  67619. if (impostor.parent) {
  67620. if (impostor.physicsBody) {
  67621. this.removePhysicsBody(impostor);
  67622. //TODO is that needed?
  67623. impostor.forceUpdate();
  67624. }
  67625. return;
  67626. }
  67627. //should a new body be created for this impostor?
  67628. if (impostor.isBodyInitRequired()) {
  67629. var shape = this._createShape(impostor);
  67630. //unregister events, if body is being changed
  67631. var oldBody = impostor.physicsBody;
  67632. if (oldBody) {
  67633. this.removePhysicsBody(impostor);
  67634. }
  67635. //create the body and material
  67636. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  67637. var bodyCreationObject = {
  67638. mass: impostor.getParam("mass"),
  67639. material: material
  67640. };
  67641. // A simple extend, in case native options were used.
  67642. var nativeOptions = impostor.getParam("nativeOptions");
  67643. for (var key in nativeOptions) {
  67644. if (nativeOptions.hasOwnProperty(key)) {
  67645. bodyCreationObject[key] = nativeOptions[key];
  67646. }
  67647. }
  67648. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  67649. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  67650. this.world.addEventListener("preStep", impostor.beforeStep);
  67651. this.world.addEventListener("postStep", impostor.afterStep);
  67652. impostor.physicsBody.addShape(shape);
  67653. this.world.add(impostor.physicsBody);
  67654. //try to keep the body moving in the right direction by taking old properties.
  67655. //Should be tested!
  67656. if (oldBody) {
  67657. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  67658. impostor.physicsBody[param].copy(oldBody[param]);
  67659. });
  67660. }
  67661. this._processChildMeshes(impostor);
  67662. }
  67663. //now update the body's transformation
  67664. this._updatePhysicsBodyTransformation(impostor);
  67665. };
  67666. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  67667. var _this = this;
  67668. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  67669. var currentRotation = mainImpostor.object.rotationQuaternion;
  67670. if (meshChildren.length) {
  67671. var processMesh = function (localPosition, mesh) {
  67672. if (!currentRotation || !mesh.rotationQuaternion) {
  67673. return;
  67674. }
  67675. var childImpostor = mesh.getPhysicsImpostor();
  67676. if (childImpostor) {
  67677. var parent = childImpostor.parent;
  67678. if (parent !== mainImpostor) {
  67679. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  67680. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  67681. if (childImpostor.physicsBody) {
  67682. _this.removePhysicsBody(childImpostor);
  67683. childImpostor.physicsBody = null;
  67684. }
  67685. childImpostor.parent = mainImpostor;
  67686. childImpostor.resetUpdateFlags();
  67687. 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));
  67688. //Add the mass of the children.
  67689. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  67690. }
  67691. }
  67692. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  67693. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  67694. };
  67695. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  67696. }
  67697. };
  67698. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67699. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  67700. this.world.removeEventListener("preStep", impostor.beforeStep);
  67701. this.world.removeEventListener("postStep", impostor.afterStep);
  67702. this.world.remove(impostor.physicsBody);
  67703. };
  67704. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67705. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67706. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67707. if (!mainBody || !connectedBody) {
  67708. return;
  67709. }
  67710. var constraint;
  67711. var jointData = impostorJoint.joint.jointData;
  67712. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  67713. var constraintData = {
  67714. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  67715. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  67716. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  67717. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  67718. maxForce: jointData.nativeParams.maxForce,
  67719. collideConnected: !!jointData.collision
  67720. };
  67721. switch (impostorJoint.joint.type) {
  67722. case BABYLON.PhysicsJoint.HingeJoint:
  67723. case BABYLON.PhysicsJoint.Hinge2Joint:
  67724. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  67725. break;
  67726. case BABYLON.PhysicsJoint.DistanceJoint:
  67727. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  67728. break;
  67729. case BABYLON.PhysicsJoint.SpringJoint:
  67730. var springData = jointData;
  67731. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  67732. restLength: springData.length,
  67733. stiffness: springData.stiffness,
  67734. damping: springData.damping,
  67735. localAnchorA: constraintData.pivotA,
  67736. localAnchorB: constraintData.pivotB
  67737. });
  67738. break;
  67739. case BABYLON.PhysicsJoint.LockJoint:
  67740. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  67741. break;
  67742. case BABYLON.PhysicsJoint.PointToPointJoint:
  67743. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67744. default:
  67745. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  67746. break;
  67747. }
  67748. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  67749. constraint.collideConnected = !!jointData.collision;
  67750. impostorJoint.joint.physicsJoint = constraint;
  67751. //don't add spring as constraint, as it is not one.
  67752. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  67753. this.world.addConstraint(constraint);
  67754. }
  67755. else {
  67756. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  67757. constraint.applyForce();
  67758. });
  67759. }
  67760. };
  67761. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67762. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  67763. };
  67764. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  67765. var index;
  67766. var mat;
  67767. for (index = 0; index < this._physicsMaterials.length; index++) {
  67768. mat = this._physicsMaterials[index];
  67769. if (mat.friction === friction && mat.restitution === restitution) {
  67770. return mat;
  67771. }
  67772. }
  67773. var currentMat = new this.BJSCANNON.Material(name);
  67774. currentMat.friction = friction;
  67775. currentMat.restitution = restitution;
  67776. this._physicsMaterials.push(currentMat);
  67777. return currentMat;
  67778. };
  67779. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  67780. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  67781. };
  67782. CannonJSPlugin.prototype._createShape = function (impostor) {
  67783. var object = impostor.object;
  67784. var returnValue;
  67785. var extendSize = impostor.getObjectExtendSize();
  67786. switch (impostor.type) {
  67787. case BABYLON.PhysicsImpostor.SphereImpostor:
  67788. var radiusX = extendSize.x;
  67789. var radiusY = extendSize.y;
  67790. var radiusZ = extendSize.z;
  67791. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  67792. break;
  67793. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  67794. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67795. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  67796. break;
  67797. case BABYLON.PhysicsImpostor.BoxImpostor:
  67798. var box = extendSize.scale(0.5);
  67799. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  67800. break;
  67801. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67802. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  67803. returnValue = new this.BJSCANNON.Plane();
  67804. break;
  67805. case BABYLON.PhysicsImpostor.MeshImpostor:
  67806. // should transform the vertex data to world coordinates!!
  67807. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  67808. var rawFaces = object.getIndices ? object.getIndices() : [];
  67809. if (!rawVerts)
  67810. return;
  67811. // get only scale! so the object could transform correctly.
  67812. var oldPosition = object.position.clone();
  67813. var oldRotation = object.rotation && object.rotation.clone();
  67814. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  67815. object.position.copyFromFloats(0, 0, 0);
  67816. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67817. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67818. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67819. var transform = object.computeWorldMatrix(true);
  67820. // convert rawVerts to object space
  67821. var temp = new Array();
  67822. var index;
  67823. for (index = 0; index < rawVerts.length; index += 3) {
  67824. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  67825. }
  67826. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  67827. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  67828. //now set back the transformation!
  67829. object.position.copyFrom(oldPosition);
  67830. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  67831. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  67832. break;
  67833. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  67834. var oldPosition2 = object.position.clone();
  67835. var oldRotation2 = object.rotation && object.rotation.clone();
  67836. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  67837. object.position.copyFromFloats(0, 0, 0);
  67838. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  67839. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  67840. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  67841. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  67842. returnValue = this._createHeightmap(object);
  67843. object.position.copyFrom(oldPosition2);
  67844. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  67845. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  67846. object.computeWorldMatrix(true);
  67847. break;
  67848. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67849. returnValue = new this.BJSCANNON.Particle();
  67850. break;
  67851. }
  67852. return returnValue;
  67853. };
  67854. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  67855. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  67856. var transform = object.computeWorldMatrix(true);
  67857. // convert rawVerts to object space
  67858. var temp = new Array();
  67859. var index;
  67860. for (index = 0; index < pos.length; index += 3) {
  67861. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  67862. }
  67863. pos = temp;
  67864. var matrix = new Array();
  67865. //For now pointDepth will not be used and will be automatically calculated.
  67866. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  67867. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  67868. var boundingInfo = object.getBoundingInfo();
  67869. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  67870. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  67871. var elementSize = dim * 2 / arraySize;
  67872. for (var i = 0; i < pos.length; i = i + 3) {
  67873. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  67874. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  67875. var y = -pos[i + 2] + minY;
  67876. if (!matrix[x]) {
  67877. matrix[x] = [];
  67878. }
  67879. if (!matrix[x][z]) {
  67880. matrix[x][z] = y;
  67881. }
  67882. matrix[x][z] = Math.max(y, matrix[x][z]);
  67883. }
  67884. for (var x = 0; x <= arraySize; ++x) {
  67885. if (!matrix[x]) {
  67886. var loc = 1;
  67887. while (!matrix[(x + loc) % arraySize]) {
  67888. loc++;
  67889. }
  67890. matrix[x] = matrix[(x + loc) % arraySize].slice();
  67891. //console.log("missing x", x);
  67892. }
  67893. for (var z = 0; z <= arraySize; ++z) {
  67894. if (!matrix[x][z]) {
  67895. var loc = 1;
  67896. var newValue;
  67897. while (newValue === undefined) {
  67898. newValue = matrix[x][(z + loc++) % arraySize];
  67899. }
  67900. matrix[x][z] = newValue;
  67901. }
  67902. }
  67903. }
  67904. var shape = new this.BJSCANNON.Heightfield(matrix, {
  67905. elementSize: elementSize
  67906. });
  67907. //For future reference, needed for body transformation
  67908. shape.minY = minY;
  67909. return shape;
  67910. };
  67911. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  67912. var object = impostor.object;
  67913. //make sure it is updated...
  67914. object.computeWorldMatrix && object.computeWorldMatrix(true);
  67915. // The delta between the mesh position and the mesh bounding box center
  67916. var bInfo = object.getBoundingInfo();
  67917. if (!bInfo)
  67918. return;
  67919. var center = impostor.getObjectCenter();
  67920. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  67921. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  67922. this._tmpPosition.copyFrom(center);
  67923. var quaternion = object.rotationQuaternion;
  67924. if (!quaternion) {
  67925. return;
  67926. }
  67927. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  67928. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  67929. //-90 DEG in X, precalculated
  67930. quaternion = quaternion.multiply(this._minus90X);
  67931. //Invert! (Precalculated, 90 deg in X)
  67932. //No need to clone. this will never change.
  67933. impostor.setDeltaRotation(this._plus90X);
  67934. }
  67935. //If it is a heightfield, if should be centered.
  67936. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  67937. var mesh = object;
  67938. var boundingInfo = mesh.getBoundingInfo();
  67939. //calculate the correct body position:
  67940. var rotationQuaternion = mesh.rotationQuaternion;
  67941. mesh.rotationQuaternion = this._tmpUnityRotation;
  67942. mesh.computeWorldMatrix(true);
  67943. //get original center with no rotation
  67944. var c = center.clone();
  67945. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  67946. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  67947. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  67948. mesh.setPivotMatrix(p);
  67949. mesh.computeWorldMatrix(true);
  67950. //calculate the translation
  67951. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  67952. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  67953. //add it inverted to the delta
  67954. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  67955. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  67956. //rotation is back
  67957. mesh.rotationQuaternion = rotationQuaternion;
  67958. mesh.setPivotMatrix(oldPivot);
  67959. mesh.computeWorldMatrix(true);
  67960. }
  67961. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  67962. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  67963. //this._tmpPosition.copyFrom(object.position);
  67964. }
  67965. impostor.setDeltaPosition(this._tmpDeltaPosition);
  67966. //Now update the impostor object
  67967. impostor.physicsBody.position.copy(this._tmpPosition);
  67968. impostor.physicsBody.quaternion.copy(quaternion);
  67969. };
  67970. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67971. impostor.object.position.copyFrom(impostor.physicsBody.position);
  67972. if (impostor.object.rotationQuaternion) {
  67973. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  67974. }
  67975. };
  67976. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67977. impostor.physicsBody.position.copy(newPosition);
  67978. impostor.physicsBody.quaternion.copy(newRotation);
  67979. };
  67980. CannonJSPlugin.prototype.isSupported = function () {
  67981. return this.BJSCANNON !== undefined;
  67982. };
  67983. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67984. impostor.physicsBody.velocity.copy(velocity);
  67985. };
  67986. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67987. impostor.physicsBody.angularVelocity.copy(velocity);
  67988. };
  67989. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67990. var v = impostor.physicsBody.velocity;
  67991. if (!v) {
  67992. return null;
  67993. }
  67994. return new BABYLON.Vector3(v.x, v.y, v.z);
  67995. };
  67996. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67997. var v = impostor.physicsBody.angularVelocity;
  67998. if (!v) {
  67999. return null;
  68000. }
  68001. return new BABYLON.Vector3(v.x, v.y, v.z);
  68002. };
  68003. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68004. impostor.physicsBody.mass = mass;
  68005. impostor.physicsBody.updateMassProperties();
  68006. };
  68007. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  68008. return impostor.physicsBody.mass;
  68009. };
  68010. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  68011. return impostor.physicsBody.material.friction;
  68012. };
  68013. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68014. impostor.physicsBody.material.friction = friction;
  68015. };
  68016. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68017. return impostor.physicsBody.material.restitution;
  68018. };
  68019. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68020. impostor.physicsBody.material.restitution = restitution;
  68021. };
  68022. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  68023. impostor.physicsBody.sleep();
  68024. };
  68025. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  68026. impostor.physicsBody.wakeUp();
  68027. };
  68028. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68029. joint.physicsJoint.distance = maxDistance;
  68030. };
  68031. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68032. // if (!motorIndex) {
  68033. // joint.physicsJoint.enableMotor();
  68034. // }
  68035. // }
  68036. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68037. // if (!motorIndex) {
  68038. // joint.physicsJoint.disableMotor();
  68039. // }
  68040. // }
  68041. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68042. if (!motorIndex) {
  68043. joint.physicsJoint.enableMotor();
  68044. joint.physicsJoint.setMotorSpeed(speed);
  68045. if (maxForce) {
  68046. this.setLimit(joint, maxForce);
  68047. }
  68048. }
  68049. };
  68050. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  68051. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  68052. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  68053. };
  68054. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68055. var body = impostor.physicsBody;
  68056. mesh.position.x = body.position.x;
  68057. mesh.position.y = body.position.y;
  68058. mesh.position.z = body.position.z;
  68059. if (mesh.rotationQuaternion) {
  68060. mesh.rotationQuaternion.x = body.quaternion.x;
  68061. mesh.rotationQuaternion.y = body.quaternion.y;
  68062. mesh.rotationQuaternion.z = body.quaternion.z;
  68063. mesh.rotationQuaternion.w = body.quaternion.w;
  68064. }
  68065. };
  68066. CannonJSPlugin.prototype.getRadius = function (impostor) {
  68067. var shape = impostor.physicsBody.shapes[0];
  68068. return shape.boundingSphereRadius;
  68069. };
  68070. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68071. var shape = impostor.physicsBody.shapes[0];
  68072. result.x = shape.halfExtents.x * 2;
  68073. result.y = shape.halfExtents.y * 2;
  68074. result.z = shape.halfExtents.z * 2;
  68075. };
  68076. CannonJSPlugin.prototype.dispose = function () {
  68077. };
  68078. CannonJSPlugin.prototype._extendNamespace = function () {
  68079. //this will force cannon to execute at least one step when using interpolation
  68080. var step_tmp1 = new this.BJSCANNON.Vec3();
  68081. var Engine = this.BJSCANNON;
  68082. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  68083. maxSubSteps = maxSubSteps || 10;
  68084. timeSinceLastCalled = timeSinceLastCalled || 0;
  68085. if (timeSinceLastCalled === 0) {
  68086. this.internalStep(dt);
  68087. this.time += dt;
  68088. }
  68089. else {
  68090. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  68091. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  68092. var t0 = performance.now();
  68093. for (var i = 0; i !== internalSteps; i++) {
  68094. this.internalStep(dt);
  68095. if (performance.now() - t0 > dt * 1000) {
  68096. break;
  68097. }
  68098. }
  68099. this.time += timeSinceLastCalled;
  68100. var h = this.time % dt;
  68101. var h_div_dt = h / dt;
  68102. var interpvelo = step_tmp1;
  68103. var bodies = this.bodies;
  68104. for (var j = 0; j !== bodies.length; j++) {
  68105. var b = bodies[j];
  68106. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  68107. b.position.vsub(b.previousPosition, interpvelo);
  68108. interpvelo.scale(h_div_dt, interpvelo);
  68109. b.position.vadd(interpvelo, b.interpolatedPosition);
  68110. }
  68111. else {
  68112. b.interpolatedPosition.copy(b.position);
  68113. b.interpolatedQuaternion.copy(b.quaternion);
  68114. }
  68115. }
  68116. }
  68117. };
  68118. };
  68119. return CannonJSPlugin;
  68120. }());
  68121. BABYLON.CannonJSPlugin = CannonJSPlugin;
  68122. })(BABYLON || (BABYLON = {}));
  68123. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  68124. var BABYLON;
  68125. (function (BABYLON) {
  68126. var OimoJSPlugin = /** @class */ (function () {
  68127. function OimoJSPlugin(iterations) {
  68128. this.name = "OimoJSPlugin";
  68129. this._tmpImpostorsArray = [];
  68130. this._tmpPositionVector = BABYLON.Vector3.Zero();
  68131. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  68132. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  68133. this.world.worldscale(1);
  68134. this.world.clear();
  68135. //making sure no stats are calculated
  68136. this.world.isNoStat = true;
  68137. }
  68138. OimoJSPlugin.prototype.setGravity = function (gravity) {
  68139. this.world.gravity.copy(gravity);
  68140. };
  68141. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  68142. this.world.timeStep = timeStep;
  68143. };
  68144. OimoJSPlugin.prototype.getTimeStep = function () {
  68145. return this.world.timeStep;
  68146. };
  68147. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  68148. var _this = this;
  68149. impostors.forEach(function (impostor) {
  68150. impostor.beforeStep();
  68151. });
  68152. this.world.step();
  68153. impostors.forEach(function (impostor) {
  68154. impostor.afterStep();
  68155. //update the ordered impostors array
  68156. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  68157. });
  68158. //check for collisions
  68159. var contact = this.world.contacts;
  68160. while (contact !== null) {
  68161. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  68162. contact = contact.next;
  68163. continue;
  68164. }
  68165. //is this body colliding with any other? get the impostor
  68166. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  68167. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  68168. if (!mainImpostor || !collidingImpostor) {
  68169. contact = contact.next;
  68170. continue;
  68171. }
  68172. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  68173. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  68174. contact = contact.next;
  68175. }
  68176. };
  68177. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68178. var mass = impostor.physicsBody.massInfo.mass;
  68179. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  68180. };
  68181. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68182. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  68183. this.applyImpulse(impostor, force, contactPoint);
  68184. };
  68185. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68186. var _this = this;
  68187. //parent-child relationship. Does this impostor has a parent impostor?
  68188. if (impostor.parent) {
  68189. if (impostor.physicsBody) {
  68190. this.removePhysicsBody(impostor);
  68191. //TODO is that needed?
  68192. impostor.forceUpdate();
  68193. }
  68194. return;
  68195. }
  68196. if (impostor.isBodyInitRequired()) {
  68197. var bodyConfig = {
  68198. name: impostor.uniqueId,
  68199. //Oimo must have mass, also for static objects.
  68200. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  68201. size: [],
  68202. type: [],
  68203. pos: [],
  68204. rot: [],
  68205. move: impostor.getParam("mass") !== 0,
  68206. //Supporting older versions of Oimo
  68207. world: this.world
  68208. };
  68209. var impostors = [impostor];
  68210. var addToArray = function (parent) {
  68211. if (!parent.getChildMeshes)
  68212. return;
  68213. parent.getChildMeshes().forEach(function (m) {
  68214. if (m.physicsImpostor) {
  68215. impostors.push(m.physicsImpostor);
  68216. //m.physicsImpostor._init();
  68217. }
  68218. });
  68219. };
  68220. addToArray(impostor.object);
  68221. var checkWithEpsilon_1 = function (value) {
  68222. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  68223. };
  68224. impostors.forEach(function (i) {
  68225. if (!impostor.object.rotationQuaternion) {
  68226. return;
  68227. }
  68228. //get the correct bounding box
  68229. var oldQuaternion = i.object.rotationQuaternion;
  68230. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  68231. x: impostor.object.rotationQuaternion.x,
  68232. y: impostor.object.rotationQuaternion.y,
  68233. z: impostor.object.rotationQuaternion.z,
  68234. s: impostor.object.rotationQuaternion.w
  68235. });
  68236. var extendSize = i.getObjectExtendSize();
  68237. if (i === impostor) {
  68238. var center = impostor.getObjectCenter();
  68239. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  68240. //Can also use Array.prototype.push.apply
  68241. bodyConfig.pos.push(center.x);
  68242. bodyConfig.pos.push(center.y);
  68243. bodyConfig.pos.push(center.z);
  68244. //tmp solution
  68245. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68246. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68247. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  68248. }
  68249. else {
  68250. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  68251. bodyConfig.pos.push(localPosition.x);
  68252. bodyConfig.pos.push(localPosition.y);
  68253. bodyConfig.pos.push(localPosition.z);
  68254. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  68255. bodyConfig.rot.push(0);
  68256. bodyConfig.rot.push(0);
  68257. bodyConfig.rot.push(0);
  68258. }
  68259. // register mesh
  68260. switch (i.type) {
  68261. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68262. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  68263. case BABYLON.PhysicsImpostor.SphereImpostor:
  68264. var radiusX = extendSize.x;
  68265. var radiusY = extendSize.y;
  68266. var radiusZ = extendSize.z;
  68267. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  68268. bodyConfig.type.push('sphere');
  68269. //due to the way oimo works with compounds, add 3 times
  68270. bodyConfig.size.push(size);
  68271. bodyConfig.size.push(size);
  68272. bodyConfig.size.push(size);
  68273. break;
  68274. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68275. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  68276. var sizeY = checkWithEpsilon_1(extendSize.y);
  68277. bodyConfig.type.push('cylinder');
  68278. bodyConfig.size.push(sizeX);
  68279. bodyConfig.size.push(sizeY);
  68280. //due to the way oimo works with compounds, add one more value.
  68281. bodyConfig.size.push(sizeY);
  68282. break;
  68283. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68284. case BABYLON.PhysicsImpostor.BoxImpostor:
  68285. default:
  68286. var sizeX = checkWithEpsilon_1(extendSize.x);
  68287. var sizeY = checkWithEpsilon_1(extendSize.y);
  68288. var sizeZ = checkWithEpsilon_1(extendSize.z);
  68289. bodyConfig.type.push('box');
  68290. bodyConfig.size.push(sizeX);
  68291. bodyConfig.size.push(sizeY);
  68292. bodyConfig.size.push(sizeZ);
  68293. break;
  68294. }
  68295. //actually not needed, but hey...
  68296. i.object.rotationQuaternion = oldQuaternion;
  68297. });
  68298. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  68299. }
  68300. else {
  68301. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  68302. }
  68303. impostor.setDeltaPosition(this._tmpPositionVector);
  68304. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  68305. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  68306. };
  68307. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68308. //impostor.physicsBody.dispose();
  68309. //Same as : (older oimo versions)
  68310. this.world.removeRigidBody(impostor.physicsBody);
  68311. };
  68312. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68313. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68314. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68315. if (!mainBody || !connectedBody) {
  68316. return;
  68317. }
  68318. var jointData = impostorJoint.joint.jointData;
  68319. var options = jointData.nativeParams || {};
  68320. var type;
  68321. var nativeJointData = {
  68322. body1: mainBody,
  68323. body2: connectedBody,
  68324. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  68325. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  68326. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  68327. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  68328. min: options.min,
  68329. max: options.max,
  68330. collision: options.collision || jointData.collision,
  68331. spring: options.spring,
  68332. //supporting older version of Oimo
  68333. world: this.world
  68334. };
  68335. switch (impostorJoint.joint.type) {
  68336. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68337. type = "jointBall";
  68338. break;
  68339. case BABYLON.PhysicsJoint.SpringJoint:
  68340. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  68341. var springData = jointData;
  68342. nativeJointData.min = springData.length || nativeJointData.min;
  68343. //Max should also be set, just make sure it is at least min
  68344. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  68345. case BABYLON.PhysicsJoint.DistanceJoint:
  68346. type = "jointDistance";
  68347. nativeJointData.max = jointData.maxDistance;
  68348. break;
  68349. case BABYLON.PhysicsJoint.PrismaticJoint:
  68350. type = "jointPrisme";
  68351. break;
  68352. case BABYLON.PhysicsJoint.SliderJoint:
  68353. type = "jointSlide";
  68354. break;
  68355. case BABYLON.PhysicsJoint.WheelJoint:
  68356. type = "jointWheel";
  68357. break;
  68358. case BABYLON.PhysicsJoint.HingeJoint:
  68359. default:
  68360. type = "jointHinge";
  68361. break;
  68362. }
  68363. nativeJointData.type = type;
  68364. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  68365. };
  68366. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68367. //Bug in Oimo prevents us from disposing a joint in the playground
  68368. //joint.joint.physicsJoint.dispose();
  68369. //So we will bruteforce it!
  68370. try {
  68371. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  68372. }
  68373. catch (e) {
  68374. BABYLON.Tools.Warn(e);
  68375. }
  68376. };
  68377. OimoJSPlugin.prototype.isSupported = function () {
  68378. return this.BJSOIMO !== undefined;
  68379. };
  68380. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68381. if (!impostor.physicsBody.sleeping) {
  68382. //TODO check that
  68383. if (impostor.physicsBody.shapes.next) {
  68384. var parentShape = this._getLastShape(impostor.physicsBody);
  68385. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  68386. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  68387. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  68388. }
  68389. else {
  68390. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  68391. }
  68392. if (impostor.object.rotationQuaternion) {
  68393. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  68394. impostor.object.rotationQuaternion.normalize();
  68395. }
  68396. }
  68397. };
  68398. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68399. var body = impostor.physicsBody;
  68400. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  68401. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  68402. body.syncShapes();
  68403. body.awake();
  68404. };
  68405. OimoJSPlugin.prototype._getLastShape = function (body) {
  68406. var lastShape = body.shapes;
  68407. while (lastShape.next) {
  68408. lastShape = lastShape.next;
  68409. }
  68410. return lastShape;
  68411. };
  68412. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68413. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  68414. };
  68415. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68416. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  68417. };
  68418. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68419. var v = impostor.physicsBody.linearVelocity;
  68420. if (!v) {
  68421. return null;
  68422. }
  68423. return new BABYLON.Vector3(v.x, v.y, v.z);
  68424. };
  68425. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68426. var v = impostor.physicsBody.angularVelocity;
  68427. if (!v) {
  68428. return null;
  68429. }
  68430. return new BABYLON.Vector3(v.x, v.y, v.z);
  68431. };
  68432. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68433. var staticBody = mass === 0;
  68434. //this will actually set the body's density and not its mass.
  68435. //But this is how oimo treats the mass variable.
  68436. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  68437. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  68438. };
  68439. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  68440. return impostor.physicsBody.shapes.density;
  68441. };
  68442. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  68443. return impostor.physicsBody.shapes.friction;
  68444. };
  68445. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68446. impostor.physicsBody.shapes.friction = friction;
  68447. };
  68448. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68449. return impostor.physicsBody.shapes.restitution;
  68450. };
  68451. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68452. impostor.physicsBody.shapes.restitution = restitution;
  68453. };
  68454. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  68455. impostor.physicsBody.sleep();
  68456. };
  68457. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  68458. impostor.physicsBody.awake();
  68459. };
  68460. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68461. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  68462. if (minDistance !== void 0) {
  68463. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  68464. }
  68465. };
  68466. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  68467. //TODO separate rotational and transational motors.
  68468. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68469. if (motor) {
  68470. motor.setMotor(speed, maxForce);
  68471. }
  68472. };
  68473. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  68474. //TODO separate rotational and transational motors.
  68475. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  68476. if (motor) {
  68477. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  68478. }
  68479. };
  68480. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  68481. var body = impostor.physicsBody;
  68482. mesh.position.x = body.position.x;
  68483. mesh.position.y = body.position.y;
  68484. mesh.position.z = body.position.z;
  68485. if (mesh.rotationQuaternion) {
  68486. mesh.rotationQuaternion.x = body.orientation.x;
  68487. mesh.rotationQuaternion.y = body.orientation.y;
  68488. mesh.rotationQuaternion.z = body.orientation.z;
  68489. mesh.rotationQuaternion.w = body.orientation.s;
  68490. }
  68491. };
  68492. OimoJSPlugin.prototype.getRadius = function (impostor) {
  68493. return impostor.physicsBody.shapes.radius;
  68494. };
  68495. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  68496. var shape = impostor.physicsBody.shapes;
  68497. result.x = shape.halfWidth * 2;
  68498. result.y = shape.halfHeight * 2;
  68499. result.z = shape.halfDepth * 2;
  68500. };
  68501. OimoJSPlugin.prototype.dispose = function () {
  68502. this.world.clear();
  68503. };
  68504. return OimoJSPlugin;
  68505. }());
  68506. BABYLON.OimoJSPlugin = OimoJSPlugin;
  68507. })(BABYLON || (BABYLON = {}));
  68508. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  68509. var BABYLON;
  68510. (function (BABYLON) {
  68511. var Internals;
  68512. (function (Internals) {
  68513. /*
  68514. * Based on jsTGALoader - Javascript loader for TGA file
  68515. * By Vincent Thibault
  68516. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  68517. */
  68518. var TGATools = /** @class */ (function () {
  68519. function TGATools() {
  68520. }
  68521. TGATools.GetTGAHeader = function (data) {
  68522. var offset = 0;
  68523. var header = {
  68524. id_length: data[offset++],
  68525. colormap_type: data[offset++],
  68526. image_type: data[offset++],
  68527. colormap_index: data[offset++] | data[offset++] << 8,
  68528. colormap_length: data[offset++] | data[offset++] << 8,
  68529. colormap_size: data[offset++],
  68530. origin: [
  68531. data[offset++] | data[offset++] << 8,
  68532. data[offset++] | data[offset++] << 8
  68533. ],
  68534. width: data[offset++] | data[offset++] << 8,
  68535. height: data[offset++] | data[offset++] << 8,
  68536. pixel_size: data[offset++],
  68537. flags: data[offset++]
  68538. };
  68539. return header;
  68540. };
  68541. TGATools.UploadContent = function (gl, data) {
  68542. // Not enough data to contain header ?
  68543. if (data.length < 19) {
  68544. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  68545. return;
  68546. }
  68547. // Read Header
  68548. var offset = 18;
  68549. var header = TGATools.GetTGAHeader(data);
  68550. // Assume it's a valid Targa file.
  68551. if (header.id_length + offset > data.length) {
  68552. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  68553. return;
  68554. }
  68555. // Skip not needed data
  68556. offset += header.id_length;
  68557. var use_rle = false;
  68558. var use_pal = false;
  68559. var use_grey = false;
  68560. // Get some informations.
  68561. switch (header.image_type) {
  68562. case TGATools._TYPE_RLE_INDEXED:
  68563. use_rle = true;
  68564. case TGATools._TYPE_INDEXED:
  68565. use_pal = true;
  68566. break;
  68567. case TGATools._TYPE_RLE_RGB:
  68568. use_rle = true;
  68569. case TGATools._TYPE_RGB:
  68570. // use_rgb = true;
  68571. break;
  68572. case TGATools._TYPE_RLE_GREY:
  68573. use_rle = true;
  68574. case TGATools._TYPE_GREY:
  68575. use_grey = true;
  68576. break;
  68577. }
  68578. var pixel_data;
  68579. // var numAlphaBits = header.flags & 0xf;
  68580. var pixel_size = header.pixel_size >> 3;
  68581. var pixel_total = header.width * header.height * pixel_size;
  68582. // Read palettes
  68583. var palettes;
  68584. if (use_pal) {
  68585. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  68586. }
  68587. // Read LRE
  68588. if (use_rle) {
  68589. pixel_data = new Uint8Array(pixel_total);
  68590. var c, count, i;
  68591. var localOffset = 0;
  68592. var pixels = new Uint8Array(pixel_size);
  68593. while (offset < pixel_total && localOffset < pixel_total) {
  68594. c = data[offset++];
  68595. count = (c & 0x7f) + 1;
  68596. // RLE pixels
  68597. if (c & 0x80) {
  68598. // Bind pixel tmp array
  68599. for (i = 0; i < pixel_size; ++i) {
  68600. pixels[i] = data[offset++];
  68601. }
  68602. // Copy pixel array
  68603. for (i = 0; i < count; ++i) {
  68604. pixel_data.set(pixels, localOffset + i * pixel_size);
  68605. }
  68606. localOffset += pixel_size * count;
  68607. }
  68608. else {
  68609. count *= pixel_size;
  68610. for (i = 0; i < count; ++i) {
  68611. pixel_data[localOffset + i] = data[offset++];
  68612. }
  68613. localOffset += count;
  68614. }
  68615. }
  68616. }
  68617. else {
  68618. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  68619. }
  68620. // Load to texture
  68621. var x_start, y_start, x_step, y_step, y_end, x_end;
  68622. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  68623. default:
  68624. case TGATools._ORIGIN_UL:
  68625. x_start = 0;
  68626. x_step = 1;
  68627. x_end = header.width;
  68628. y_start = 0;
  68629. y_step = 1;
  68630. y_end = header.height;
  68631. break;
  68632. case TGATools._ORIGIN_BL:
  68633. x_start = 0;
  68634. x_step = 1;
  68635. x_end = header.width;
  68636. y_start = header.height - 1;
  68637. y_step = -1;
  68638. y_end = -1;
  68639. break;
  68640. case TGATools._ORIGIN_UR:
  68641. x_start = header.width - 1;
  68642. x_step = -1;
  68643. x_end = -1;
  68644. y_start = 0;
  68645. y_step = 1;
  68646. y_end = header.height;
  68647. break;
  68648. case TGATools._ORIGIN_BR:
  68649. x_start = header.width - 1;
  68650. x_step = -1;
  68651. x_end = -1;
  68652. y_start = header.height - 1;
  68653. y_step = -1;
  68654. y_end = -1;
  68655. break;
  68656. }
  68657. // Load the specify method
  68658. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  68659. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  68660. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  68661. };
  68662. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68663. var image = pixel_data, colormap = palettes;
  68664. var width = header.width, height = header.height;
  68665. var color, i = 0, x, y;
  68666. var imageData = new Uint8Array(width * height * 4);
  68667. for (y = y_start; y !== y_end; y += y_step) {
  68668. for (x = x_start; x !== x_end; x += x_step, i++) {
  68669. color = image[i];
  68670. imageData[(x + width * y) * 4 + 3] = 255;
  68671. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  68672. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  68673. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  68674. }
  68675. }
  68676. return imageData;
  68677. };
  68678. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68679. var image = pixel_data;
  68680. var width = header.width, height = header.height;
  68681. var color, i = 0, x, y;
  68682. var imageData = new Uint8Array(width * height * 4);
  68683. for (y = y_start; y !== y_end; y += y_step) {
  68684. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68685. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  68686. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  68687. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  68688. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  68689. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  68690. }
  68691. }
  68692. return imageData;
  68693. };
  68694. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68695. var image = pixel_data;
  68696. var width = header.width, height = header.height;
  68697. var i = 0, x, y;
  68698. var imageData = new Uint8Array(width * height * 4);
  68699. for (y = y_start; y !== y_end; y += y_step) {
  68700. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  68701. imageData[(x + width * y) * 4 + 3] = 255;
  68702. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68703. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68704. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68705. }
  68706. }
  68707. return imageData;
  68708. };
  68709. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68710. var image = pixel_data;
  68711. var width = header.width, height = header.height;
  68712. var i = 0, x, y;
  68713. var imageData = new Uint8Array(width * height * 4);
  68714. for (y = y_start; y !== y_end; y += y_step) {
  68715. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  68716. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68717. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  68718. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  68719. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  68720. }
  68721. }
  68722. return imageData;
  68723. };
  68724. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68725. var image = pixel_data;
  68726. var width = header.width, height = header.height;
  68727. var color, i = 0, x, y;
  68728. var imageData = new Uint8Array(width * height * 4);
  68729. for (y = y_start; y !== y_end; y += y_step) {
  68730. for (x = x_start; x !== x_end; x += x_step, i++) {
  68731. color = image[i];
  68732. imageData[(x + width * y) * 4 + 0] = color;
  68733. imageData[(x + width * y) * 4 + 1] = color;
  68734. imageData[(x + width * y) * 4 + 2] = color;
  68735. imageData[(x + width * y) * 4 + 3] = 255;
  68736. }
  68737. }
  68738. return imageData;
  68739. };
  68740. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  68741. var image = pixel_data;
  68742. var width = header.width, height = header.height;
  68743. var i = 0, x, y;
  68744. var imageData = new Uint8Array(width * height * 4);
  68745. for (y = y_start; y !== y_end; y += y_step) {
  68746. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  68747. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  68748. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  68749. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  68750. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  68751. }
  68752. }
  68753. return imageData;
  68754. };
  68755. //private static _TYPE_NO_DATA = 0;
  68756. TGATools._TYPE_INDEXED = 1;
  68757. TGATools._TYPE_RGB = 2;
  68758. TGATools._TYPE_GREY = 3;
  68759. TGATools._TYPE_RLE_INDEXED = 9;
  68760. TGATools._TYPE_RLE_RGB = 10;
  68761. TGATools._TYPE_RLE_GREY = 11;
  68762. TGATools._ORIGIN_MASK = 0x30;
  68763. TGATools._ORIGIN_SHIFT = 0x04;
  68764. TGATools._ORIGIN_BL = 0x00;
  68765. TGATools._ORIGIN_BR = 0x01;
  68766. TGATools._ORIGIN_UL = 0x02;
  68767. TGATools._ORIGIN_UR = 0x03;
  68768. return TGATools;
  68769. }());
  68770. Internals.TGATools = TGATools;
  68771. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68772. })(BABYLON || (BABYLON = {}));
  68773. //# sourceMappingURL=babylon.tga.js.map
  68774. var BABYLON;
  68775. (function (BABYLON) {
  68776. var Internals;
  68777. (function (Internals) {
  68778. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  68779. // All values and structures referenced from:
  68780. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  68781. var DDS_MAGIC = 0x20534444;
  68782. var
  68783. //DDSD_CAPS = 0x1,
  68784. //DDSD_HEIGHT = 0x2,
  68785. //DDSD_WIDTH = 0x4,
  68786. //DDSD_PITCH = 0x8,
  68787. //DDSD_PIXELFORMAT = 0x1000,
  68788. DDSD_MIPMAPCOUNT = 0x20000;
  68789. //DDSD_LINEARSIZE = 0x80000,
  68790. //DDSD_DEPTH = 0x800000;
  68791. // var DDSCAPS_COMPLEX = 0x8,
  68792. // DDSCAPS_MIPMAP = 0x400000,
  68793. // DDSCAPS_TEXTURE = 0x1000;
  68794. var DDSCAPS2_CUBEMAP = 0x200;
  68795. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  68796. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  68797. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  68798. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  68799. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  68800. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  68801. // DDSCAPS2_VOLUME = 0x200000;
  68802. var
  68803. //DDPF_ALPHAPIXELS = 0x1,
  68804. //DDPF_ALPHA = 0x2,
  68805. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  68806. //DDPF_YUV = 0x200,
  68807. DDPF_LUMINANCE = 0x20000;
  68808. function FourCCToInt32(value) {
  68809. return value.charCodeAt(0) +
  68810. (value.charCodeAt(1) << 8) +
  68811. (value.charCodeAt(2) << 16) +
  68812. (value.charCodeAt(3) << 24);
  68813. }
  68814. function Int32ToFourCC(value) {
  68815. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  68816. }
  68817. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  68818. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  68819. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  68820. var FOURCC_DX10 = FourCCToInt32("DX10");
  68821. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  68822. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  68823. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  68824. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  68825. var headerLengthInt = 31; // The header length in 32 bit ints
  68826. // Offsets into the header array
  68827. var off_magic = 0;
  68828. var off_size = 1;
  68829. var off_flags = 2;
  68830. var off_height = 3;
  68831. var off_width = 4;
  68832. var off_mipmapCount = 7;
  68833. var off_pfFlags = 20;
  68834. var off_pfFourCC = 21;
  68835. var off_RGBbpp = 22;
  68836. // var off_RMask = 23;
  68837. // var off_GMask = 24;
  68838. // var off_BMask = 25;
  68839. // var off_AMask = 26;
  68840. // var off_caps1 = 27;
  68841. var off_caps2 = 28;
  68842. // var off_caps3 = 29;
  68843. // var off_caps4 = 30;
  68844. var off_dxgiFormat = 32;
  68845. ;
  68846. var DDSTools = /** @class */ (function () {
  68847. function DDSTools() {
  68848. }
  68849. DDSTools.GetDDSInfo = function (arrayBuffer) {
  68850. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  68851. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  68852. var mipmapCount = 1;
  68853. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  68854. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68855. }
  68856. var fourCC = header[off_pfFourCC];
  68857. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  68858. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68859. switch (fourCC) {
  68860. case FOURCC_D3DFMT_R16G16B16A16F:
  68861. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68862. break;
  68863. case FOURCC_D3DFMT_R32G32B32A32F:
  68864. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68865. break;
  68866. case FOURCC_DX10:
  68867. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  68868. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68869. break;
  68870. }
  68871. }
  68872. return {
  68873. width: header[off_width],
  68874. height: header[off_height],
  68875. mipmapCount: mipmapCount,
  68876. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  68877. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  68878. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  68879. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  68880. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  68881. dxgiFormat: dxgiFormat,
  68882. textureType: textureType
  68883. };
  68884. };
  68885. DDSTools._ToHalfFloat = function (value) {
  68886. if (!DDSTools._FloatView) {
  68887. DDSTools._FloatView = new Float32Array(1);
  68888. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  68889. }
  68890. DDSTools._FloatView[0] = value;
  68891. var x = DDSTools._Int32View[0];
  68892. var bits = (x >> 16) & 0x8000; /* Get the sign */
  68893. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  68894. var e = (x >> 23) & 0xff; /* Using int is faster here */
  68895. /* If zero, or denormal, or exponent underflows too much for a denormal
  68896. * half, return signed zero. */
  68897. if (e < 103) {
  68898. return bits;
  68899. }
  68900. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  68901. if (e > 142) {
  68902. bits |= 0x7c00;
  68903. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  68904. * not Inf, so make sure we set one mantissa bit too. */
  68905. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  68906. return bits;
  68907. }
  68908. /* If exponent underflows but not too much, return a denormal */
  68909. if (e < 113) {
  68910. m |= 0x0800;
  68911. /* Extra rounding may overflow and set mantissa to 0 and exponent
  68912. * to 1, which is OK. */
  68913. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  68914. return bits;
  68915. }
  68916. bits |= ((e - 112) << 10) | (m >> 1);
  68917. bits += m & 1;
  68918. return bits;
  68919. };
  68920. DDSTools._FromHalfFloat = function (value) {
  68921. var s = (value & 0x8000) >> 15;
  68922. var e = (value & 0x7C00) >> 10;
  68923. var f = value & 0x03FF;
  68924. if (e === 0) {
  68925. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  68926. }
  68927. else if (e == 0x1F) {
  68928. return f ? NaN : ((s ? -1 : 1) * Infinity);
  68929. }
  68930. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  68931. };
  68932. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68933. var destArray = new Float32Array(dataLength);
  68934. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68935. var index = 0;
  68936. for (var y = 0; y < height; y++) {
  68937. for (var x = 0; x < width; x++) {
  68938. var srcPos = (x + y * width) * 4;
  68939. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  68940. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  68941. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  68942. if (DDSTools.StoreLODInAlphaChannel) {
  68943. destArray[index + 3] = lod;
  68944. }
  68945. else {
  68946. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  68947. }
  68948. index += 4;
  68949. }
  68950. }
  68951. return destArray;
  68952. };
  68953. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68954. if (DDSTools.StoreLODInAlphaChannel) {
  68955. var destArray = new Uint16Array(dataLength);
  68956. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68957. var index = 0;
  68958. for (var y = 0; y < height; y++) {
  68959. for (var x = 0; x < width; x++) {
  68960. var srcPos = (x + y * width) * 4;
  68961. destArray[index] = srcData[srcPos];
  68962. destArray[index + 1] = srcData[srcPos + 1];
  68963. destArray[index + 2] = srcData[srcPos + 2];
  68964. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  68965. index += 4;
  68966. }
  68967. }
  68968. return destArray;
  68969. }
  68970. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  68971. };
  68972. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68973. if (DDSTools.StoreLODInAlphaChannel) {
  68974. var destArray = new Float32Array(dataLength);
  68975. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68976. var index = 0;
  68977. for (var y = 0; y < height; y++) {
  68978. for (var x = 0; x < width; x++) {
  68979. var srcPos = (x + y * width) * 4;
  68980. destArray[index] = srcData[srcPos];
  68981. destArray[index + 1] = srcData[srcPos + 1];
  68982. destArray[index + 2] = srcData[srcPos + 2];
  68983. destArray[index + 3] = lod;
  68984. index += 4;
  68985. }
  68986. }
  68987. return destArray;
  68988. }
  68989. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  68990. };
  68991. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68992. var destArray = new Uint8Array(dataLength);
  68993. var srcData = new Float32Array(arrayBuffer, dataOffset);
  68994. var index = 0;
  68995. for (var y = 0; y < height; y++) {
  68996. for (var x = 0; x < width; x++) {
  68997. var srcPos = (x + y * width) * 4;
  68998. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  68999. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  69000. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  69001. if (DDSTools.StoreLODInAlphaChannel) {
  69002. destArray[index + 3] = lod;
  69003. }
  69004. else {
  69005. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  69006. }
  69007. index += 4;
  69008. }
  69009. }
  69010. return destArray;
  69011. };
  69012. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69013. var destArray = new Uint8Array(dataLength);
  69014. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69015. var index = 0;
  69016. for (var y = 0; y < height; y++) {
  69017. for (var x = 0; x < width; x++) {
  69018. var srcPos = (x + y * width) * 4;
  69019. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  69020. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  69021. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  69022. if (DDSTools.StoreLODInAlphaChannel) {
  69023. destArray[index + 3] = lod;
  69024. }
  69025. else {
  69026. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  69027. }
  69028. index += 4;
  69029. }
  69030. }
  69031. return destArray;
  69032. };
  69033. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69034. var byteArray = new Uint8Array(dataLength);
  69035. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69036. var index = 0;
  69037. for (var y = 0; y < height; y++) {
  69038. for (var x = 0; x < width; x++) {
  69039. var srcPos = (x + y * width) * 4;
  69040. byteArray[index] = srcData[srcPos + 2];
  69041. byteArray[index + 1] = srcData[srcPos + 1];
  69042. byteArray[index + 2] = srcData[srcPos];
  69043. byteArray[index + 3] = srcData[srcPos + 3];
  69044. index += 4;
  69045. }
  69046. }
  69047. return byteArray;
  69048. };
  69049. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69050. var byteArray = new Uint8Array(dataLength);
  69051. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69052. var index = 0;
  69053. for (var y = 0; y < height; y++) {
  69054. for (var x = 0; x < width; x++) {
  69055. var srcPos = (x + y * width) * 3;
  69056. byteArray[index] = srcData[srcPos + 2];
  69057. byteArray[index + 1] = srcData[srcPos + 1];
  69058. byteArray[index + 2] = srcData[srcPos];
  69059. index += 3;
  69060. }
  69061. }
  69062. return byteArray;
  69063. };
  69064. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69065. var byteArray = new Uint8Array(dataLength);
  69066. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69067. var index = 0;
  69068. for (var y = 0; y < height; y++) {
  69069. for (var x = 0; x < width; x++) {
  69070. var srcPos = (x + y * width);
  69071. byteArray[index] = srcData[srcPos];
  69072. index++;
  69073. }
  69074. }
  69075. return byteArray;
  69076. };
  69077. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  69078. if (lodIndex === void 0) { lodIndex = -1; }
  69079. var ext = engine.getCaps().s3tc;
  69080. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69081. var fourCC, width, height, dataLength = 0, dataOffset;
  69082. var byteArray, mipmapCount, mip;
  69083. var internalFormat = 0;
  69084. var format = 0;
  69085. var blockBytes = 1;
  69086. if (header[off_magic] !== DDS_MAGIC) {
  69087. BABYLON.Tools.Error("Invalid magic number in DDS header");
  69088. return;
  69089. }
  69090. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  69091. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  69092. return;
  69093. }
  69094. if (info.isCompressed && !ext) {
  69095. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  69096. return;
  69097. }
  69098. var bpp = header[off_RGBbpp];
  69099. dataOffset = header[off_size] + 4;
  69100. var computeFormats = false;
  69101. if (info.isFourCC) {
  69102. fourCC = header[off_pfFourCC];
  69103. switch (fourCC) {
  69104. case FOURCC_DXT1:
  69105. blockBytes = 8;
  69106. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  69107. break;
  69108. case FOURCC_DXT3:
  69109. blockBytes = 16;
  69110. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  69111. break;
  69112. case FOURCC_DXT5:
  69113. blockBytes = 16;
  69114. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  69115. break;
  69116. case FOURCC_D3DFMT_R16G16B16A16F:
  69117. computeFormats = true;
  69118. break;
  69119. case FOURCC_D3DFMT_R32G32B32A32F:
  69120. computeFormats = true;
  69121. break;
  69122. case FOURCC_DX10:
  69123. // There is an additionnal header so dataOffset need to be changed
  69124. dataOffset += 5 * 4; // 5 uints
  69125. var supported = false;
  69126. switch (info.dxgiFormat) {
  69127. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  69128. computeFormats = true;
  69129. supported = true;
  69130. break;
  69131. case DXGI_FORMAT_B8G8R8X8_UNORM:
  69132. info.isRGB = true;
  69133. info.isFourCC = false;
  69134. bpp = 32;
  69135. supported = true;
  69136. break;
  69137. }
  69138. if (supported) {
  69139. break;
  69140. }
  69141. default:
  69142. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  69143. return;
  69144. }
  69145. }
  69146. if (computeFormats) {
  69147. format = engine._getWebGLTextureType(info.textureType);
  69148. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69149. }
  69150. mipmapCount = 1;
  69151. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  69152. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69153. }
  69154. for (var face = 0; face < faces; face++) {
  69155. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  69156. width = header[off_width];
  69157. height = header[off_height];
  69158. for (mip = 0; mip < mipmapCount; ++mip) {
  69159. if (lodIndex === -1 || lodIndex === mip) {
  69160. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  69161. var i = (lodIndex === -1) ? mip : 0;
  69162. if (!info.isCompressed && info.isFourCC) {
  69163. dataLength = width * height * 4;
  69164. var floatArray = null;
  69165. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  69166. if (bpp === 128) {
  69167. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69168. }
  69169. else if (bpp === 64) {
  69170. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69171. }
  69172. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69173. format = engine._getWebGLTextureType(info.textureType);
  69174. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69175. }
  69176. else {
  69177. if (bpp === 128) {
  69178. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69179. }
  69180. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  69181. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69182. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69183. format = engine._getWebGLTextureType(info.textureType);
  69184. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  69185. }
  69186. else {
  69187. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  69188. }
  69189. }
  69190. if (floatArray) {
  69191. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  69192. }
  69193. }
  69194. else if (info.isRGB) {
  69195. if (bpp === 24) {
  69196. dataLength = width * height * 3;
  69197. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69198. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  69199. }
  69200. else {
  69201. dataLength = width * height * 4;
  69202. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69203. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  69204. }
  69205. }
  69206. else if (info.isLuminance) {
  69207. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  69208. var unpaddedRowSize = width;
  69209. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  69210. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  69211. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  69212. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  69213. }
  69214. else {
  69215. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  69216. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  69217. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  69218. }
  69219. }
  69220. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  69221. width *= 0.5;
  69222. height *= 0.5;
  69223. width = Math.max(1.0, width);
  69224. height = Math.max(1.0, height);
  69225. }
  69226. if (currentFace !== undefined) {
  69227. // Loading a single face
  69228. break;
  69229. }
  69230. }
  69231. };
  69232. DDSTools.StoreLODInAlphaChannel = false;
  69233. return DDSTools;
  69234. }());
  69235. Internals.DDSTools = DDSTools;
  69236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69237. })(BABYLON || (BABYLON = {}));
  69238. //# sourceMappingURL=babylon.dds.js.map
  69239. var BABYLON;
  69240. (function (BABYLON) {
  69241. var Internals;
  69242. (function (Internals) {
  69243. /**
  69244. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  69245. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  69246. */
  69247. var KhronosTextureContainer = /** @class */ (function () {
  69248. /**
  69249. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  69250. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  69251. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  69252. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  69253. */
  69254. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  69255. this.arrayBuffer = arrayBuffer;
  69256. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  69257. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  69258. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  69259. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  69260. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  69261. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  69262. BABYLON.Tools.Error("texture missing KTX identifier");
  69263. return;
  69264. }
  69265. // load the reset of the header in native 32 bit int
  69266. var header = new Int32Array(this.arrayBuffer, 12, 13);
  69267. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  69268. var oppositeEndianess = header[0] === 0x01020304;
  69269. // read all the header elements in order they exist in the file, without modification (sans endainness)
  69270. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  69271. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  69272. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  69273. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  69274. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  69275. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  69276. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  69277. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  69278. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  69279. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  69280. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  69281. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  69282. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  69283. if (this.glType !== 0) {
  69284. BABYLON.Tools.Error("only compressed formats currently supported");
  69285. return;
  69286. }
  69287. else {
  69288. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  69289. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  69290. }
  69291. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  69292. BABYLON.Tools.Error("only 2D textures currently supported");
  69293. return;
  69294. }
  69295. if (this.numberOfArrayElements !== 0) {
  69296. BABYLON.Tools.Error("texture arrays not currently supported");
  69297. return;
  69298. }
  69299. if (this.numberOfFaces !== facesExpected) {
  69300. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  69301. return;
  69302. }
  69303. // we now have a completely validated file, so could use existence of loadType as success
  69304. // would need to make this more elaborate & adjust checks above to support more than one load type
  69305. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  69306. }
  69307. // not as fast hardware based, but will probably never need to use
  69308. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  69309. return ((val & 0xFF) << 24)
  69310. | ((val & 0xFF00) << 8)
  69311. | ((val >> 8) & 0xFF00)
  69312. | ((val >> 24) & 0xFF);
  69313. };
  69314. /**
  69315. * It is assumed that the texture has already been created & is currently bound
  69316. */
  69317. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  69318. switch (this.loadType) {
  69319. case KhronosTextureContainer.COMPRESSED_2D:
  69320. this._upload2DCompressedLevels(gl, loadMipmaps);
  69321. break;
  69322. case KhronosTextureContainer.TEX_2D:
  69323. case KhronosTextureContainer.COMPRESSED_3D:
  69324. case KhronosTextureContainer.TEX_3D:
  69325. }
  69326. };
  69327. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  69328. // initialize width & height for level 1
  69329. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  69330. var width = this.pixelWidth;
  69331. var height = this.pixelHeight;
  69332. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  69333. for (var level = 0; level < mipmapCount; level++) {
  69334. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  69335. for (var face = 0; face < this.numberOfFaces; face++) {
  69336. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  69337. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  69338. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  69339. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  69340. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  69341. }
  69342. width = Math.max(1.0, width * 0.5);
  69343. height = Math.max(1.0, height * 0.5);
  69344. }
  69345. };
  69346. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  69347. // load types
  69348. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  69349. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  69350. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  69351. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  69352. return KhronosTextureContainer;
  69353. }());
  69354. Internals.KhronosTextureContainer = KhronosTextureContainer;
  69355. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69356. })(BABYLON || (BABYLON = {}));
  69357. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  69358. var BABYLON;
  69359. (function (BABYLON) {
  69360. var Debug;
  69361. (function (Debug) {
  69362. /**
  69363. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  69364. */
  69365. var SkeletonViewer = /** @class */ (function () {
  69366. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  69367. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  69368. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  69369. this.skeleton = skeleton;
  69370. this.mesh = mesh;
  69371. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  69372. this.renderingGroupId = renderingGroupId;
  69373. this.color = BABYLON.Color3.White();
  69374. this._debugLines = new Array();
  69375. this._isEnabled = false;
  69376. this._scene = scene;
  69377. this.update();
  69378. this._renderFunction = this.update.bind(this);
  69379. }
  69380. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  69381. get: function () {
  69382. return this._isEnabled;
  69383. },
  69384. set: function (value) {
  69385. if (this._isEnabled === value) {
  69386. return;
  69387. }
  69388. this._isEnabled = value;
  69389. if (value) {
  69390. this._scene.registerBeforeRender(this._renderFunction);
  69391. }
  69392. else {
  69393. this._scene.unregisterBeforeRender(this._renderFunction);
  69394. }
  69395. },
  69396. enumerable: true,
  69397. configurable: true
  69398. });
  69399. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  69400. if (x === void 0) { x = 0; }
  69401. if (y === void 0) { y = 0; }
  69402. if (z === void 0) { z = 0; }
  69403. var tmat = BABYLON.Tmp.Matrix[0];
  69404. var parentBone = bone.getParent();
  69405. tmat.copyFrom(bone.getLocalMatrix());
  69406. if (x !== 0 || y !== 0 || z !== 0) {
  69407. var tmat2 = BABYLON.Tmp.Matrix[1];
  69408. BABYLON.Matrix.IdentityToRef(tmat2);
  69409. tmat2.m[12] = x;
  69410. tmat2.m[13] = y;
  69411. tmat2.m[14] = z;
  69412. tmat2.multiplyToRef(tmat, tmat);
  69413. }
  69414. if (parentBone) {
  69415. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  69416. }
  69417. tmat.multiplyToRef(meshMat, tmat);
  69418. position.x = tmat.m[12];
  69419. position.y = tmat.m[13];
  69420. position.z = tmat.m[14];
  69421. };
  69422. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  69423. var len = bones.length;
  69424. var meshPos = this.mesh.position;
  69425. for (var i = 0; i < len; i++) {
  69426. var bone = bones[i];
  69427. var points = this._debugLines[i];
  69428. if (!points) {
  69429. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69430. this._debugLines[i] = points;
  69431. }
  69432. this._getBonePosition(points[0], bone, meshMat);
  69433. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  69434. points[0].subtractInPlace(meshPos);
  69435. points[1].subtractInPlace(meshPos);
  69436. }
  69437. };
  69438. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  69439. var len = bones.length;
  69440. var boneNum = 0;
  69441. var meshPos = this.mesh.position;
  69442. for (var i = len - 1; i >= 0; i--) {
  69443. var childBone = bones[i];
  69444. var parentBone = childBone.getParent();
  69445. if (!parentBone) {
  69446. continue;
  69447. }
  69448. var points = this._debugLines[boneNum];
  69449. if (!points) {
  69450. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69451. this._debugLines[boneNum] = points;
  69452. }
  69453. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  69454. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  69455. points[0].subtractInPlace(meshPos);
  69456. points[1].subtractInPlace(meshPos);
  69457. boneNum++;
  69458. }
  69459. };
  69460. SkeletonViewer.prototype.update = function () {
  69461. if (this.autoUpdateBonesMatrices) {
  69462. this.skeleton.computeAbsoluteTransforms();
  69463. }
  69464. if (this.skeleton.bones[0].length === undefined) {
  69465. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69466. }
  69467. else {
  69468. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  69469. }
  69470. if (!this._debugMesh) {
  69471. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  69472. this._debugMesh.renderingGroupId = this.renderingGroupId;
  69473. }
  69474. else {
  69475. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  69476. }
  69477. this._debugMesh.position.copyFrom(this.mesh.position);
  69478. this._debugMesh.color = this.color;
  69479. };
  69480. SkeletonViewer.prototype.dispose = function () {
  69481. if (this._debugMesh) {
  69482. this.isEnabled = false;
  69483. this._debugMesh.dispose();
  69484. this._debugMesh = null;
  69485. }
  69486. };
  69487. return SkeletonViewer;
  69488. }());
  69489. Debug.SkeletonViewer = SkeletonViewer;
  69490. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69491. })(BABYLON || (BABYLON = {}));
  69492. //# sourceMappingURL=babylon.skeletonViewer.js.map
  69493. var BABYLON;
  69494. (function (BABYLON) {
  69495. var Debug;
  69496. (function (Debug) {
  69497. var AxesViewer = /** @class */ (function () {
  69498. function AxesViewer(scene, scaleLines) {
  69499. if (scaleLines === void 0) { scaleLines = 1; }
  69500. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69501. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69502. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69503. this.scaleLines = 1;
  69504. this.scaleLines = scaleLines;
  69505. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  69506. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  69507. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  69508. this._xmesh.renderingGroupId = 2;
  69509. this._ymesh.renderingGroupId = 2;
  69510. this._zmesh.renderingGroupId = 2;
  69511. this._xmesh.material.checkReadyOnlyOnce = true;
  69512. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  69513. this._ymesh.material.checkReadyOnlyOnce = true;
  69514. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  69515. this._zmesh.material.checkReadyOnlyOnce = true;
  69516. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  69517. this.scene = scene;
  69518. }
  69519. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  69520. var scaleLines = this.scaleLines;
  69521. if (this._xmesh) {
  69522. this._xmesh.position.copyFrom(position);
  69523. }
  69524. if (this._ymesh) {
  69525. this._ymesh.position.copyFrom(position);
  69526. }
  69527. if (this._zmesh) {
  69528. this._zmesh.position.copyFrom(position);
  69529. }
  69530. var point2 = this._xline[1];
  69531. point2.x = xaxis.x * scaleLines;
  69532. point2.y = xaxis.y * scaleLines;
  69533. point2.z = xaxis.z * scaleLines;
  69534. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  69535. point2 = this._yline[1];
  69536. point2.x = yaxis.x * scaleLines;
  69537. point2.y = yaxis.y * scaleLines;
  69538. point2.z = yaxis.z * scaleLines;
  69539. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  69540. point2 = this._zline[1];
  69541. point2.x = zaxis.x * scaleLines;
  69542. point2.y = zaxis.y * scaleLines;
  69543. point2.z = zaxis.z * scaleLines;
  69544. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  69545. };
  69546. AxesViewer.prototype.dispose = function () {
  69547. if (this._xmesh) {
  69548. this._xmesh.dispose();
  69549. }
  69550. if (this._ymesh) {
  69551. this._ymesh.dispose();
  69552. }
  69553. if (this._zmesh) {
  69554. this._zmesh.dispose();
  69555. }
  69556. this._xmesh = null;
  69557. this._ymesh = null;
  69558. this._zmesh = null;
  69559. this.scene = null;
  69560. };
  69561. return AxesViewer;
  69562. }());
  69563. Debug.AxesViewer = AxesViewer;
  69564. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69565. })(BABYLON || (BABYLON = {}));
  69566. //# sourceMappingURL=babylon.axesViewer.js.map
  69567. var BABYLON;
  69568. (function (BABYLON) {
  69569. var Debug;
  69570. (function (Debug) {
  69571. var BoneAxesViewer = /** @class */ (function (_super) {
  69572. __extends(BoneAxesViewer, _super);
  69573. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  69574. if (scaleLines === void 0) { scaleLines = 1; }
  69575. var _this = _super.call(this, scene, scaleLines) || this;
  69576. _this.pos = BABYLON.Vector3.Zero();
  69577. _this.xaxis = BABYLON.Vector3.Zero();
  69578. _this.yaxis = BABYLON.Vector3.Zero();
  69579. _this.zaxis = BABYLON.Vector3.Zero();
  69580. _this.mesh = mesh;
  69581. _this.bone = bone;
  69582. return _this;
  69583. }
  69584. BoneAxesViewer.prototype.update = function () {
  69585. if (!this.mesh || !this.bone) {
  69586. return;
  69587. }
  69588. var bone = this.bone;
  69589. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  69590. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  69591. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  69592. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  69593. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  69594. };
  69595. BoneAxesViewer.prototype.dispose = function () {
  69596. if (this.mesh) {
  69597. this.mesh = null;
  69598. this.bone = null;
  69599. _super.prototype.dispose.call(this);
  69600. }
  69601. };
  69602. return BoneAxesViewer;
  69603. }(Debug.AxesViewer));
  69604. Debug.BoneAxesViewer = BoneAxesViewer;
  69605. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69606. })(BABYLON || (BABYLON = {}));
  69607. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  69608. var BABYLON;
  69609. (function (BABYLON) {
  69610. var RayHelper = /** @class */ (function () {
  69611. function RayHelper(ray) {
  69612. this.ray = ray;
  69613. }
  69614. RayHelper.CreateAndShow = function (ray, scene, color) {
  69615. var helper = new RayHelper(ray);
  69616. helper.show(scene, color);
  69617. return helper;
  69618. };
  69619. RayHelper.prototype.show = function (scene, color) {
  69620. if (!this._renderFunction && this.ray) {
  69621. var ray = this.ray;
  69622. this._renderFunction = this._render.bind(this);
  69623. this._scene = scene;
  69624. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  69625. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  69626. if (this._renderFunction) {
  69627. this._scene.registerBeforeRender(this._renderFunction);
  69628. }
  69629. }
  69630. if (color && this._renderLine) {
  69631. this._renderLine.color.copyFrom(color);
  69632. }
  69633. };
  69634. RayHelper.prototype.hide = function () {
  69635. if (this._renderFunction && this._scene) {
  69636. this._scene.unregisterBeforeRender(this._renderFunction);
  69637. this._scene = null;
  69638. this._renderFunction = null;
  69639. if (this._renderLine) {
  69640. this._renderLine.dispose();
  69641. this._renderLine = null;
  69642. }
  69643. this._renderPoints = [];
  69644. }
  69645. };
  69646. RayHelper.prototype._render = function () {
  69647. var ray = this.ray;
  69648. if (!ray) {
  69649. return;
  69650. }
  69651. var point = this._renderPoints[1];
  69652. var len = Math.min(ray.length, 1000000);
  69653. point.copyFrom(ray.direction);
  69654. point.scaleInPlace(len);
  69655. point.addInPlace(ray.origin);
  69656. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  69657. };
  69658. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  69659. this._attachedToMesh = mesh;
  69660. var ray = this.ray;
  69661. if (!ray) {
  69662. return;
  69663. }
  69664. if (!ray.direction) {
  69665. ray.direction = BABYLON.Vector3.Zero();
  69666. }
  69667. if (!ray.origin) {
  69668. ray.origin = BABYLON.Vector3.Zero();
  69669. }
  69670. if (length) {
  69671. ray.length = length;
  69672. }
  69673. if (!meshSpaceOrigin) {
  69674. meshSpaceOrigin = BABYLON.Vector3.Zero();
  69675. }
  69676. if (!meshSpaceDirection) {
  69677. // -1 so that this will work with Mesh.lookAt
  69678. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  69679. }
  69680. if (!this._meshSpaceDirection) {
  69681. this._meshSpaceDirection = meshSpaceDirection.clone();
  69682. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  69683. }
  69684. else {
  69685. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  69686. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  69687. }
  69688. if (!this._updateToMeshFunction) {
  69689. this._updateToMeshFunction = this._updateToMesh.bind(this);
  69690. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  69691. }
  69692. this._updateToMesh();
  69693. };
  69694. RayHelper.prototype.detachFromMesh = function () {
  69695. if (this._attachedToMesh) {
  69696. if (this._updateToMeshFunction) {
  69697. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  69698. }
  69699. this._attachedToMesh = null;
  69700. this._updateToMeshFunction = null;
  69701. }
  69702. };
  69703. RayHelper.prototype._updateToMesh = function () {
  69704. var ray = this.ray;
  69705. if (!this._attachedToMesh || !ray) {
  69706. return;
  69707. }
  69708. if (this._attachedToMesh._isDisposed) {
  69709. this.detachFromMesh();
  69710. return;
  69711. }
  69712. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  69713. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  69714. };
  69715. RayHelper.prototype.dispose = function () {
  69716. this.hide();
  69717. this.detachFromMesh();
  69718. this.ray = null;
  69719. };
  69720. return RayHelper;
  69721. }());
  69722. BABYLON.RayHelper = RayHelper;
  69723. })(BABYLON || (BABYLON = {}));
  69724. //# sourceMappingURL=babylon.rayHelper.js.map
  69725. var BABYLON;
  69726. (function (BABYLON) {
  69727. // load the inspector using require, if not present in the global namespace.
  69728. var DebugLayer = /** @class */ (function () {
  69729. function DebugLayer(scene) {
  69730. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69731. this._scene = scene;
  69732. // load inspector using require, if it doesn't exist on the global namespace.
  69733. }
  69734. /** Creates the inspector window. */
  69735. DebugLayer.prototype._createInspector = function (config) {
  69736. if (config === void 0) { config = {}; }
  69737. var popup = config.popup || false;
  69738. var initialTab = config.initialTab || 0;
  69739. var parentElement = config.parentElement || null;
  69740. if (!this._inspector) {
  69741. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  69742. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  69743. } // else nothing to do,; instance is already existing
  69744. };
  69745. DebugLayer.prototype.isVisible = function () {
  69746. if (!this._inspector) {
  69747. return false;
  69748. }
  69749. return true;
  69750. };
  69751. DebugLayer.prototype.hide = function () {
  69752. if (this._inspector) {
  69753. try {
  69754. this._inspector.dispose();
  69755. }
  69756. catch (e) {
  69757. // If the inspector has been removed directly from the inspector tool
  69758. }
  69759. this._inspector = null;
  69760. }
  69761. };
  69762. DebugLayer.prototype.show = function (config) {
  69763. if (config === void 0) { config = {}; }
  69764. if (typeof this.BJSINSPECTOR == 'undefined') {
  69765. // Load inspector and add it to the DOM
  69766. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  69767. }
  69768. else {
  69769. // Otherwise creates the inspector
  69770. this._createInspector(config);
  69771. }
  69772. };
  69773. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  69774. return DebugLayer;
  69775. }());
  69776. BABYLON.DebugLayer = DebugLayer;
  69777. })(BABYLON || (BABYLON = {}));
  69778. //# sourceMappingURL=babylon.debugLayer.js.map
  69779. var BABYLON;
  69780. (function (BABYLON) {
  69781. var Debug;
  69782. (function (Debug) {
  69783. var PhysicsViewer = /** @class */ (function () {
  69784. function PhysicsViewer(scene) {
  69785. this._impostors = [];
  69786. this._meshes = [];
  69787. this._numMeshes = 0;
  69788. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69789. var physicEngine = this._scene.getPhysicsEngine();
  69790. if (physicEngine) {
  69791. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  69792. }
  69793. }
  69794. PhysicsViewer.prototype._updateDebugMeshes = function () {
  69795. var plugin = this._physicsEnginePlugin;
  69796. for (var i = 0; i < this._numMeshes; i++) {
  69797. var impostor = this._impostors[i];
  69798. if (!impostor) {
  69799. continue;
  69800. }
  69801. if (impostor.isDisposed) {
  69802. this.hideImpostor(this._impostors[i--]);
  69803. }
  69804. else {
  69805. var mesh = this._meshes[i];
  69806. if (mesh && plugin) {
  69807. plugin.syncMeshWithImpostor(mesh, impostor);
  69808. }
  69809. }
  69810. }
  69811. };
  69812. PhysicsViewer.prototype.showImpostor = function (impostor) {
  69813. if (!this._scene) {
  69814. return;
  69815. }
  69816. for (var i = 0; i < this._numMeshes; i++) {
  69817. if (this._impostors[i] == impostor) {
  69818. return;
  69819. }
  69820. }
  69821. var debugMesh = this._getDebugMesh(impostor, this._scene);
  69822. if (debugMesh) {
  69823. this._impostors[this._numMeshes] = impostor;
  69824. this._meshes[this._numMeshes] = debugMesh;
  69825. if (this._numMeshes === 0) {
  69826. this._renderFunction = this._updateDebugMeshes.bind(this);
  69827. this._scene.registerBeforeRender(this._renderFunction);
  69828. }
  69829. this._numMeshes++;
  69830. }
  69831. };
  69832. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  69833. if (!impostor || !this._scene) {
  69834. return;
  69835. }
  69836. var removed = false;
  69837. for (var i = 0; i < this._numMeshes; i++) {
  69838. if (this._impostors[i] == impostor) {
  69839. var mesh = this._meshes[i];
  69840. if (!mesh) {
  69841. continue;
  69842. }
  69843. this._scene.removeMesh(mesh);
  69844. mesh.dispose();
  69845. this._numMeshes--;
  69846. if (this._numMeshes > 0) {
  69847. this._meshes[i] = this._meshes[this._numMeshes];
  69848. this._impostors[i] = this._impostors[this._numMeshes];
  69849. this._meshes[this._numMeshes] = null;
  69850. this._impostors[this._numMeshes] = null;
  69851. }
  69852. else {
  69853. this._meshes[0] = null;
  69854. this._impostors[0] = null;
  69855. }
  69856. removed = true;
  69857. break;
  69858. }
  69859. }
  69860. if (removed && this._numMeshes === 0) {
  69861. this._scene.unregisterBeforeRender(this._renderFunction);
  69862. }
  69863. };
  69864. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  69865. if (!this._debugMaterial) {
  69866. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  69867. this._debugMaterial.wireframe = true;
  69868. }
  69869. return this._debugMaterial;
  69870. };
  69871. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  69872. if (!this._debugBoxMesh) {
  69873. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  69874. this._debugBoxMesh.renderingGroupId = 1;
  69875. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69876. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  69877. scene.removeMesh(this._debugBoxMesh);
  69878. }
  69879. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  69880. };
  69881. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  69882. if (!this._debugSphereMesh) {
  69883. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  69884. this._debugSphereMesh.renderingGroupId = 1;
  69885. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  69886. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  69887. scene.removeMesh(this._debugSphereMesh);
  69888. }
  69889. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  69890. };
  69891. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  69892. var mesh = null;
  69893. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  69894. mesh = this._getDebugBoxMesh(scene);
  69895. impostor.getBoxSizeToRef(mesh.scaling);
  69896. }
  69897. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  69898. mesh = this._getDebugSphereMesh(scene);
  69899. var radius = impostor.getRadius();
  69900. mesh.scaling.x = radius * 2;
  69901. mesh.scaling.y = radius * 2;
  69902. mesh.scaling.z = radius * 2;
  69903. }
  69904. return mesh;
  69905. };
  69906. PhysicsViewer.prototype.dispose = function () {
  69907. for (var i = 0; i < this._numMeshes; i++) {
  69908. this.hideImpostor(this._impostors[i]);
  69909. }
  69910. if (this._debugBoxMesh) {
  69911. this._debugBoxMesh.dispose();
  69912. }
  69913. if (this._debugSphereMesh) {
  69914. this._debugSphereMesh.dispose();
  69915. }
  69916. if (this._debugMaterial) {
  69917. this._debugMaterial.dispose();
  69918. }
  69919. this._impostors.length = 0;
  69920. this._scene = null;
  69921. this._physicsEnginePlugin = null;
  69922. };
  69923. return PhysicsViewer;
  69924. }());
  69925. Debug.PhysicsViewer = PhysicsViewer;
  69926. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  69927. })(BABYLON || (BABYLON = {}));
  69928. //# sourceMappingURL=babylon.physicsViewer.js.map
  69929. var BABYLON;
  69930. (function (BABYLON) {
  69931. var BoundingBoxRenderer = /** @class */ (function () {
  69932. function BoundingBoxRenderer(scene) {
  69933. this.frontColor = new BABYLON.Color3(1, 1, 1);
  69934. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  69935. this.showBackLines = true;
  69936. this.renderList = new BABYLON.SmartArray(32);
  69937. this._vertexBuffers = {};
  69938. this._scene = scene;
  69939. }
  69940. BoundingBoxRenderer.prototype._prepareRessources = function () {
  69941. if (this._colorShader) {
  69942. return;
  69943. }
  69944. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  69945. attributes: [BABYLON.VertexBuffer.PositionKind],
  69946. uniforms: ["world", "viewProjection", "color"]
  69947. });
  69948. var engine = this._scene.getEngine();
  69949. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  69950. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  69951. this._createIndexBuffer();
  69952. };
  69953. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  69954. var engine = this._scene.getEngine();
  69955. 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]);
  69956. };
  69957. BoundingBoxRenderer.prototype._rebuild = function () {
  69958. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69959. if (vb) {
  69960. vb._rebuild();
  69961. }
  69962. this._createIndexBuffer();
  69963. };
  69964. BoundingBoxRenderer.prototype.reset = function () {
  69965. this.renderList.reset();
  69966. };
  69967. BoundingBoxRenderer.prototype.render = function () {
  69968. if (this.renderList.length === 0) {
  69969. return;
  69970. }
  69971. this._prepareRessources();
  69972. if (!this._colorShader.isReady()) {
  69973. return;
  69974. }
  69975. var engine = this._scene.getEngine();
  69976. engine.setDepthWrite(false);
  69977. this._colorShader._preBind();
  69978. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  69979. var boundingBox = this.renderList.data[boundingBoxIndex];
  69980. var min = boundingBox.minimum;
  69981. var max = boundingBox.maximum;
  69982. var diff = max.subtract(min);
  69983. var median = min.add(diff.scale(0.5));
  69984. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69985. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69986. .multiply(boundingBox.getWorldMatrix());
  69987. // VBOs
  69988. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69989. if (this.showBackLines) {
  69990. // Back
  69991. engine.setDepthFunctionToGreaterOrEqual();
  69992. this._scene.resetCachedMaterial();
  69993. this._colorShader.setColor4("color", this.backColor.toColor4());
  69994. this._colorShader.bind(worldMatrix);
  69995. // Draw order
  69996. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  69997. }
  69998. // Front
  69999. engine.setDepthFunctionToLess();
  70000. this._scene.resetCachedMaterial();
  70001. this._colorShader.setColor4("color", this.frontColor.toColor4());
  70002. this._colorShader.bind(worldMatrix);
  70003. // Draw order
  70004. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  70005. }
  70006. this._colorShader.unbind();
  70007. engine.setDepthFunctionToLessOrEqual();
  70008. engine.setDepthWrite(true);
  70009. };
  70010. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  70011. this._prepareRessources();
  70012. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  70013. return;
  70014. }
  70015. var engine = this._scene.getEngine();
  70016. engine.setDepthWrite(false);
  70017. engine.setColorWrite(false);
  70018. this._colorShader._preBind();
  70019. var boundingBox = mesh._boundingInfo.boundingBox;
  70020. var min = boundingBox.minimum;
  70021. var max = boundingBox.maximum;
  70022. var diff = max.subtract(min);
  70023. var median = min.add(diff.scale(0.5));
  70024. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70025. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70026. .multiply(boundingBox.getWorldMatrix());
  70027. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70028. engine.setDepthFunctionToLess();
  70029. this._scene.resetCachedMaterial();
  70030. this._colorShader.bind(worldMatrix);
  70031. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  70032. this._colorShader.unbind();
  70033. engine.setDepthFunctionToLessOrEqual();
  70034. engine.setDepthWrite(true);
  70035. engine.setColorWrite(true);
  70036. };
  70037. BoundingBoxRenderer.prototype.dispose = function () {
  70038. if (!this._colorShader) {
  70039. return;
  70040. }
  70041. this.renderList.dispose();
  70042. this._colorShader.dispose();
  70043. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70044. if (buffer) {
  70045. buffer.dispose();
  70046. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70047. }
  70048. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70049. };
  70050. return BoundingBoxRenderer;
  70051. }());
  70052. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  70053. })(BABYLON || (BABYLON = {}));
  70054. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  70055. var BABYLON;
  70056. (function (BABYLON) {
  70057. var MorphTarget = /** @class */ (function () {
  70058. function MorphTarget(name, influence) {
  70059. if (influence === void 0) { influence = 0; }
  70060. this.name = name;
  70061. this.animations = new Array();
  70062. this._positions = null;
  70063. this._normals = null;
  70064. this._tangents = null;
  70065. this.onInfluenceChanged = new BABYLON.Observable();
  70066. this.influence = influence;
  70067. }
  70068. Object.defineProperty(MorphTarget.prototype, "influence", {
  70069. get: function () {
  70070. return this._influence;
  70071. },
  70072. set: function (influence) {
  70073. if (this._influence === influence) {
  70074. return;
  70075. }
  70076. var previous = this._influence;
  70077. this._influence = influence;
  70078. if (this.onInfluenceChanged.hasObservers) {
  70079. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  70080. }
  70081. },
  70082. enumerable: true,
  70083. configurable: true
  70084. });
  70085. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  70086. get: function () {
  70087. return !!this._positions;
  70088. },
  70089. enumerable: true,
  70090. configurable: true
  70091. });
  70092. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  70093. get: function () {
  70094. return !!this._normals;
  70095. },
  70096. enumerable: true,
  70097. configurable: true
  70098. });
  70099. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  70100. get: function () {
  70101. return !!this._tangents;
  70102. },
  70103. enumerable: true,
  70104. configurable: true
  70105. });
  70106. MorphTarget.prototype.setPositions = function (data) {
  70107. this._positions = data;
  70108. };
  70109. MorphTarget.prototype.getPositions = function () {
  70110. return this._positions;
  70111. };
  70112. MorphTarget.prototype.setNormals = function (data) {
  70113. this._normals = data;
  70114. };
  70115. MorphTarget.prototype.getNormals = function () {
  70116. return this._normals;
  70117. };
  70118. MorphTarget.prototype.setTangents = function (data) {
  70119. this._tangents = data;
  70120. };
  70121. MorphTarget.prototype.getTangents = function () {
  70122. return this._tangents;
  70123. };
  70124. /**
  70125. * Serializes the current target into a Serialization object.
  70126. * Returns the serialized object.
  70127. */
  70128. MorphTarget.prototype.serialize = function () {
  70129. var serializationObject = {};
  70130. serializationObject.name = this.name;
  70131. serializationObject.influence = this.influence;
  70132. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  70133. if (this.hasNormals) {
  70134. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  70135. }
  70136. if (this.hasTangents) {
  70137. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  70138. }
  70139. // Animations
  70140. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  70141. return serializationObject;
  70142. };
  70143. // Statics
  70144. MorphTarget.Parse = function (serializationObject) {
  70145. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  70146. result.setPositions(serializationObject.positions);
  70147. if (serializationObject.normals) {
  70148. result.setNormals(serializationObject.normals);
  70149. }
  70150. if (serializationObject.tangents) {
  70151. result.setTangents(serializationObject.tangents);
  70152. }
  70153. // Animations
  70154. if (serializationObject.animations) {
  70155. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  70156. var parsedAnimation = serializationObject.animations[animationIndex];
  70157. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70158. }
  70159. }
  70160. return result;
  70161. };
  70162. MorphTarget.FromMesh = function (mesh, name, influence) {
  70163. if (!name) {
  70164. name = mesh.name;
  70165. }
  70166. var result = new MorphTarget(name, influence);
  70167. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  70168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70169. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  70170. }
  70171. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  70172. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  70173. }
  70174. return result;
  70175. };
  70176. return MorphTarget;
  70177. }());
  70178. BABYLON.MorphTarget = MorphTarget;
  70179. })(BABYLON || (BABYLON = {}));
  70180. //# sourceMappingURL=babylon.morphTarget.js.map
  70181. var BABYLON;
  70182. (function (BABYLON) {
  70183. var MorphTargetManager = /** @class */ (function () {
  70184. function MorphTargetManager(scene) {
  70185. if (scene === void 0) { scene = null; }
  70186. this._targets = new Array();
  70187. this._targetObservable = new Array();
  70188. this._activeTargets = new BABYLON.SmartArray(16);
  70189. this._supportsNormals = false;
  70190. this._supportsTangents = false;
  70191. this._vertexCount = 0;
  70192. this._uniqueId = 0;
  70193. this._tempInfluences = new Array();
  70194. if (!scene) {
  70195. scene = BABYLON.Engine.LastCreatedScene;
  70196. }
  70197. this._scene = scene;
  70198. if (this._scene) {
  70199. this._scene.morphTargetManagers.push(this);
  70200. this._uniqueId = this._scene.getUniqueId();
  70201. }
  70202. }
  70203. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  70204. get: function () {
  70205. return this._uniqueId;
  70206. },
  70207. enumerable: true,
  70208. configurable: true
  70209. });
  70210. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  70211. get: function () {
  70212. return this._vertexCount;
  70213. },
  70214. enumerable: true,
  70215. configurable: true
  70216. });
  70217. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  70218. get: function () {
  70219. return this._supportsNormals;
  70220. },
  70221. enumerable: true,
  70222. configurable: true
  70223. });
  70224. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  70225. get: function () {
  70226. return this._supportsTangents;
  70227. },
  70228. enumerable: true,
  70229. configurable: true
  70230. });
  70231. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  70232. get: function () {
  70233. return this._targets.length;
  70234. },
  70235. enumerable: true,
  70236. configurable: true
  70237. });
  70238. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  70239. get: function () {
  70240. return this._activeTargets.length;
  70241. },
  70242. enumerable: true,
  70243. configurable: true
  70244. });
  70245. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  70246. get: function () {
  70247. return this._influences;
  70248. },
  70249. enumerable: true,
  70250. configurable: true
  70251. });
  70252. MorphTargetManager.prototype.getActiveTarget = function (index) {
  70253. return this._activeTargets.data[index];
  70254. };
  70255. MorphTargetManager.prototype.getTarget = function (index) {
  70256. return this._targets[index];
  70257. };
  70258. MorphTargetManager.prototype.addTarget = function (target) {
  70259. var _this = this;
  70260. this._targets.push(target);
  70261. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  70262. _this._syncActiveTargets(needUpdate);
  70263. }));
  70264. this._syncActiveTargets(true);
  70265. };
  70266. MorphTargetManager.prototype.removeTarget = function (target) {
  70267. var index = this._targets.indexOf(target);
  70268. if (index >= 0) {
  70269. this._targets.splice(index, 1);
  70270. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  70271. this._syncActiveTargets(true);
  70272. }
  70273. };
  70274. /**
  70275. * Serializes the current manager into a Serialization object.
  70276. * Returns the serialized object.
  70277. */
  70278. MorphTargetManager.prototype.serialize = function () {
  70279. var serializationObject = {};
  70280. serializationObject.id = this.uniqueId;
  70281. serializationObject.targets = [];
  70282. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70283. var target = _a[_i];
  70284. serializationObject.targets.push(target.serialize());
  70285. }
  70286. return serializationObject;
  70287. };
  70288. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  70289. var influenceCount = 0;
  70290. this._activeTargets.reset();
  70291. this._supportsNormals = true;
  70292. this._supportsTangents = true;
  70293. this._vertexCount = 0;
  70294. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  70295. var target = _a[_i];
  70296. if (target.influence > 0) {
  70297. this._activeTargets.push(target);
  70298. this._tempInfluences[influenceCount++] = target.influence;
  70299. this._supportsNormals = this._supportsNormals && target.hasNormals;
  70300. this._supportsTangents = this._supportsTangents && target.hasTangents;
  70301. var positions = target.getPositions();
  70302. if (!positions) {
  70303. BABYLON.Tools.Error("Invalid target. Target must positions.");
  70304. return;
  70305. }
  70306. var vertexCount = positions.length / 3;
  70307. if (this._vertexCount === 0) {
  70308. this._vertexCount = vertexCount;
  70309. }
  70310. else if (this._vertexCount !== vertexCount) {
  70311. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  70312. return;
  70313. }
  70314. }
  70315. }
  70316. if (!this._influences || this._influences.length !== influenceCount) {
  70317. this._influences = new Float32Array(influenceCount);
  70318. }
  70319. for (var index = 0; index < influenceCount; index++) {
  70320. this._influences[index] = this._tempInfluences[index];
  70321. }
  70322. if (needUpdate && this._scene) {
  70323. // Flag meshes as dirty to resync with the active targets
  70324. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  70325. var mesh = _c[_b];
  70326. if (mesh.morphTargetManager === this) {
  70327. mesh._syncGeometryWithMorphTargetManager();
  70328. }
  70329. }
  70330. }
  70331. };
  70332. // Statics
  70333. MorphTargetManager.Parse = function (serializationObject, scene) {
  70334. var result = new MorphTargetManager(scene);
  70335. result._uniqueId = serializationObject.id;
  70336. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  70337. var targetData = _a[_i];
  70338. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  70339. }
  70340. return result;
  70341. };
  70342. return MorphTargetManager;
  70343. }());
  70344. BABYLON.MorphTargetManager = MorphTargetManager;
  70345. })(BABYLON || (BABYLON = {}));
  70346. //# sourceMappingURL=babylon.morphTargetManager.js.map
  70347. var BABYLON;
  70348. (function (BABYLON) {
  70349. var Octree = /** @class */ (function () {
  70350. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  70351. if (maxDepth === void 0) { maxDepth = 2; }
  70352. this.maxDepth = maxDepth;
  70353. this.dynamicContent = new Array();
  70354. this._maxBlockCapacity = maxBlockCapacity || 64;
  70355. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  70356. this._creationFunc = creationFunc;
  70357. }
  70358. // Methods
  70359. Octree.prototype.update = function (worldMin, worldMax, entries) {
  70360. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  70361. };
  70362. Octree.prototype.addMesh = function (entry) {
  70363. for (var index = 0; index < this.blocks.length; index++) {
  70364. var block = this.blocks[index];
  70365. block.addEntry(entry);
  70366. }
  70367. };
  70368. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  70369. this._selectionContent.reset();
  70370. for (var index = 0; index < this.blocks.length; index++) {
  70371. var block = this.blocks[index];
  70372. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  70373. }
  70374. if (allowDuplicate) {
  70375. this._selectionContent.concat(this.dynamicContent);
  70376. }
  70377. else {
  70378. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70379. }
  70380. return this._selectionContent;
  70381. };
  70382. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  70383. this._selectionContent.reset();
  70384. for (var index = 0; index < this.blocks.length; index++) {
  70385. var block = this.blocks[index];
  70386. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  70387. }
  70388. if (allowDuplicate) {
  70389. this._selectionContent.concat(this.dynamicContent);
  70390. }
  70391. else {
  70392. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70393. }
  70394. return this._selectionContent;
  70395. };
  70396. Octree.prototype.intersectsRay = function (ray) {
  70397. this._selectionContent.reset();
  70398. for (var index = 0; index < this.blocks.length; index++) {
  70399. var block = this.blocks[index];
  70400. block.intersectsRay(ray, this._selectionContent);
  70401. }
  70402. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  70403. return this._selectionContent;
  70404. };
  70405. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  70406. target.blocks = new Array();
  70407. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  70408. // Segmenting space
  70409. for (var x = 0; x < 2; x++) {
  70410. for (var y = 0; y < 2; y++) {
  70411. for (var z = 0; z < 2; z++) {
  70412. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  70413. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  70414. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  70415. block.addEntries(entries);
  70416. target.blocks.push(block);
  70417. }
  70418. }
  70419. }
  70420. };
  70421. Octree.CreationFuncForMeshes = function (entry, block) {
  70422. var boundingInfo = entry.getBoundingInfo();
  70423. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70424. block.entries.push(entry);
  70425. }
  70426. };
  70427. Octree.CreationFuncForSubMeshes = function (entry, block) {
  70428. var boundingInfo = entry.getBoundingInfo();
  70429. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  70430. block.entries.push(entry);
  70431. }
  70432. };
  70433. return Octree;
  70434. }());
  70435. BABYLON.Octree = Octree;
  70436. })(BABYLON || (BABYLON = {}));
  70437. //# sourceMappingURL=babylon.octree.js.map
  70438. var BABYLON;
  70439. (function (BABYLON) {
  70440. var OctreeBlock = /** @class */ (function () {
  70441. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  70442. this.entries = new Array();
  70443. this._boundingVectors = new Array();
  70444. this._capacity = capacity;
  70445. this._depth = depth;
  70446. this._maxDepth = maxDepth;
  70447. this._creationFunc = creationFunc;
  70448. this._minPoint = minPoint;
  70449. this._maxPoint = maxPoint;
  70450. this._boundingVectors.push(minPoint.clone());
  70451. this._boundingVectors.push(maxPoint.clone());
  70452. this._boundingVectors.push(minPoint.clone());
  70453. this._boundingVectors[2].x = maxPoint.x;
  70454. this._boundingVectors.push(minPoint.clone());
  70455. this._boundingVectors[3].y = maxPoint.y;
  70456. this._boundingVectors.push(minPoint.clone());
  70457. this._boundingVectors[4].z = maxPoint.z;
  70458. this._boundingVectors.push(maxPoint.clone());
  70459. this._boundingVectors[5].z = minPoint.z;
  70460. this._boundingVectors.push(maxPoint.clone());
  70461. this._boundingVectors[6].x = minPoint.x;
  70462. this._boundingVectors.push(maxPoint.clone());
  70463. this._boundingVectors[7].y = minPoint.y;
  70464. }
  70465. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  70466. // Property
  70467. get: function () {
  70468. return this._capacity;
  70469. },
  70470. enumerable: true,
  70471. configurable: true
  70472. });
  70473. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  70474. get: function () {
  70475. return this._minPoint;
  70476. },
  70477. enumerable: true,
  70478. configurable: true
  70479. });
  70480. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  70481. get: function () {
  70482. return this._maxPoint;
  70483. },
  70484. enumerable: true,
  70485. configurable: true
  70486. });
  70487. // Methods
  70488. OctreeBlock.prototype.addEntry = function (entry) {
  70489. if (this.blocks) {
  70490. for (var index = 0; index < this.blocks.length; index++) {
  70491. var block = this.blocks[index];
  70492. block.addEntry(entry);
  70493. }
  70494. return;
  70495. }
  70496. this._creationFunc(entry, this);
  70497. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  70498. this.createInnerBlocks();
  70499. }
  70500. };
  70501. OctreeBlock.prototype.addEntries = function (entries) {
  70502. for (var index = 0; index < entries.length; index++) {
  70503. var mesh = entries[index];
  70504. this.addEntry(mesh);
  70505. }
  70506. };
  70507. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  70508. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  70509. if (this.blocks) {
  70510. for (var index = 0; index < this.blocks.length; index++) {
  70511. var block = this.blocks[index];
  70512. block.select(frustumPlanes, selection, allowDuplicate);
  70513. }
  70514. return;
  70515. }
  70516. if (allowDuplicate) {
  70517. selection.concat(this.entries);
  70518. }
  70519. else {
  70520. selection.concatWithNoDuplicate(this.entries);
  70521. }
  70522. }
  70523. };
  70524. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  70525. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  70526. if (this.blocks) {
  70527. for (var index = 0; index < this.blocks.length; index++) {
  70528. var block = this.blocks[index];
  70529. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  70530. }
  70531. return;
  70532. }
  70533. if (allowDuplicate) {
  70534. selection.concat(this.entries);
  70535. }
  70536. else {
  70537. selection.concatWithNoDuplicate(this.entries);
  70538. }
  70539. }
  70540. };
  70541. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  70542. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  70543. if (this.blocks) {
  70544. for (var index = 0; index < this.blocks.length; index++) {
  70545. var block = this.blocks[index];
  70546. block.intersectsRay(ray, selection);
  70547. }
  70548. return;
  70549. }
  70550. selection.concatWithNoDuplicate(this.entries);
  70551. }
  70552. };
  70553. OctreeBlock.prototype.createInnerBlocks = function () {
  70554. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  70555. };
  70556. return OctreeBlock;
  70557. }());
  70558. BABYLON.OctreeBlock = OctreeBlock;
  70559. })(BABYLON || (BABYLON = {}));
  70560. //# sourceMappingURL=babylon.octreeBlock.js.map
  70561. var BABYLON;
  70562. (function (BABYLON) {
  70563. var SIMDVector3 = /** @class */ (function () {
  70564. function SIMDVector3() {
  70565. }
  70566. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  70567. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  70568. };
  70569. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  70570. var m = transformation.m;
  70571. var m0 = SIMD.Float32x4.load(m, 0);
  70572. var m1 = SIMD.Float32x4.load(m, 4);
  70573. var m2 = SIMD.Float32x4.load(m, 8);
  70574. var m3 = SIMD.Float32x4.load(m, 12);
  70575. 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));
  70576. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  70577. result.x = SIMD.Float32x4.extractLane(r, 0);
  70578. result.y = SIMD.Float32x4.extractLane(r, 1);
  70579. result.z = SIMD.Float32x4.extractLane(r, 2);
  70580. };
  70581. return SIMDVector3;
  70582. }());
  70583. var SIMDMatrix = /** @class */ (function () {
  70584. function SIMDMatrix() {
  70585. }
  70586. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  70587. var tm = this.m;
  70588. var om = other.m;
  70589. var m0 = SIMD.Float32x4.load(om, 0);
  70590. var m1 = SIMD.Float32x4.load(om, 4);
  70591. var m2 = SIMD.Float32x4.load(om, 8);
  70592. var m3 = SIMD.Float32x4.load(om, 12);
  70593. for (var i = 0; i < 16; i += 4) {
  70594. 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)))));
  70595. }
  70596. return this;
  70597. };
  70598. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  70599. var src = this.m;
  70600. var dest = other.m;
  70601. // Load the 4 rows
  70602. var src0 = SIMD.Float32x4.load(src, 0);
  70603. var src1 = SIMD.Float32x4.load(src, 4);
  70604. var src2 = SIMD.Float32x4.load(src, 8);
  70605. var src3 = SIMD.Float32x4.load(src, 12);
  70606. // Transpose the source matrix. Sort of. Not a true transpose operation
  70607. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  70608. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  70609. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  70610. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  70611. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  70612. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  70613. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  70614. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  70615. // This is a true transposition, but it will lead to an incorrect result
  70616. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  70617. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  70618. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70619. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70620. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  70621. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  70622. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  70623. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  70624. // ----
  70625. tmp1 = SIMD.Float32x4.mul(row2, row3);
  70626. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70627. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  70628. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  70629. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70630. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  70631. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  70632. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  70633. // ----
  70634. tmp1 = SIMD.Float32x4.mul(row1, row2);
  70635. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70636. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  70637. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  70638. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70639. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  70640. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  70641. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  70642. // ----
  70643. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  70644. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70645. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  70646. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  70647. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  70648. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70649. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  70650. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  70651. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  70652. // ----
  70653. tmp1 = SIMD.Float32x4.mul(row0, row1);
  70654. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70655. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70656. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  70657. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70658. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  70659. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  70660. // ----
  70661. tmp1 = SIMD.Float32x4.mul(row0, row3);
  70662. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70663. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  70664. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  70665. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70666. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  70667. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  70668. // ----
  70669. tmp1 = SIMD.Float32x4.mul(row0, row2);
  70670. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  70671. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  70672. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  70673. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  70674. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  70675. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  70676. // Compute determinant
  70677. var det = SIMD.Float32x4.mul(row0, minor0);
  70678. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  70679. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  70680. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  70681. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  70682. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  70683. // These shuffles aren't necessary if the faulty transposition is done
  70684. // up at the top of this function.
  70685. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  70686. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  70687. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  70688. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  70689. // Compute final values by multiplying with 1/det
  70690. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  70691. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  70692. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  70693. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  70694. return this;
  70695. };
  70696. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  70697. var out = result.m;
  70698. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  70699. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  70700. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  70701. // cc.kmVec3Subtract(f, pCenter, pEye);
  70702. var f = SIMD.Float32x4.sub(center, eye);
  70703. // cc.kmVec3Normalize(f, f);
  70704. var tmp = SIMD.Float32x4.mul(f, f);
  70705. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70706. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70707. // cc.kmVec3Assign(up, pUp);
  70708. // cc.kmVec3Normalize(up, up);
  70709. tmp = SIMD.Float32x4.mul(up, up);
  70710. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70711. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70712. // cc.kmVec3Cross(s, f, up);
  70713. 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)));
  70714. // cc.kmVec3Normalize(s, s);
  70715. tmp = SIMD.Float32x4.mul(s, s);
  70716. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70717. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70718. // cc.kmVec3Cross(u, s, f);
  70719. 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)));
  70720. // cc.kmVec3Normalize(s, s);
  70721. tmp = SIMD.Float32x4.mul(s, s);
  70722. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  70723. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  70724. var zero = SIMD.Float32x4.splat(0.0);
  70725. s = SIMD.Float32x4.neg(s);
  70726. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  70727. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  70728. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  70729. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  70730. 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);
  70731. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  70732. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  70733. 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)))));
  70734. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  70735. 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)))));
  70736. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  70737. 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)))));
  70738. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  70739. 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)))));
  70740. };
  70741. return SIMDMatrix;
  70742. }());
  70743. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  70744. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  70745. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  70746. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  70747. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  70748. var SIMDHelper = /** @class */ (function () {
  70749. function SIMDHelper() {
  70750. }
  70751. Object.defineProperty(SIMDHelper, "IsEnabled", {
  70752. get: function () {
  70753. return SIMDHelper._isEnabled;
  70754. },
  70755. enumerable: true,
  70756. configurable: true
  70757. });
  70758. SIMDHelper.DisableSIMD = function () {
  70759. // Replace functions
  70760. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  70761. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  70762. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  70763. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  70764. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  70765. SIMDHelper._isEnabled = false;
  70766. };
  70767. SIMDHelper.EnableSIMD = function () {
  70768. if (self.SIMD === undefined) {
  70769. return;
  70770. }
  70771. // check if polyfills needed
  70772. if (!self.Math.fround) {
  70773. self.Math.fround = (function (array) { return function (x) {
  70774. return array[0] = x, array[0];
  70775. }; })(new Float32Array(1));
  70776. }
  70777. if (!self.Math.imul) {
  70778. self.Math.imul = function (a, b) {
  70779. var ah = (a >>> 16) & 0xffff;
  70780. var al = a & 0xffff;
  70781. var bh = (b >>> 16) & 0xffff;
  70782. var bl = b & 0xffff;
  70783. // the shift by 0 fixes the sign on the high part
  70784. // the final |0 converts the unsigned value into a signed value
  70785. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  70786. };
  70787. }
  70788. // Replace functions
  70789. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  70790. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  70791. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  70792. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  70793. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  70794. SIMDHelper._isEnabled = true;
  70795. };
  70796. SIMDHelper._isEnabled = false;
  70797. return SIMDHelper;
  70798. }());
  70799. BABYLON.SIMDHelper = SIMDHelper;
  70800. })(BABYLON || (BABYLON = {}));
  70801. //# sourceMappingURL=babylon.math.SIMD.js.map
  70802. var BABYLON;
  70803. (function (BABYLON) {
  70804. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  70805. __extends(VRDistortionCorrectionPostProcess, _super);
  70806. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  70807. var _this = _super.call(this, name, "vrDistortionCorrection", [
  70808. 'LensCenter',
  70809. 'Scale',
  70810. 'ScaleIn',
  70811. 'HmdWarpParam'
  70812. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  70813. _this._isRightEye = isRightEye;
  70814. _this._distortionFactors = vrMetrics.distortionK;
  70815. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  70816. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  70817. _this.adaptScaleToCurrentViewport = true;
  70818. _this.onSizeChangedObservable.add(function () {
  70819. _this.aspectRatio = _this.width * .5 / _this.height;
  70820. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  70821. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  70822. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  70823. });
  70824. _this.onApplyObservable.add(function (effect) {
  70825. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  70826. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  70827. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  70828. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  70829. });
  70830. return _this;
  70831. }
  70832. return VRDistortionCorrectionPostProcess;
  70833. }(BABYLON.PostProcess));
  70834. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  70835. })(BABYLON || (BABYLON = {}));
  70836. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  70837. var BABYLON;
  70838. (function (BABYLON) {
  70839. var AnaglyphPostProcess = /** @class */ (function (_super) {
  70840. __extends(AnaglyphPostProcess, _super);
  70841. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  70842. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  70843. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70844. _this.onApplyObservable.add(function (effect) {
  70845. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  70846. });
  70847. return _this;
  70848. }
  70849. return AnaglyphPostProcess;
  70850. }(BABYLON.PostProcess));
  70851. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  70852. })(BABYLON || (BABYLON = {}));
  70853. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  70854. var BABYLON;
  70855. (function (BABYLON) {
  70856. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  70857. __extends(StereoscopicInterlacePostProcess, _super);
  70858. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  70859. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  70860. _this._passedProcess = rigCameras[0]._rigPostProcess;
  70861. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70862. _this.onSizeChangedObservable.add(function () {
  70863. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  70864. });
  70865. _this.onApplyObservable.add(function (effect) {
  70866. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  70867. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  70868. });
  70869. return _this;
  70870. }
  70871. return StereoscopicInterlacePostProcess;
  70872. }(BABYLON.PostProcess));
  70873. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  70874. })(BABYLON || (BABYLON = {}));
  70875. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  70876. var BABYLON;
  70877. (function (BABYLON) {
  70878. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  70879. function FreeCameraDeviceOrientationInput() {
  70880. var _this = this;
  70881. this._screenOrientationAngle = 0;
  70882. this._screenQuaternion = new BABYLON.Quaternion();
  70883. this._alpha = 0;
  70884. this._beta = 0;
  70885. this._gamma = 0;
  70886. this._orientationChanged = function () {
  70887. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  70888. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  70889. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  70890. };
  70891. this._deviceOrientation = function (evt) {
  70892. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  70893. _this._beta = evt.beta !== null ? evt.beta : 0;
  70894. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  70895. };
  70896. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  70897. this._orientationChanged();
  70898. }
  70899. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  70900. get: function () {
  70901. return this._camera;
  70902. },
  70903. set: function (camera) {
  70904. this._camera = camera;
  70905. if (this._camera != null && !this._camera.rotationQuaternion) {
  70906. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  70907. }
  70908. },
  70909. enumerable: true,
  70910. configurable: true
  70911. });
  70912. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70913. window.addEventListener("orientationchange", this._orientationChanged);
  70914. window.addEventListener("deviceorientation", this._deviceOrientation);
  70915. //In certain cases, the attach control is called AFTER orientation was changed,
  70916. //So this is needed.
  70917. this._orientationChanged();
  70918. };
  70919. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  70920. window.removeEventListener("orientationchange", this._orientationChanged);
  70921. window.removeEventListener("deviceorientation", this._deviceOrientation);
  70922. };
  70923. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  70924. //if no device orientation provided, don't update the rotation.
  70925. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  70926. if (!this._alpha)
  70927. return;
  70928. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  70929. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  70930. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  70931. //Mirror on XY Plane
  70932. this._camera.rotationQuaternion.z *= -1;
  70933. this._camera.rotationQuaternion.w *= -1;
  70934. };
  70935. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  70936. return "FreeCameraDeviceOrientationInput";
  70937. };
  70938. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  70939. return "deviceOrientation";
  70940. };
  70941. return FreeCameraDeviceOrientationInput;
  70942. }());
  70943. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  70944. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  70945. })(BABYLON || (BABYLON = {}));
  70946. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  70947. var BABYLON;
  70948. (function (BABYLON) {
  70949. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  70950. function ArcRotateCameraVRDeviceOrientationInput() {
  70951. this.alphaCorrection = 1;
  70952. this.betaCorrection = 1;
  70953. this.gammaCorrection = 1;
  70954. this._alpha = 0;
  70955. this._gamma = 0;
  70956. this._dirty = false;
  70957. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  70958. }
  70959. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  70960. this.camera.attachControl(element, noPreventDefault);
  70961. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  70962. };
  70963. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  70964. if (evt.alpha !== null) {
  70965. this._alpha = +evt.alpha | 0;
  70966. }
  70967. if (evt.gamma !== null) {
  70968. this._gamma = +evt.gamma | 0;
  70969. }
  70970. this._dirty = true;
  70971. };
  70972. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  70973. if (this._dirty) {
  70974. this._dirty = false;
  70975. if (this._gamma < 0) {
  70976. this._gamma = 180 + this._gamma;
  70977. }
  70978. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  70979. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  70980. }
  70981. };
  70982. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  70983. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  70984. };
  70985. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  70986. return "ArcRotateCameraVRDeviceOrientationInput";
  70987. };
  70988. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  70989. return "VRDeviceOrientation";
  70990. };
  70991. return ArcRotateCameraVRDeviceOrientationInput;
  70992. }());
  70993. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  70994. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  70995. })(BABYLON || (BABYLON = {}));
  70996. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  70997. var BABYLON;
  70998. (function (BABYLON) {
  70999. var VRCameraMetrics = /** @class */ (function () {
  71000. function VRCameraMetrics() {
  71001. this.compensateDistortion = true;
  71002. }
  71003. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  71004. get: function () {
  71005. return this.hResolution / (2 * this.vResolution);
  71006. },
  71007. enumerable: true,
  71008. configurable: true
  71009. });
  71010. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  71011. get: function () {
  71012. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  71013. },
  71014. enumerable: true,
  71015. configurable: true
  71016. });
  71017. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  71018. get: function () {
  71019. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71020. var h = (4 * meters) / this.hScreenSize;
  71021. return BABYLON.Matrix.Translation(h, 0, 0);
  71022. },
  71023. enumerable: true,
  71024. configurable: true
  71025. });
  71026. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  71027. get: function () {
  71028. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71029. var h = (4 * meters) / this.hScreenSize;
  71030. return BABYLON.Matrix.Translation(-h, 0, 0);
  71031. },
  71032. enumerable: true,
  71033. configurable: true
  71034. });
  71035. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  71036. get: function () {
  71037. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  71038. },
  71039. enumerable: true,
  71040. configurable: true
  71041. });
  71042. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  71043. get: function () {
  71044. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  71045. },
  71046. enumerable: true,
  71047. configurable: true
  71048. });
  71049. VRCameraMetrics.GetDefault = function () {
  71050. var result = new VRCameraMetrics();
  71051. result.hResolution = 1280;
  71052. result.vResolution = 800;
  71053. result.hScreenSize = 0.149759993;
  71054. result.vScreenSize = 0.0935999975;
  71055. result.vScreenCenter = 0.0467999987;
  71056. result.eyeToScreenDistance = 0.0410000011;
  71057. result.lensSeparationDistance = 0.0635000020;
  71058. result.interpupillaryDistance = 0.0640000030;
  71059. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  71060. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  71061. result.postProcessScaleFactor = 1.714605507808412;
  71062. result.lensCenterOffset = 0.151976421;
  71063. return result;
  71064. };
  71065. return VRCameraMetrics;
  71066. }());
  71067. BABYLON.VRCameraMetrics = VRCameraMetrics;
  71068. })(BABYLON || (BABYLON = {}));
  71069. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  71070. var BABYLON;
  71071. (function (BABYLON) {
  71072. var WebVRFreeCamera = /** @class */ (function (_super) {
  71073. __extends(WebVRFreeCamera, _super);
  71074. function WebVRFreeCamera(name, position, scene, webVROptions) {
  71075. if (webVROptions === void 0) { webVROptions = {}; }
  71076. var _this = _super.call(this, name, position, scene) || this;
  71077. _this.webVROptions = webVROptions;
  71078. _this._vrDevice = null;
  71079. _this.rawPose = null;
  71080. _this._specsVersion = "1.1";
  71081. _this._attached = false;
  71082. _this._descendants = [];
  71083. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71084. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71085. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  71086. _this._standingMatrix = null;
  71087. // Represents device position and rotation in babylon space
  71088. _this.devicePosition = BABYLON.Vector3.Zero();
  71089. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  71090. _this.deviceScaleFactor = 1;
  71091. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71092. _this._worldToDevice = BABYLON.Matrix.Identity();
  71093. _this.controllers = [];
  71094. _this.onControllersAttachedObservable = new BABYLON.Observable();
  71095. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  71096. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  71097. _this._defaultHeight = 0;
  71098. _this.deviceDistanceToRoomGround = function () {
  71099. if (_this._standingMatrix) {
  71100. // Add standing matrix offset to get real offset from ground in room
  71101. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  71102. return _this._deviceRoomPosition.y + _this._workingVector.y;
  71103. }
  71104. else {
  71105. return _this._defaultHeight;
  71106. }
  71107. };
  71108. _this.useStandingMatrix = function (callback) {
  71109. if (callback === void 0) { callback = function (bool) { }; }
  71110. // Use standing matrix if availible
  71111. if (!navigator || !navigator.getVRDisplays) {
  71112. callback(false);
  71113. }
  71114. else {
  71115. navigator.getVRDisplays().then(function (displays) {
  71116. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  71117. callback(false);
  71118. }
  71119. else {
  71120. _this._standingMatrix = new BABYLON.Matrix();
  71121. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  71122. if (!_this.getScene().useRightHandedSystem) {
  71123. [2, 6, 8, 9, 14].forEach(function (num) {
  71124. if (_this._standingMatrix) {
  71125. _this._standingMatrix.m[num] *= -1;
  71126. }
  71127. });
  71128. }
  71129. callback(true);
  71130. }
  71131. });
  71132. }
  71133. };
  71134. _this._workingVector = BABYLON.Vector3.Zero();
  71135. _this._oneVector = BABYLON.Vector3.One();
  71136. _this._workingMatrix = BABYLON.Matrix.Identity();
  71137. _this._cache.position = BABYLON.Vector3.Zero();
  71138. if (webVROptions.defaultHeight) {
  71139. _this._defaultHeight = webVROptions.defaultHeight;
  71140. _this.position.y = _this._defaultHeight;
  71141. }
  71142. _this.minZ = 0.1;
  71143. //legacy support - the compensation boolean was removed.
  71144. if (arguments.length === 5) {
  71145. _this.webVROptions = arguments[4];
  71146. }
  71147. // default webVR options
  71148. if (_this.webVROptions.trackPosition == undefined) {
  71149. _this.webVROptions.trackPosition = true;
  71150. }
  71151. if (_this.webVROptions.controllerMeshes == undefined) {
  71152. _this.webVROptions.controllerMeshes = true;
  71153. }
  71154. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  71155. _this.webVROptions.defaultLightingOnControllers = true;
  71156. }
  71157. _this.rotationQuaternion = new BABYLON.Quaternion();
  71158. if (_this.webVROptions && _this.webVROptions.positionScale) {
  71159. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  71160. }
  71161. //enable VR
  71162. var engine = _this.getEngine();
  71163. _this._onVREnabled = function (success) { if (success) {
  71164. _this.initControllers();
  71165. } };
  71166. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  71167. engine.initWebVR().add(function (event) {
  71168. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  71169. return;
  71170. }
  71171. _this._vrDevice = event.vrDisplay;
  71172. //reset the rig parameters.
  71173. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  71174. if (_this._attached) {
  71175. _this.getEngine().enableVR();
  71176. }
  71177. });
  71178. if (typeof (VRFrameData) !== "undefined")
  71179. _this._frameData = new VRFrameData();
  71180. /**
  71181. * The idea behind the following lines:
  71182. * objects that have the camera as parent should actually have the rig cameras as a parent.
  71183. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  71184. * the second will not show it correctly.
  71185. *
  71186. * To solve this - each object that has the camera as parent will be added to a protected array.
  71187. * When the rig camera renders, it will take this array and set all of those to be its children.
  71188. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  71189. * Amazing!
  71190. */
  71191. scene.onBeforeCameraRenderObservable.add(function (camera) {
  71192. if (camera.parent === _this && _this.rigParenting) {
  71193. _this._descendants = _this.getDescendants(true, function (n) {
  71194. // don't take the cameras or the controllers!
  71195. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  71196. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  71197. return !isController && !isRigCamera;
  71198. });
  71199. _this._descendants.forEach(function (node) {
  71200. node.parent = camera;
  71201. });
  71202. }
  71203. });
  71204. scene.onAfterCameraRenderObservable.add(function (camera) {
  71205. if (camera.parent === _this && _this.rigParenting) {
  71206. _this._descendants.forEach(function (node) {
  71207. node.parent = _this;
  71208. });
  71209. }
  71210. });
  71211. return _this;
  71212. }
  71213. WebVRFreeCamera.prototype.dispose = function () {
  71214. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  71215. _super.prototype.dispose.call(this);
  71216. };
  71217. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  71218. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  71219. var gp = _a[_i];
  71220. if (gp.hand === name) {
  71221. return gp;
  71222. }
  71223. }
  71224. return null;
  71225. };
  71226. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  71227. get: function () {
  71228. if (!this._leftController) {
  71229. this._leftController = this.getControllerByName("left");
  71230. }
  71231. return this._leftController;
  71232. },
  71233. enumerable: true,
  71234. configurable: true
  71235. });
  71236. ;
  71237. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  71238. get: function () {
  71239. if (!this._rightController) {
  71240. this._rightController = this.getControllerByName("right");
  71241. }
  71242. return this._rightController;
  71243. },
  71244. enumerable: true,
  71245. configurable: true
  71246. });
  71247. ;
  71248. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  71249. if (length === void 0) { length = 100; }
  71250. if (this.leftCamera) {
  71251. // Use left eye to avoid computation to compute center on every call
  71252. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  71253. }
  71254. else {
  71255. return _super.prototype.getForwardRay.call(this, length);
  71256. }
  71257. };
  71258. WebVRFreeCamera.prototype._checkInputs = function () {
  71259. if (this._vrDevice && this._vrDevice.isPresenting) {
  71260. this._vrDevice.getFrameData(this._frameData);
  71261. this.updateFromDevice(this._frameData.pose);
  71262. }
  71263. _super.prototype._checkInputs.call(this);
  71264. };
  71265. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  71266. if (poseData && poseData.orientation) {
  71267. this.rawPose = poseData;
  71268. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  71269. if (this.getScene().useRightHandedSystem) {
  71270. this._deviceRoomRotationQuaternion.z *= -1;
  71271. this._deviceRoomRotationQuaternion.w *= -1;
  71272. }
  71273. if (this.webVROptions.trackPosition && this.rawPose.position) {
  71274. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  71275. if (this.getScene().useRightHandedSystem) {
  71276. this._deviceRoomPosition.z *= -1;
  71277. }
  71278. }
  71279. }
  71280. };
  71281. /**
  71282. * WebVR's attach control will start broadcasting frames to the device.
  71283. * Note that in certain browsers (chrome for example) this function must be called
  71284. * within a user-interaction callback. Example:
  71285. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  71286. *
  71287. * @param {HTMLElement} element
  71288. * @param {boolean} [noPreventDefault]
  71289. *
  71290. * @memberOf WebVRFreeCamera
  71291. */
  71292. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  71293. _super.prototype.attachControl.call(this, element, noPreventDefault);
  71294. this._attached = true;
  71295. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  71296. if (this._vrDevice) {
  71297. this.getEngine().enableVR();
  71298. }
  71299. };
  71300. WebVRFreeCamera.prototype.detachControl = function (element) {
  71301. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71302. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71303. _super.prototype.detachControl.call(this, element);
  71304. this._attached = false;
  71305. this.getEngine().disableVR();
  71306. };
  71307. WebVRFreeCamera.prototype.getClassName = function () {
  71308. return "WebVRFreeCamera";
  71309. };
  71310. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  71311. //uses the vrDisplay's "resetPose()".
  71312. //pitch and roll won't be affected.
  71313. this._vrDevice.resetPose();
  71314. };
  71315. WebVRFreeCamera.prototype._updateRigCameras = function () {
  71316. var camLeft = this._rigCameras[0];
  71317. var camRight = this._rigCameras[1];
  71318. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71319. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  71320. camLeft.position.copyFrom(this._deviceRoomPosition);
  71321. camRight.position.copyFrom(this._deviceRoomPosition);
  71322. };
  71323. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  71324. var _this = this;
  71325. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  71326. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  71327. this.update();
  71328. // Set working vector to the device position in room space rotated by the new rotation
  71329. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  71330. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  71331. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  71332. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  71333. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  71334. // Add translation from anchor position
  71335. this._deviceToWorld.getTranslationToRef(this._workingVector);
  71336. this._workingVector.addInPlace(this.position);
  71337. this._workingVector.subtractInPlace(this._cache.position);
  71338. this._deviceToWorld.setTranslation(this._workingVector);
  71339. // Set an inverted matrix to be used when updating the camera
  71340. this._deviceToWorld.invertToRef(this._worldToDevice);
  71341. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  71342. this.controllers.forEach(function (controller) {
  71343. controller._deviceToWorld = _this._deviceToWorld;
  71344. controller.update();
  71345. });
  71346. this.update();
  71347. }
  71348. if (!ignoreParentClass) {
  71349. _super.prototype._updateCache.call(this);
  71350. }
  71351. };
  71352. WebVRFreeCamera.prototype.update = function () {
  71353. // Get current device position in babylon world
  71354. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  71355. // Get current device rotation in babylon world
  71356. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  71357. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  71358. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71359. _super.prototype.update.call(this);
  71360. };
  71361. WebVRFreeCamera.prototype._getViewMatrix = function () {
  71362. return BABYLON.Matrix.Identity();
  71363. };
  71364. /**
  71365. * This function is called by the two RIG cameras.
  71366. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  71367. */
  71368. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  71369. var _this = this;
  71370. //WebVR 1.1
  71371. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  71372. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  71373. if (!this.getScene().useRightHandedSystem) {
  71374. [2, 6, 8, 9, 14].forEach(function (num) {
  71375. _this._webvrViewMatrix.m[num] *= -1;
  71376. });
  71377. }
  71378. // update the camera rotation matrix
  71379. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  71380. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  71381. // Computing target and final matrix
  71382. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  71383. var parentCamera = this._cameraRigParams["parentCamera"];
  71384. // should the view matrix be updated with scale and position offset?
  71385. if (parentCamera.deviceScaleFactor !== 1) {
  71386. this._webvrViewMatrix.invert();
  71387. // scale the position, if set
  71388. if (parentCamera.deviceScaleFactor) {
  71389. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  71390. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  71391. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  71392. }
  71393. this._webvrViewMatrix.invert();
  71394. }
  71395. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  71396. return this._webvrViewMatrix;
  71397. };
  71398. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  71399. var _this = this;
  71400. var parentCamera = this.parent;
  71401. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  71402. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  71403. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  71404. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  71405. //babylon compatible matrix
  71406. if (!this.getScene().useRightHandedSystem) {
  71407. [8, 9, 10, 11].forEach(function (num) {
  71408. _this._projectionMatrix.m[num] *= -1;
  71409. });
  71410. }
  71411. return this._projectionMatrix;
  71412. };
  71413. WebVRFreeCamera.prototype.initControllers = function () {
  71414. var _this = this;
  71415. this.controllers = [];
  71416. var manager = this.getScene().gamepadManager;
  71417. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71418. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71419. var webVrController = gamepad;
  71420. if (webVrController.defaultModel) {
  71421. webVrController.defaultModel.setEnabled(false);
  71422. }
  71423. if (webVrController.hand === "right") {
  71424. _this._rightController = null;
  71425. }
  71426. if (webVrController.hand === "left") {
  71427. _this._rightController = null;
  71428. }
  71429. var controllerIndex = _this.controllers.indexOf(webVrController);
  71430. if (controllerIndex !== -1) {
  71431. _this.controllers.splice(controllerIndex, 1);
  71432. }
  71433. }
  71434. });
  71435. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71436. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  71437. var webVrController_1 = gamepad;
  71438. webVrController_1._deviceToWorld = _this._deviceToWorld;
  71439. if (_this.webVROptions.controllerMeshes) {
  71440. if (webVrController_1.defaultModel) {
  71441. webVrController_1.defaultModel.setEnabled(true);
  71442. }
  71443. else {
  71444. // Load the meshes
  71445. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  71446. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  71447. if (_this.webVROptions.defaultLightingOnControllers) {
  71448. if (!_this._lightOnControllers) {
  71449. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  71450. }
  71451. var activateLightOnSubMeshes_1 = function (mesh, light) {
  71452. var children = mesh.getChildren();
  71453. if (children.length !== 0) {
  71454. children.forEach(function (mesh) {
  71455. light.includedOnlyMeshes.push(mesh);
  71456. activateLightOnSubMeshes_1(mesh, light);
  71457. });
  71458. }
  71459. };
  71460. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  71461. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  71462. }
  71463. });
  71464. }
  71465. }
  71466. webVrController_1.attachToPoseControlledCamera(_this);
  71467. // since this is async - sanity check. Is the controller already stored?
  71468. if (_this.controllers.indexOf(webVrController_1) === -1) {
  71469. //add to the controllers array
  71470. _this.controllers.push(webVrController_1);
  71471. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  71472. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  71473. // So we're overriding setting left & right manually to be sure
  71474. var firstViveWandDetected = false;
  71475. for (var i = 0; i < _this.controllers.length; i++) {
  71476. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  71477. if (!firstViveWandDetected) {
  71478. firstViveWandDetected = true;
  71479. _this.controllers[i].hand = "left";
  71480. }
  71481. else {
  71482. _this.controllers[i].hand = "right";
  71483. }
  71484. }
  71485. }
  71486. //did we find enough controllers? Great! let the developer know.
  71487. if (_this.controllers.length >= 2) {
  71488. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  71489. }
  71490. }
  71491. }
  71492. });
  71493. };
  71494. return WebVRFreeCamera;
  71495. }(BABYLON.FreeCamera));
  71496. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  71497. })(BABYLON || (BABYLON = {}));
  71498. //# sourceMappingURL=babylon.webVRCamera.js.map
  71499. var BABYLON;
  71500. (function (BABYLON) {
  71501. // We're mainly based on the logic defined into the FreeCamera code
  71502. var DeviceOrientationCamera = /** @class */ (function (_super) {
  71503. __extends(DeviceOrientationCamera, _super);
  71504. function DeviceOrientationCamera(name, position, scene) {
  71505. var _this = _super.call(this, name, position, scene) || this;
  71506. _this._quaternionCache = new BABYLON.Quaternion();
  71507. _this.inputs.addDeviceOrientation();
  71508. return _this;
  71509. }
  71510. DeviceOrientationCamera.prototype.getClassName = function () {
  71511. return "DeviceOrientationCamera";
  71512. };
  71513. DeviceOrientationCamera.prototype._checkInputs = function () {
  71514. _super.prototype._checkInputs.call(this);
  71515. this._quaternionCache.copyFrom(this.rotationQuaternion);
  71516. if (this._initialQuaternion) {
  71517. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71518. }
  71519. };
  71520. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  71521. var _this = this;
  71522. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  71523. //can only work if this camera has a rotation quaternion already.
  71524. if (!this.rotationQuaternion)
  71525. return;
  71526. if (!this._initialQuaternion) {
  71527. this._initialQuaternion = new BABYLON.Quaternion();
  71528. }
  71529. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  71530. ['x', 'y', 'z'].forEach(function (axisName) {
  71531. if (!axis[axisName]) {
  71532. _this._initialQuaternion[axisName] = 0;
  71533. }
  71534. else {
  71535. _this._initialQuaternion[axisName] *= -1;
  71536. }
  71537. });
  71538. this._initialQuaternion.normalize();
  71539. //force rotation update
  71540. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  71541. };
  71542. return DeviceOrientationCamera;
  71543. }(BABYLON.FreeCamera));
  71544. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  71545. })(BABYLON || (BABYLON = {}));
  71546. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  71547. var BABYLON;
  71548. (function (BABYLON) {
  71549. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  71550. __extends(VRDeviceOrientationFreeCamera, _super);
  71551. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71552. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71553. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71554. var _this = _super.call(this, name, position, scene) || this;
  71555. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71556. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71557. return _this;
  71558. }
  71559. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  71560. return "VRDeviceOrientationFreeCamera";
  71561. };
  71562. return VRDeviceOrientationFreeCamera;
  71563. }(BABYLON.DeviceOrientationCamera));
  71564. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  71565. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  71566. __extends(VRDeviceOrientationGamepadCamera, _super);
  71567. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  71568. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71569. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71570. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  71571. _this.inputs.addGamepad();
  71572. return _this;
  71573. }
  71574. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  71575. return "VRDeviceOrientationGamepadCamera";
  71576. };
  71577. return VRDeviceOrientationGamepadCamera;
  71578. }(VRDeviceOrientationFreeCamera));
  71579. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  71580. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  71581. __extends(VRDeviceOrientationArcRotateCamera, _super);
  71582. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  71583. if (compensateDistortion === void 0) { compensateDistortion = true; }
  71584. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  71585. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71586. vrCameraMetrics.compensateDistortion = compensateDistortion;
  71587. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  71588. _this.inputs.addVRDeviceOrientation();
  71589. return _this;
  71590. }
  71591. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  71592. return "VRDeviceOrientationArcRotateCamera";
  71593. };
  71594. return VRDeviceOrientationArcRotateCamera;
  71595. }(BABYLON.ArcRotateCamera));
  71596. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  71597. })(BABYLON || (BABYLON = {}));
  71598. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  71599. var BABYLON;
  71600. (function (BABYLON) {
  71601. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  71602. __extends(AnaglyphFreeCamera, _super);
  71603. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  71604. var _this = _super.call(this, name, position, scene) || this;
  71605. _this.interaxialDistance = interaxialDistance;
  71606. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71607. return _this;
  71608. }
  71609. AnaglyphFreeCamera.prototype.getClassName = function () {
  71610. return "AnaglyphFreeCamera";
  71611. };
  71612. return AnaglyphFreeCamera;
  71613. }(BABYLON.FreeCamera));
  71614. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  71615. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  71616. __extends(AnaglyphArcRotateCamera, _super);
  71617. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  71618. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71619. _this.interaxialDistance = interaxialDistance;
  71620. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71621. return _this;
  71622. }
  71623. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  71624. return "AnaglyphArcRotateCamera";
  71625. };
  71626. return AnaglyphArcRotateCamera;
  71627. }(BABYLON.ArcRotateCamera));
  71628. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  71629. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  71630. __extends(AnaglyphGamepadCamera, _super);
  71631. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  71632. var _this = _super.call(this, name, position, scene) || this;
  71633. _this.interaxialDistance = interaxialDistance;
  71634. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71635. return _this;
  71636. }
  71637. AnaglyphGamepadCamera.prototype.getClassName = function () {
  71638. return "AnaglyphGamepadCamera";
  71639. };
  71640. return AnaglyphGamepadCamera;
  71641. }(BABYLON.GamepadCamera));
  71642. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  71643. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  71644. __extends(AnaglyphUniversalCamera, _super);
  71645. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  71646. var _this = _super.call(this, name, position, scene) || this;
  71647. _this.interaxialDistance = interaxialDistance;
  71648. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  71649. return _this;
  71650. }
  71651. AnaglyphUniversalCamera.prototype.getClassName = function () {
  71652. return "AnaglyphUniversalCamera";
  71653. };
  71654. return AnaglyphUniversalCamera;
  71655. }(BABYLON.UniversalCamera));
  71656. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  71657. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  71658. __extends(StereoscopicFreeCamera, _super);
  71659. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71660. var _this = _super.call(this, name, position, scene) || this;
  71661. _this.interaxialDistance = interaxialDistance;
  71662. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71663. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71664. return _this;
  71665. }
  71666. StereoscopicFreeCamera.prototype.getClassName = function () {
  71667. return "StereoscopicFreeCamera";
  71668. };
  71669. return StereoscopicFreeCamera;
  71670. }(BABYLON.FreeCamera));
  71671. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  71672. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  71673. __extends(StereoscopicArcRotateCamera, _super);
  71674. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  71675. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  71676. _this.interaxialDistance = interaxialDistance;
  71677. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71678. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71679. return _this;
  71680. }
  71681. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  71682. return "StereoscopicArcRotateCamera";
  71683. };
  71684. return StereoscopicArcRotateCamera;
  71685. }(BABYLON.ArcRotateCamera));
  71686. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  71687. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  71688. __extends(StereoscopicGamepadCamera, _super);
  71689. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71690. var _this = _super.call(this, name, position, scene) || this;
  71691. _this.interaxialDistance = interaxialDistance;
  71692. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71693. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71694. return _this;
  71695. }
  71696. StereoscopicGamepadCamera.prototype.getClassName = function () {
  71697. return "StereoscopicGamepadCamera";
  71698. };
  71699. return StereoscopicGamepadCamera;
  71700. }(BABYLON.GamepadCamera));
  71701. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  71702. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  71703. __extends(StereoscopicUniversalCamera, _super);
  71704. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  71705. var _this = _super.call(this, name, position, scene) || this;
  71706. _this.interaxialDistance = interaxialDistance;
  71707. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  71708. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  71709. return _this;
  71710. }
  71711. StereoscopicUniversalCamera.prototype.getClassName = function () {
  71712. return "StereoscopicUniversalCamera";
  71713. };
  71714. return StereoscopicUniversalCamera;
  71715. }(BABYLON.UniversalCamera));
  71716. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  71717. })(BABYLON || (BABYLON = {}));
  71718. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  71719. var BABYLON;
  71720. (function (BABYLON) {
  71721. var VRExperienceHelper = /** @class */ (function () {
  71722. function VRExperienceHelper(scene, webVROptions) {
  71723. if (webVROptions === void 0) { webVROptions = {}; }
  71724. var _this = this;
  71725. this.webVROptions = webVROptions;
  71726. // Can the system support WebVR, even if a headset isn't plugged in?
  71727. this._webVRsupported = false;
  71728. // If WebVR is supported, is a headset plugged in and are we ready to present?
  71729. this._webVRready = false;
  71730. // Are we waiting for the requestPresent callback to complete?
  71731. this._webVRrequesting = false;
  71732. // Are we presenting to the headset right now?
  71733. this._webVRpresenting = false;
  71734. // Are we presenting in the fullscreen fallback?
  71735. this._fullscreenVRpresenting = false;
  71736. this.onEnteringVR = new BABYLON.Observable();
  71737. this.onExitingVR = new BABYLON.Observable();
  71738. this.onControllerMeshLoaded = new BABYLON.Observable();
  71739. this._useCustomVRButton = false;
  71740. this._teleportationRequested = false;
  71741. this._teleportationEnabledOnLeftController = false;
  71742. this._teleportationEnabledOnRightController = false;
  71743. this._interactionsEnabledOnLeftController = false;
  71744. this._interactionsEnabledOnRightController = false;
  71745. this._leftControllerReady = false;
  71746. this._rightControllerReady = false;
  71747. this._floorMeshesCollection = [];
  71748. this._teleportationAllowed = false;
  71749. this._rotationAllowed = true;
  71750. this._teleportationRequestInitiated = false;
  71751. this._teleportationBackRequestInitiated = false;
  71752. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  71753. this._rotationRightAsked = false;
  71754. this._rotationLeftAsked = false;
  71755. this._isDefaultTeleportationTarget = true;
  71756. this._teleportationFillColor = "#444444";
  71757. this._teleportationBorderColor = "#FFFFFF";
  71758. this._rotationAngle = 0;
  71759. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  71760. this._padSensibilityUp = 0.65;
  71761. this._padSensibilityDown = 0.35;
  71762. this.onNewMeshSelected = new BABYLON.Observable();
  71763. this._pointerDownOnMeshAsked = false;
  71764. this._isActionableMesh = false;
  71765. this._teleportationEnabled = false;
  71766. this._interactionsEnabled = false;
  71767. this._interactionsRequested = false;
  71768. this._displayGaze = true;
  71769. this._displayLaserPointer = true;
  71770. this._dpadPressed = true;
  71771. this._onResize = function () {
  71772. _this.moveButtonToBottomRight();
  71773. if (_this._fullscreenVRpresenting && _this._webVRready) {
  71774. _this.exitVR();
  71775. }
  71776. };
  71777. this._onFullscreenChange = function () {
  71778. if (document.fullscreen !== undefined) {
  71779. _this._fullscreenVRpresenting = document.fullscreen;
  71780. }
  71781. else if (document.mozFullScreen !== undefined) {
  71782. _this._fullscreenVRpresenting = document.mozFullScreen;
  71783. }
  71784. else if (document.webkitIsFullScreen !== undefined) {
  71785. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  71786. }
  71787. else if (document.msIsFullScreen !== undefined) {
  71788. _this._fullscreenVRpresenting = document.msIsFullScreen;
  71789. }
  71790. if (!_this._fullscreenVRpresenting && _this._canvas) {
  71791. _this.exitVR();
  71792. if (!_this._useCustomVRButton) {
  71793. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  71794. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  71795. }
  71796. }
  71797. };
  71798. this.beforeRender = function () {
  71799. _this._castRayAndSelectObject();
  71800. };
  71801. this._onNewGamepadConnected = function (gamepad) {
  71802. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71803. if (gamepad.leftStick) {
  71804. gamepad.onleftstickchanged(function (stickValues) {
  71805. if (_this._teleportationEnabled) {
  71806. // Listening to classic/xbox gamepad only if no VR controller is active
  71807. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  71808. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  71809. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  71810. _this._checkTeleportWithRay(stickValues);
  71811. _this._checkTeleportBackwards(stickValues);
  71812. }
  71813. }
  71814. });
  71815. }
  71816. if (gamepad.rightStick) {
  71817. gamepad.onrightstickchanged(function (stickValues) {
  71818. if (_this._teleportationEnabled) {
  71819. _this._checkRotate(stickValues);
  71820. }
  71821. });
  71822. }
  71823. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  71824. gamepad.onbuttondown(function (buttonPressed) {
  71825. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  71826. _this._selectionPointerDown();
  71827. }
  71828. });
  71829. gamepad.onbuttonup(function (buttonPressed) {
  71830. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  71831. _this._selectionPointerUp();
  71832. }
  71833. });
  71834. }
  71835. }
  71836. else {
  71837. var webVRController = gamepad;
  71838. _this._tryEnableInteractionOnController(webVRController);
  71839. }
  71840. };
  71841. // 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
  71842. this._tryEnableInteractionOnController = function (webVRController) {
  71843. if (webVRController.hand === "left") {
  71844. _this._leftControllerReady = true;
  71845. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  71846. _this._enableInteractionOnController(webVRController);
  71847. }
  71848. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  71849. _this._enableTeleportationOnController(webVRController);
  71850. }
  71851. }
  71852. if (webVRController.hand === "right") {
  71853. _this._rightControllerReady = true;
  71854. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  71855. _this._enableInteractionOnController(webVRController);
  71856. }
  71857. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  71858. _this._enableTeleportationOnController(webVRController);
  71859. }
  71860. }
  71861. };
  71862. this._onNewGamepadDisconnected = function (gamepad) {
  71863. if (gamepad instanceof BABYLON.WebVRController) {
  71864. if (gamepad.hand === "left") {
  71865. _this._interactionsEnabledOnLeftController = false;
  71866. _this._teleportationEnabledOnLeftController = false;
  71867. _this._leftControllerReady = false;
  71868. if (_this._leftLaserPointer) {
  71869. _this._leftLaserPointer.dispose();
  71870. }
  71871. }
  71872. if (gamepad.hand === "right") {
  71873. _this._interactionsEnabledOnRightController = false;
  71874. _this._teleportationEnabledOnRightController = false;
  71875. _this._rightControllerReady = false;
  71876. if (_this._rightLaserPointer) {
  71877. _this._rightLaserPointer.dispose();
  71878. }
  71879. }
  71880. }
  71881. };
  71882. this._workingVector = BABYLON.Vector3.Zero();
  71883. this._workingQuaternion = BABYLON.Quaternion.Identity();
  71884. this._workingMatrix = BABYLON.Matrix.Identity();
  71885. this._scene = scene;
  71886. this._canvas = scene.getEngine().getRenderingCanvas();
  71887. // Parse options
  71888. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  71889. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  71890. }
  71891. if (webVROptions.createDeviceOrientationCamera === undefined) {
  71892. webVROptions.createDeviceOrientationCamera = true;
  71893. }
  71894. if (webVROptions.defaultHeight === undefined) {
  71895. webVROptions.defaultHeight = 1.7;
  71896. }
  71897. if (webVROptions.useCustomVRButton) {
  71898. this._useCustomVRButton = true;
  71899. if (webVROptions.customVRButton) {
  71900. this._btnVR = webVROptions.customVRButton;
  71901. }
  71902. }
  71903. if (webVROptions.rayLength) {
  71904. this._rayLength = webVROptions.rayLength;
  71905. }
  71906. this._defaultHeight = webVROptions.defaultHeight;
  71907. // Set position
  71908. if (this._scene.activeCamera) {
  71909. this._position = this._scene.activeCamera.position.clone();
  71910. }
  71911. else {
  71912. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  71913. }
  71914. // Set non-vr camera
  71915. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  71916. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  71917. // Copy data from existing camera
  71918. if (this._scene.activeCamera) {
  71919. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  71920. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  71921. // Set rotation from previous camera
  71922. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  71923. var targetCamera = this._scene.activeCamera;
  71924. if (targetCamera.rotationQuaternion) {
  71925. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  71926. }
  71927. else {
  71928. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  71929. }
  71930. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  71931. }
  71932. }
  71933. this._scene.activeCamera = this._deviceOrientationCamera;
  71934. if (this._canvas) {
  71935. this._scene.activeCamera.attachControl(this._canvas);
  71936. }
  71937. }
  71938. else {
  71939. this._existingCamera = this._scene.activeCamera;
  71940. }
  71941. // Create VR cameras
  71942. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  71943. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  71944. }
  71945. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  71946. this._webVRCamera.useStandingMatrix();
  71947. // Create default button
  71948. if (!this._useCustomVRButton) {
  71949. this._btnVR = document.createElement("BUTTON");
  71950. this._btnVR.className = "babylonVRicon";
  71951. this._btnVR.id = "babylonVRiconbtn";
  71952. this._btnVR.title = "Click to switch to VR";
  71953. 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) }";
  71954. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  71955. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  71956. // css += ".babylonVRicon.vrdisplaysupported { }";
  71957. // css += ".babylonVRicon.vrdisplayready { }";
  71958. // css += ".babylonVRicon.vrdisplayrequesting { }";
  71959. var style = document.createElement('style');
  71960. style.appendChild(document.createTextNode(css));
  71961. document.getElementsByTagName('head')[0].appendChild(style);
  71962. this.moveButtonToBottomRight();
  71963. }
  71964. // VR button click event
  71965. if (this._btnVR) {
  71966. this._btnVR.addEventListener("click", function () {
  71967. if (!_this.isInVRMode) {
  71968. _this.enterVR();
  71969. }
  71970. else {
  71971. _this.exitVR();
  71972. }
  71973. });
  71974. }
  71975. // Window events
  71976. window.addEventListener("resize", this._onResize);
  71977. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  71978. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  71979. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  71980. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  71981. // Display vr button when headset is connected
  71982. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  71983. this.displayVRButton();
  71984. }
  71985. else {
  71986. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  71987. if (e.vrDisplay) {
  71988. _this.displayVRButton();
  71989. }
  71990. });
  71991. }
  71992. // Exiting VR mode using 'ESC' key on desktop
  71993. this._onKeyDown = function (event) {
  71994. if (event.keyCode === 27 && _this.isInVRMode) {
  71995. _this.exitVR();
  71996. }
  71997. };
  71998. document.addEventListener("keydown", this._onKeyDown);
  71999. // Exiting VR mode double tapping the touch screen
  72000. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  72001. if (_this.isInVRMode) {
  72002. _this.exitVR();
  72003. if (_this._fullscreenVRpresenting) {
  72004. _this._scene.getEngine().switchFullscreen(true);
  72005. }
  72006. }
  72007. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  72008. // Listen for WebVR display changes
  72009. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  72010. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  72011. this._onVRRequestPresentStart = function () {
  72012. _this._webVRrequesting = true;
  72013. _this.updateButtonVisibility();
  72014. };
  72015. this._onVRRequestPresentComplete = function (success) {
  72016. _this._webVRrequesting = false;
  72017. _this.updateButtonVisibility();
  72018. };
  72019. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  72020. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  72021. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  72022. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72023. scene.onDisposeObservable.add(function () {
  72024. _this.dispose();
  72025. });
  72026. // Gamepad connection events
  72027. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  72028. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  72029. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  72030. this.updateButtonVisibility();
  72031. //create easing functions
  72032. this._circleEase = new BABYLON.CircleEase();
  72033. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72034. }
  72035. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  72036. get: function () {
  72037. return this._teleportationTarget;
  72038. },
  72039. set: function (value) {
  72040. if (value) {
  72041. value.name = "teleportationTarget";
  72042. this._isDefaultTeleportationTarget = false;
  72043. this._teleportationTarget = value;
  72044. }
  72045. },
  72046. enumerable: true,
  72047. configurable: true
  72048. });
  72049. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  72050. get: function () {
  72051. return this._displayGaze;
  72052. },
  72053. set: function (value) {
  72054. this._displayGaze = value;
  72055. if (!value) {
  72056. this._gazeTracker.isVisible = false;
  72057. }
  72058. },
  72059. enumerable: true,
  72060. configurable: true
  72061. });
  72062. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  72063. get: function () {
  72064. return this._displayLaserPointer;
  72065. },
  72066. set: function (value) {
  72067. this._displayLaserPointer = value;
  72068. if (!value) {
  72069. if (this._rightLaserPointer) {
  72070. this._rightLaserPointer.isVisible = false;
  72071. }
  72072. if (this._leftLaserPointer) {
  72073. this._leftLaserPointer.isVisible = false;
  72074. }
  72075. }
  72076. else {
  72077. if (this._rightLaserPointer) {
  72078. this._rightLaserPointer.isVisible = true;
  72079. }
  72080. else if (this._leftLaserPointer) {
  72081. this._leftLaserPointer.isVisible = true;
  72082. }
  72083. }
  72084. },
  72085. enumerable: true,
  72086. configurable: true
  72087. });
  72088. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  72089. get: function () {
  72090. return this._deviceOrientationCamera;
  72091. },
  72092. enumerable: true,
  72093. configurable: true
  72094. });
  72095. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  72096. // Based on the current WebVR support, returns the current VR camera used
  72097. get: function () {
  72098. if (this._webVRready) {
  72099. return this._webVRCamera;
  72100. }
  72101. else {
  72102. return this._scene.activeCamera;
  72103. }
  72104. },
  72105. enumerable: true,
  72106. configurable: true
  72107. });
  72108. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  72109. get: function () {
  72110. return this._webVRCamera;
  72111. },
  72112. enumerable: true,
  72113. configurable: true
  72114. });
  72115. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  72116. get: function () {
  72117. return this._vrDeviceOrientationCamera;
  72118. },
  72119. enumerable: true,
  72120. configurable: true
  72121. });
  72122. // Raised when one of the controller has loaded successfully its associated default mesh
  72123. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  72124. this._tryEnableInteractionOnController(webVRController);
  72125. try {
  72126. this.onControllerMeshLoaded.notifyObservers(webVRController);
  72127. }
  72128. catch (err) {
  72129. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  72130. }
  72131. };
  72132. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  72133. /**
  72134. * Gets a value indicating if we are currently in VR mode.
  72135. */
  72136. get: function () {
  72137. return this._webVRpresenting || this._fullscreenVRpresenting;
  72138. },
  72139. enumerable: true,
  72140. configurable: true
  72141. });
  72142. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  72143. var vrDisplay = this._scene.getEngine().getVRDevice();
  72144. if (vrDisplay) {
  72145. var wasPresenting = this._webVRpresenting;
  72146. // A VR display is connected
  72147. this._webVRpresenting = vrDisplay.isPresenting;
  72148. if (wasPresenting && !this._webVRpresenting)
  72149. this.exitVR();
  72150. }
  72151. else {
  72152. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  72153. }
  72154. this.updateButtonVisibility();
  72155. };
  72156. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  72157. this._webVRsupported = eventArgs.vrSupported;
  72158. this._webVRready = !!eventArgs.vrDisplay;
  72159. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  72160. this.updateButtonVisibility();
  72161. };
  72162. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  72163. if (this._canvas && !this._useCustomVRButton) {
  72164. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  72165. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  72166. }
  72167. };
  72168. VRExperienceHelper.prototype.displayVRButton = function () {
  72169. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  72170. document.body.appendChild(this._btnVR);
  72171. this._btnVRDisplayed = true;
  72172. }
  72173. };
  72174. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  72175. if (!this._btnVR || this._useCustomVRButton) {
  72176. return;
  72177. }
  72178. this._btnVR.className = "babylonVRicon";
  72179. if (this.isInVRMode) {
  72180. this._btnVR.className += " vrdisplaypresenting";
  72181. }
  72182. else {
  72183. if (this._webVRready)
  72184. this._btnVR.className += " vrdisplayready";
  72185. if (this._webVRsupported)
  72186. this._btnVR.className += " vrdisplaysupported";
  72187. if (this._webVRrequesting)
  72188. this._btnVR.className += " vrdisplayrequesting";
  72189. }
  72190. };
  72191. /**
  72192. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  72193. * Otherwise, will use the fullscreen API.
  72194. */
  72195. VRExperienceHelper.prototype.enterVR = function () {
  72196. if (this.onEnteringVR) {
  72197. try {
  72198. this.onEnteringVR.notifyObservers(this);
  72199. }
  72200. catch (err) {
  72201. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  72202. }
  72203. }
  72204. if (this._scene.activeCamera) {
  72205. this._position = this._scene.activeCamera.position.clone();
  72206. }
  72207. if (this._webVRrequesting)
  72208. return;
  72209. // If WebVR is supported and a headset is connected
  72210. if (this._webVRready) {
  72211. if (!this._webVRpresenting) {
  72212. this._webVRCamera.position = this._position;
  72213. this._scene.activeCamera = this._webVRCamera;
  72214. }
  72215. }
  72216. else if (this._vrDeviceOrientationCamera) {
  72217. this._vrDeviceOrientationCamera.position = this._position;
  72218. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  72219. this._scene.getEngine().switchFullscreen(true);
  72220. this.updateButtonVisibility();
  72221. }
  72222. if (this._scene.activeCamera && this._canvas) {
  72223. this._scene.activeCamera.attachControl(this._canvas);
  72224. }
  72225. };
  72226. /**
  72227. * Attempt to exit VR, or fullscreen.
  72228. */
  72229. VRExperienceHelper.prototype.exitVR = function () {
  72230. if (this.onExitingVR) {
  72231. try {
  72232. this.onExitingVR.notifyObservers(this);
  72233. }
  72234. catch (err) {
  72235. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  72236. }
  72237. }
  72238. if (this._webVRpresenting) {
  72239. this._scene.getEngine().disableVR();
  72240. }
  72241. if (this._scene.activeCamera) {
  72242. this._position = this._scene.activeCamera.position.clone();
  72243. }
  72244. if (this._deviceOrientationCamera) {
  72245. this._deviceOrientationCamera.position = this._position;
  72246. this._scene.activeCamera = this._deviceOrientationCamera;
  72247. if (this._canvas) {
  72248. this._scene.activeCamera.attachControl(this._canvas);
  72249. }
  72250. }
  72251. else if (this._existingCamera) {
  72252. this._existingCamera.position = this._position;
  72253. this._scene.activeCamera = this._existingCamera;
  72254. }
  72255. this.updateButtonVisibility();
  72256. };
  72257. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  72258. get: function () {
  72259. return this._position;
  72260. },
  72261. set: function (value) {
  72262. this._position = value;
  72263. if (this._scene.activeCamera) {
  72264. this._scene.activeCamera.position = value;
  72265. }
  72266. },
  72267. enumerable: true,
  72268. configurable: true
  72269. });
  72270. VRExperienceHelper.prototype.enableInteractions = function () {
  72271. var _this = this;
  72272. if (!this._interactionsEnabled) {
  72273. this._interactionsRequested = true;
  72274. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72275. this._enableInteractionOnController(this._webVRCamera.leftController);
  72276. }
  72277. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72278. this._enableInteractionOnController(this._webVRCamera.rightController);
  72279. }
  72280. this._createGazeTracker();
  72281. this.raySelectionPredicate = function (mesh) {
  72282. return true;
  72283. };
  72284. this.meshSelectionPredicate = function (mesh) {
  72285. return true;
  72286. };
  72287. this._raySelectionPredicate = function (mesh) {
  72288. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  72289. && mesh.name.indexOf("teleportationTarget") === -1
  72290. && mesh.name.indexOf("torusTeleportation") === -1
  72291. && mesh.name.indexOf("laserPointer") === -1)) {
  72292. return _this.raySelectionPredicate(mesh);
  72293. }
  72294. return false;
  72295. };
  72296. this._scene.registerBeforeRender(this.beforeRender);
  72297. this._interactionsEnabled = true;
  72298. }
  72299. };
  72300. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  72301. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  72302. if (this._floorMeshesCollection[i].id === mesh.id) {
  72303. return true;
  72304. }
  72305. }
  72306. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  72307. return true;
  72308. }
  72309. return false;
  72310. };
  72311. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  72312. if (!this._floorMeshesCollection) {
  72313. return;
  72314. }
  72315. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  72316. return;
  72317. }
  72318. this._floorMeshesCollection.push(floorMesh);
  72319. };
  72320. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  72321. if (!this._floorMeshesCollection) {
  72322. return;
  72323. }
  72324. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  72325. if (meshIndex !== -1) {
  72326. this._floorMeshesCollection.splice(meshIndex, 1);
  72327. }
  72328. };
  72329. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  72330. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  72331. if (!this._teleportationEnabled) {
  72332. this._teleportationRequested = true;
  72333. this.enableInteractions();
  72334. if (vrTeleportationOptions) {
  72335. if (vrTeleportationOptions.floorMeshName) {
  72336. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  72337. }
  72338. if (vrTeleportationOptions.floorMeshes) {
  72339. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  72340. }
  72341. }
  72342. if (this._leftControllerReady && this._webVRCamera.leftController) {
  72343. this._enableTeleportationOnController(this._webVRCamera.leftController);
  72344. }
  72345. if (this._rightControllerReady && this._webVRCamera.rightController) {
  72346. this._enableTeleportationOnController(this._webVRCamera.rightController);
  72347. }
  72348. // Creates an image processing post process for the vignette not relying
  72349. // on the main scene configuration for image processing to reduce setup and spaces
  72350. // (gamma/linear) conflicts.
  72351. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  72352. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  72353. imageProcessingConfiguration.vignetteEnabled = true;
  72354. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  72355. this._webVRCamera.detachPostProcess(this._postProcessMove);
  72356. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  72357. this._teleportationEnabled = true;
  72358. if (this._isDefaultTeleportationTarget) {
  72359. this._createTeleportationCircles();
  72360. }
  72361. }
  72362. };
  72363. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  72364. var _this = this;
  72365. var controllerMesh = webVRController.mesh;
  72366. if (controllerMesh) {
  72367. var makeNotPick = function (root) {
  72368. root.name += " laserPointer";
  72369. root.getChildMeshes().forEach(function (c) {
  72370. makeNotPick(c);
  72371. });
  72372. };
  72373. makeNotPick(controllerMesh);
  72374. var childMeshes = controllerMesh.getChildMeshes();
  72375. for (var i = 0; i < childMeshes.length; i++) {
  72376. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  72377. controllerMesh = childMeshes[i];
  72378. break;
  72379. }
  72380. }
  72381. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  72382. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  72383. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72384. laserPointerMaterial.alpha = 0.6;
  72385. laserPointer.material = laserPointerMaterial;
  72386. laserPointer.rotation.x = Math.PI / 2;
  72387. laserPointer.parent = controllerMesh;
  72388. laserPointer.position.z = -0.5;
  72389. laserPointer.isVisible = false;
  72390. if (webVRController.hand === "left") {
  72391. this._leftLaserPointer = laserPointer;
  72392. this._interactionsEnabledOnLeftController = true;
  72393. if (!this._rightLaserPointer) {
  72394. this._leftLaserPointer.isVisible = true;
  72395. }
  72396. }
  72397. else {
  72398. this._rightLaserPointer = laserPointer;
  72399. this._interactionsEnabledOnRightController = true;
  72400. if (!this._leftLaserPointer) {
  72401. this._rightLaserPointer.isVisible = true;
  72402. }
  72403. }
  72404. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  72405. // Enabling / disabling laserPointer
  72406. if (_this._displayLaserPointer && stateObject.value === 1) {
  72407. laserPointer.isVisible = !laserPointer.isVisible;
  72408. // Laser pointer can only be active on left or right, not both at the same time
  72409. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  72410. _this._rightLaserPointer.isVisible = false;
  72411. }
  72412. else if (_this._leftLaserPointer) {
  72413. _this._leftLaserPointer.isVisible = false;
  72414. }
  72415. }
  72416. });
  72417. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  72418. if (!_this._pointerDownOnMeshAsked) {
  72419. if (stateObject.value > _this._padSensibilityUp) {
  72420. _this._selectionPointerDown();
  72421. }
  72422. }
  72423. else if (stateObject.value < _this._padSensibilityDown) {
  72424. _this._selectionPointerUp();
  72425. }
  72426. });
  72427. }
  72428. };
  72429. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  72430. if (webVRController === void 0) { webVRController = null; }
  72431. if (!this._teleportationRequestInitiated) {
  72432. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  72433. if (webVRController) {
  72434. // If laser pointer wasn't enabled yet
  72435. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  72436. this._leftLaserPointer.isVisible = true;
  72437. if (this._rightLaserPointer) {
  72438. this._rightLaserPointer.isVisible = false;
  72439. }
  72440. }
  72441. else if (this._displayLaserPointer && this._rightLaserPointer) {
  72442. this._rightLaserPointer.isVisible = true;
  72443. if (this._leftLaserPointer) {
  72444. this._leftLaserPointer.isVisible = false;
  72445. }
  72446. }
  72447. }
  72448. this._teleportationRequestInitiated = true;
  72449. }
  72450. }
  72451. else {
  72452. // Listening to the proper controller values changes to confirm teleportation
  72453. if (webVRController == null
  72454. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  72455. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  72456. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  72457. if (this._teleportationAllowed) {
  72458. this._teleportationAllowed = false;
  72459. this._teleportCamera();
  72460. }
  72461. this._teleportationRequestInitiated = false;
  72462. }
  72463. }
  72464. }
  72465. };
  72466. VRExperienceHelper.prototype._selectionPointerDown = function () {
  72467. this._pointerDownOnMeshAsked = true;
  72468. if (this._currentMeshSelected && this._currentHit) {
  72469. this._scene.simulatePointerDown(this._currentHit);
  72470. }
  72471. };
  72472. VRExperienceHelper.prototype._selectionPointerUp = function () {
  72473. if (this._currentMeshSelected && this._currentHit) {
  72474. this._scene.simulatePointerUp(this._currentHit);
  72475. }
  72476. this._pointerDownOnMeshAsked = false;
  72477. };
  72478. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  72479. // Only rotate when user is not currently selecting a teleportation location
  72480. if (this._teleportationRequestInitiated) {
  72481. return;
  72482. }
  72483. if (!this._rotationLeftAsked) {
  72484. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  72485. this._rotationLeftAsked = true;
  72486. if (this._rotationAllowed) {
  72487. this._rotateCamera(false);
  72488. }
  72489. }
  72490. }
  72491. else {
  72492. if (stateObject.x > -this._padSensibilityDown) {
  72493. this._rotationLeftAsked = false;
  72494. }
  72495. }
  72496. if (!this._rotationRightAsked) {
  72497. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  72498. this._rotationRightAsked = true;
  72499. if (this._rotationAllowed) {
  72500. this._rotateCamera(true);
  72501. }
  72502. }
  72503. }
  72504. else {
  72505. if (stateObject.x < this._padSensibilityDown) {
  72506. this._rotationRightAsked = false;
  72507. }
  72508. }
  72509. };
  72510. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  72511. // Only teleport backwards when user is not currently selecting a teleportation location
  72512. if (this._teleportationRequestInitiated) {
  72513. return;
  72514. }
  72515. // Teleport backwards
  72516. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  72517. if (!this._teleportationBackRequestInitiated) {
  72518. if (!this.currentVRCamera) {
  72519. return;
  72520. }
  72521. // Get rotation and position of the current camera
  72522. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  72523. var position = this.currentVRCamera.position;
  72524. // If the camera has device position, use that instead
  72525. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  72526. rotation = this.currentVRCamera.deviceRotationQuaternion;
  72527. position = this.currentVRCamera.devicePosition;
  72528. }
  72529. // Get matrix with only the y rotation of the device rotation
  72530. rotation.toEulerAnglesToRef(this._workingVector);
  72531. this._workingVector.z = 0;
  72532. this._workingVector.x = 0;
  72533. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  72534. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  72535. // Rotate backwards ray by device rotation to cast at the ground behind the user
  72536. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  72537. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  72538. var ray = new BABYLON.Ray(position, this._workingVector);
  72539. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  72540. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  72541. this._teleportCamera(hit.pickedPoint);
  72542. }
  72543. this._teleportationBackRequestInitiated = true;
  72544. }
  72545. }
  72546. else {
  72547. this._teleportationBackRequestInitiated = false;
  72548. }
  72549. };
  72550. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  72551. var _this = this;
  72552. var controllerMesh = webVRController.mesh;
  72553. if (controllerMesh) {
  72554. if (webVRController.hand === "left") {
  72555. if (!this._interactionsEnabledOnLeftController) {
  72556. this._enableInteractionOnController(webVRController);
  72557. }
  72558. this._teleportationEnabledOnLeftController = true;
  72559. }
  72560. else {
  72561. if (!this._interactionsEnabledOnRightController) {
  72562. this._enableInteractionOnController(webVRController);
  72563. }
  72564. this._teleportationEnabledOnRightController = true;
  72565. }
  72566. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72567. this._dpadPressed = false;
  72568. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  72569. _this._dpadPressed = stateObject.pressed;
  72570. if (!_this._dpadPressed) {
  72571. _this._rotationLeftAsked = false;
  72572. _this._rotationRightAsked = false;
  72573. _this._teleportationBackRequestInitiated = false;
  72574. }
  72575. });
  72576. }
  72577. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  72578. _this._checkTeleportBackwards(stateObject);
  72579. _this._checkTeleportWithRay(stateObject, webVRController);
  72580. _this._checkRotate(stateObject);
  72581. });
  72582. }
  72583. };
  72584. // Gaze support used to point to teleport or to interact with an object
  72585. VRExperienceHelper.prototype._createGazeTracker = function () {
  72586. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  72587. this._gazeTracker.bakeCurrentTransformIntoVertices();
  72588. this._gazeTracker.isPickable = false;
  72589. this._gazeTracker.isVisible = false;
  72590. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  72591. targetMat.specularColor = BABYLON.Color3.Black();
  72592. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  72593. targetMat.backFaceCulling = false;
  72594. this._gazeTracker.material = targetMat;
  72595. };
  72596. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  72597. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  72598. this._teleportationTarget.isPickable = false;
  72599. var length = 512;
  72600. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  72601. dynamicTexture.hasAlpha = true;
  72602. var context = dynamicTexture.getContext();
  72603. var centerX = length / 2;
  72604. var centerY = length / 2;
  72605. var radius = 200;
  72606. context.beginPath();
  72607. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  72608. context.fillStyle = this._teleportationFillColor;
  72609. context.fill();
  72610. context.lineWidth = 10;
  72611. context.strokeStyle = this._teleportationBorderColor;
  72612. context.stroke();
  72613. context.closePath();
  72614. dynamicTexture.update();
  72615. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  72616. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  72617. this._teleportationTarget.material = teleportationCircleMaterial;
  72618. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  72619. torus.isPickable = false;
  72620. torus.parent = this._teleportationTarget;
  72621. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  72622. var keys = [];
  72623. keys.push({
  72624. frame: 0,
  72625. value: 0
  72626. });
  72627. keys.push({
  72628. frame: 30,
  72629. value: 0.4
  72630. });
  72631. keys.push({
  72632. frame: 60,
  72633. value: 0
  72634. });
  72635. animationInnerCircle.setKeys(keys);
  72636. var easingFunction = new BABYLON.SineEase();
  72637. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  72638. animationInnerCircle.setEasingFunction(easingFunction);
  72639. torus.animations = [];
  72640. torus.animations.push(animationInnerCircle);
  72641. this._scene.beginAnimation(torus, 0, 60, true);
  72642. this._hideTeleportationTarget();
  72643. };
  72644. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  72645. if (this._teleportationEnabled) {
  72646. this._teleportationTarget.isVisible = true;
  72647. if (this._isDefaultTeleportationTarget) {
  72648. this._teleportationTarget.getChildren()[0].isVisible = true;
  72649. }
  72650. }
  72651. };
  72652. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  72653. if (this._teleportationEnabled) {
  72654. this._teleportationTarget.isVisible = false;
  72655. if (this._isDefaultTeleportationTarget) {
  72656. this._teleportationTarget.getChildren()[0].isVisible = false;
  72657. }
  72658. }
  72659. };
  72660. VRExperienceHelper.prototype._rotateCamera = function (right) {
  72661. var _this = this;
  72662. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72663. return;
  72664. }
  72665. if (right) {
  72666. this._rotationAngle++;
  72667. }
  72668. else {
  72669. this._rotationAngle--;
  72670. }
  72671. this.currentVRCamera.animations = [];
  72672. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  72673. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72674. var animationRotationKeys = [];
  72675. animationRotationKeys.push({
  72676. frame: 0,
  72677. value: this.currentVRCamera.rotationQuaternion
  72678. });
  72679. animationRotationKeys.push({
  72680. frame: 6,
  72681. value: target
  72682. });
  72683. animationRotation.setKeys(animationRotationKeys);
  72684. animationRotation.setEasingFunction(this._circleEase);
  72685. this.currentVRCamera.animations.push(animationRotation);
  72686. this._postProcessMove.animations = [];
  72687. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72688. var vignetteWeightKeys = [];
  72689. vignetteWeightKeys.push({
  72690. frame: 0,
  72691. value: 0
  72692. });
  72693. vignetteWeightKeys.push({
  72694. frame: 3,
  72695. value: 4
  72696. });
  72697. vignetteWeightKeys.push({
  72698. frame: 6,
  72699. value: 0
  72700. });
  72701. animationPP.setKeys(vignetteWeightKeys);
  72702. animationPP.setEasingFunction(this._circleEase);
  72703. this._postProcessMove.animations.push(animationPP);
  72704. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72705. var vignetteStretchKeys = [];
  72706. vignetteStretchKeys.push({
  72707. frame: 0,
  72708. value: 0
  72709. });
  72710. vignetteStretchKeys.push({
  72711. frame: 3,
  72712. value: 10
  72713. });
  72714. vignetteStretchKeys.push({
  72715. frame: 6,
  72716. value: 0
  72717. });
  72718. animationPP2.setKeys(vignetteStretchKeys);
  72719. animationPP2.setEasingFunction(this._circleEase);
  72720. this._postProcessMove.animations.push(animationPP2);
  72721. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  72722. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  72723. this._webVRCamera.attachPostProcess(this._postProcessMove);
  72724. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  72725. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  72726. });
  72727. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  72728. };
  72729. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  72730. if (hit.pickedPoint) {
  72731. this._teleportationAllowed = true;
  72732. if (this._teleportationRequestInitiated) {
  72733. this._displayTeleportationTarget();
  72734. }
  72735. else {
  72736. this._hideTeleportationTarget();
  72737. }
  72738. this._haloCenter.copyFrom(hit.pickedPoint);
  72739. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  72740. var pickNormal = hit.getNormal(true, false);
  72741. if (pickNormal) {
  72742. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72743. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72744. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  72745. }
  72746. this._teleportationTarget.position.y += 0.1;
  72747. }
  72748. };
  72749. VRExperienceHelper.prototype._teleportCamera = function (location) {
  72750. var _this = this;
  72751. if (location === void 0) { location = null; }
  72752. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72753. return;
  72754. }
  72755. if (!location) {
  72756. location = this._haloCenter;
  72757. }
  72758. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  72759. // offset of the headset from the anchor.
  72760. if (this.webVRCamera.leftCamera) {
  72761. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  72762. this._workingVector.subtractInPlace(this.webVRCamera.position);
  72763. location.subtractToRef(this._workingVector, this._workingVector);
  72764. }
  72765. else {
  72766. this._workingVector.copyFrom(location);
  72767. }
  72768. // Add height to account for user's height offset
  72769. if (this.isInVRMode) {
  72770. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  72771. }
  72772. else {
  72773. this._workingVector.y += this._defaultHeight;
  72774. }
  72775. // Create animation from the camera's position to the new location
  72776. this.currentVRCamera.animations = [];
  72777. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72778. var animationCameraTeleportationKeys = [{
  72779. frame: 0,
  72780. value: this.currentVRCamera.position
  72781. },
  72782. {
  72783. frame: 11,
  72784. value: this._workingVector
  72785. }
  72786. ];
  72787. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  72788. animationCameraTeleportation.setEasingFunction(this._circleEase);
  72789. this.currentVRCamera.animations.push(animationCameraTeleportation);
  72790. this._postProcessMove.animations = [];
  72791. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72792. var vignetteWeightKeys = [];
  72793. vignetteWeightKeys.push({
  72794. frame: 0,
  72795. value: 0
  72796. });
  72797. vignetteWeightKeys.push({
  72798. frame: 5,
  72799. value: 8
  72800. });
  72801. vignetteWeightKeys.push({
  72802. frame: 11,
  72803. value: 0
  72804. });
  72805. animationPP.setKeys(vignetteWeightKeys);
  72806. this._postProcessMove.animations.push(animationPP);
  72807. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  72808. var vignetteStretchKeys = [];
  72809. vignetteStretchKeys.push({
  72810. frame: 0,
  72811. value: 0
  72812. });
  72813. vignetteStretchKeys.push({
  72814. frame: 5,
  72815. value: 10
  72816. });
  72817. vignetteStretchKeys.push({
  72818. frame: 11,
  72819. value: 0
  72820. });
  72821. animationPP2.setKeys(vignetteStretchKeys);
  72822. this._postProcessMove.animations.push(animationPP2);
  72823. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  72824. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  72825. this._webVRCamera.attachPostProcess(this._postProcessMove);
  72826. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  72827. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  72828. });
  72829. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  72830. };
  72831. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  72832. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  72833. return;
  72834. }
  72835. var ray;
  72836. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  72837. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  72838. }
  72839. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  72840. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  72841. }
  72842. else {
  72843. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  72844. }
  72845. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  72846. // Moving the gazeTracker on the mesh face targetted
  72847. if (hit && hit.pickedPoint) {
  72848. if (this._displayGaze) {
  72849. var multiplier = 1;
  72850. this._gazeTracker.isVisible = true;
  72851. if (this._isActionableMesh) {
  72852. multiplier = 3;
  72853. }
  72854. this._gazeTracker.scaling.x = hit.distance * multiplier;
  72855. this._gazeTracker.scaling.y = hit.distance * multiplier;
  72856. this._gazeTracker.scaling.z = hit.distance * multiplier;
  72857. var pickNormal = hit.getNormal();
  72858. // To avoid z-fighting
  72859. var deltaFighting = 0.002;
  72860. if (pickNormal) {
  72861. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  72862. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  72863. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  72864. }
  72865. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  72866. if (this._gazeTracker.position.x < 0) {
  72867. this._gazeTracker.position.x += deltaFighting;
  72868. }
  72869. else {
  72870. this._gazeTracker.position.x -= deltaFighting;
  72871. }
  72872. if (this._gazeTracker.position.y < 0) {
  72873. this._gazeTracker.position.y += deltaFighting;
  72874. }
  72875. else {
  72876. this._gazeTracker.position.y -= deltaFighting;
  72877. }
  72878. if (this._gazeTracker.position.z < 0) {
  72879. this._gazeTracker.position.z += deltaFighting;
  72880. }
  72881. else {
  72882. this._gazeTracker.position.z -= deltaFighting;
  72883. }
  72884. }
  72885. // Changing the size of the laser pointer based on the distance from the targetted point
  72886. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  72887. this._rightLaserPointer.scaling.y = hit.distance;
  72888. this._rightLaserPointer.position.z = -hit.distance / 2;
  72889. }
  72890. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  72891. this._leftLaserPointer.scaling.y = hit.distance;
  72892. this._leftLaserPointer.position.z = -hit.distance / 2;
  72893. }
  72894. }
  72895. else {
  72896. this._gazeTracker.isVisible = false;
  72897. }
  72898. if (hit && hit.pickedMesh) {
  72899. this._currentHit = hit;
  72900. if (this._pointerDownOnMeshAsked) {
  72901. this._scene.simulatePointerMove(this._currentHit);
  72902. }
  72903. // The object selected is the floor, we're in a teleportation scenario
  72904. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  72905. // Moving the teleportation area to this targetted point
  72906. this._moveTeleportationSelectorTo(hit);
  72907. return;
  72908. }
  72909. // If not, we're in a selection scenario
  72910. this._hideTeleportationTarget();
  72911. this._teleportationAllowed = false;
  72912. if (hit.pickedMesh !== this._currentMeshSelected) {
  72913. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  72914. this._currentMeshSelected = hit.pickedMesh;
  72915. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  72916. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  72917. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  72918. this._isActionableMesh = true;
  72919. }
  72920. else {
  72921. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72922. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72923. this._isActionableMesh = false;
  72924. }
  72925. try {
  72926. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  72927. }
  72928. catch (err) {
  72929. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  72930. }
  72931. }
  72932. else {
  72933. this._currentMeshSelected = null;
  72934. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72935. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72936. }
  72937. }
  72938. }
  72939. else {
  72940. this._currentHit = null;
  72941. this._currentMeshSelected = null;
  72942. this._teleportationAllowed = false;
  72943. this._hideTeleportationTarget();
  72944. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72945. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  72946. }
  72947. };
  72948. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  72949. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  72950. this._leftLaserPointer.material.emissiveColor = color;
  72951. }
  72952. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  72953. this._rightLaserPointer.material.emissiveColor = color;
  72954. }
  72955. };
  72956. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  72957. if (this._gazeTracker.material) {
  72958. this._gazeTracker.material.emissiveColor = color;
  72959. }
  72960. };
  72961. VRExperienceHelper.prototype.dispose = function () {
  72962. if (this.isInVRMode) {
  72963. this.exitVR();
  72964. }
  72965. if (this._passProcessMove) {
  72966. this._passProcessMove.dispose();
  72967. }
  72968. if (this._postProcessMove) {
  72969. this._postProcessMove.dispose();
  72970. }
  72971. if (this._webVRCamera) {
  72972. this._webVRCamera.dispose();
  72973. }
  72974. if (this._vrDeviceOrientationCamera) {
  72975. this._vrDeviceOrientationCamera.dispose();
  72976. }
  72977. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  72978. document.body.removeChild(this._btnVR);
  72979. }
  72980. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  72981. this._deviceOrientationCamera.dispose();
  72982. }
  72983. if (this._gazeTracker) {
  72984. this._gazeTracker.dispose();
  72985. }
  72986. if (this._teleportationTarget) {
  72987. this._teleportationTarget.dispose();
  72988. }
  72989. this._floorMeshesCollection = [];
  72990. document.removeEventListener("keydown", this._onKeyDown);
  72991. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72992. window.removeEventListener("resize", this._onResize);
  72993. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  72994. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  72995. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  72996. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  72997. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  72998. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  72999. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  73000. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73001. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  73002. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  73003. this._scene.unregisterBeforeRender(this.beforeRender);
  73004. };
  73005. VRExperienceHelper.prototype.getClassName = function () {
  73006. return "VRExperienceHelper";
  73007. };
  73008. return VRExperienceHelper;
  73009. }());
  73010. BABYLON.VRExperienceHelper = VRExperienceHelper;
  73011. })(BABYLON || (BABYLON = {}));
  73012. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  73013. // Mainly based on these 2 articles :
  73014. // 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
  73015. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  73016. var BABYLON;
  73017. (function (BABYLON) {
  73018. var JoystickAxis;
  73019. (function (JoystickAxis) {
  73020. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  73021. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  73022. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  73023. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  73024. var VirtualJoystick = /** @class */ (function () {
  73025. function VirtualJoystick(leftJoystick) {
  73026. var _this = this;
  73027. if (leftJoystick) {
  73028. this._leftJoystick = true;
  73029. }
  73030. else {
  73031. this._leftJoystick = false;
  73032. }
  73033. VirtualJoystick._globalJoystickIndex++;
  73034. // By default left & right arrow keys are moving the X
  73035. // and up & down keys are moving the Y
  73036. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73037. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73038. this.reverseLeftRight = false;
  73039. this.reverseUpDown = false;
  73040. // collections of pointers
  73041. this._touches = new BABYLON.StringDictionary();
  73042. this.deltaPosition = BABYLON.Vector3.Zero();
  73043. this._joystickSensibility = 25;
  73044. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73045. this._onResize = function (evt) {
  73046. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73047. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73048. if (VirtualJoystick.vjCanvas) {
  73049. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  73050. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  73051. }
  73052. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  73053. };
  73054. // injecting a canvas element on top of the canvas 3D game
  73055. if (!VirtualJoystick.vjCanvas) {
  73056. window.addEventListener("resize", this._onResize, false);
  73057. VirtualJoystick.vjCanvas = document.createElement("canvas");
  73058. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  73059. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  73060. VirtualJoystick.vjCanvas.width = window.innerWidth;
  73061. VirtualJoystick.vjCanvas.height = window.innerHeight;
  73062. VirtualJoystick.vjCanvas.style.width = "100%";
  73063. VirtualJoystick.vjCanvas.style.height = "100%";
  73064. VirtualJoystick.vjCanvas.style.position = "absolute";
  73065. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  73066. VirtualJoystick.vjCanvas.style.top = "0px";
  73067. VirtualJoystick.vjCanvas.style.left = "0px";
  73068. VirtualJoystick.vjCanvas.style.zIndex = "5";
  73069. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  73070. // Support for jQuery PEP polyfill
  73071. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  73072. var context = VirtualJoystick.vjCanvas.getContext('2d');
  73073. if (!context) {
  73074. throw new Error("Unable to create canvas for virtual joystick");
  73075. }
  73076. VirtualJoystick.vjCanvasContext = context;
  73077. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  73078. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73079. document.body.appendChild(VirtualJoystick.vjCanvas);
  73080. }
  73081. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  73082. this.pressed = false;
  73083. // default joystick color
  73084. this._joystickColor = "cyan";
  73085. this._joystickPointerID = -1;
  73086. // current joystick position
  73087. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  73088. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  73089. // origin joystick position
  73090. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  73091. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  73092. this._onPointerDownHandlerRef = function (evt) {
  73093. _this._onPointerDown(evt);
  73094. };
  73095. this._onPointerMoveHandlerRef = function (evt) {
  73096. _this._onPointerMove(evt);
  73097. };
  73098. this._onPointerUpHandlerRef = function (evt) {
  73099. _this._onPointerUp(evt);
  73100. };
  73101. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  73102. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  73103. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  73104. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  73105. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  73106. evt.preventDefault(); // Disables system menu
  73107. }, false);
  73108. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73109. }
  73110. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  73111. this._joystickSensibility = newJoystickSensibility;
  73112. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  73113. };
  73114. VirtualJoystick.prototype._onPointerDown = function (e) {
  73115. var positionOnScreenCondition;
  73116. e.preventDefault();
  73117. if (this._leftJoystick === true) {
  73118. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  73119. }
  73120. else {
  73121. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  73122. }
  73123. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  73124. // First contact will be dedicated to the virtual joystick
  73125. this._joystickPointerID = e.pointerId;
  73126. this._joystickPointerStartPos.x = e.clientX;
  73127. this._joystickPointerStartPos.y = e.clientY;
  73128. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  73129. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  73130. this._deltaJoystickVector.x = 0;
  73131. this._deltaJoystickVector.y = 0;
  73132. this.pressed = true;
  73133. this._touches.add(e.pointerId.toString(), e);
  73134. }
  73135. else {
  73136. // You can only trigger the action buttons with a joystick declared
  73137. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  73138. this._action();
  73139. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  73140. }
  73141. }
  73142. };
  73143. VirtualJoystick.prototype._onPointerMove = function (e) {
  73144. // If the current pointer is the one associated to the joystick (first touch contact)
  73145. if (this._joystickPointerID == e.pointerId) {
  73146. this._joystickPointerPos.x = e.clientX;
  73147. this._joystickPointerPos.y = e.clientY;
  73148. this._deltaJoystickVector = this._joystickPointerPos.clone();
  73149. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  73150. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  73151. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  73152. switch (this._axisTargetedByLeftAndRight) {
  73153. case JoystickAxis.X:
  73154. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  73155. break;
  73156. case JoystickAxis.Y:
  73157. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  73158. break;
  73159. case JoystickAxis.Z:
  73160. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  73161. break;
  73162. }
  73163. var directionUpDown = this.reverseUpDown ? 1 : -1;
  73164. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  73165. switch (this._axisTargetedByUpAndDown) {
  73166. case JoystickAxis.X:
  73167. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  73168. break;
  73169. case JoystickAxis.Y:
  73170. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  73171. break;
  73172. case JoystickAxis.Z:
  73173. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  73174. break;
  73175. }
  73176. }
  73177. else {
  73178. var data = this._touches.get(e.pointerId.toString());
  73179. if (data) {
  73180. data.x = e.clientX;
  73181. data.y = e.clientY;
  73182. }
  73183. }
  73184. };
  73185. VirtualJoystick.prototype._onPointerUp = function (e) {
  73186. if (this._joystickPointerID == e.pointerId) {
  73187. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  73188. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  73189. this._joystickPointerID = -1;
  73190. this.pressed = false;
  73191. }
  73192. else {
  73193. var touch = this._touches.get(e.pointerId.toString());
  73194. if (touch) {
  73195. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73196. }
  73197. }
  73198. this._deltaJoystickVector.x = 0;
  73199. this._deltaJoystickVector.y = 0;
  73200. this._touches.remove(e.pointerId.toString());
  73201. };
  73202. /**
  73203. * Change the color of the virtual joystick
  73204. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  73205. */
  73206. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  73207. this._joystickColor = newColor;
  73208. };
  73209. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  73210. this._action = action;
  73211. };
  73212. // Define which axis you'd like to control for left & right
  73213. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  73214. switch (axis) {
  73215. case JoystickAxis.X:
  73216. case JoystickAxis.Y:
  73217. case JoystickAxis.Z:
  73218. this._axisTargetedByLeftAndRight = axis;
  73219. break;
  73220. default:
  73221. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  73222. break;
  73223. }
  73224. };
  73225. // Define which axis you'd like to control for up & down
  73226. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  73227. switch (axis) {
  73228. case JoystickAxis.X:
  73229. case JoystickAxis.Y:
  73230. case JoystickAxis.Z:
  73231. this._axisTargetedByUpAndDown = axis;
  73232. break;
  73233. default:
  73234. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  73235. break;
  73236. }
  73237. };
  73238. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  73239. var _this = this;
  73240. if (this.pressed) {
  73241. this._touches.forEach(function (key, touch) {
  73242. if (touch.pointerId === _this._joystickPointerID) {
  73243. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  73244. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  73245. VirtualJoystick.vjCanvasContext.beginPath();
  73246. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73247. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73248. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  73249. VirtualJoystick.vjCanvasContext.stroke();
  73250. VirtualJoystick.vjCanvasContext.closePath();
  73251. VirtualJoystick.vjCanvasContext.beginPath();
  73252. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73253. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  73254. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  73255. VirtualJoystick.vjCanvasContext.stroke();
  73256. VirtualJoystick.vjCanvasContext.closePath();
  73257. VirtualJoystick.vjCanvasContext.beginPath();
  73258. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  73259. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  73260. VirtualJoystick.vjCanvasContext.stroke();
  73261. VirtualJoystick.vjCanvasContext.closePath();
  73262. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  73263. }
  73264. else {
  73265. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  73266. VirtualJoystick.vjCanvasContext.beginPath();
  73267. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  73268. VirtualJoystick.vjCanvasContext.beginPath();
  73269. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  73270. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  73271. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  73272. VirtualJoystick.vjCanvasContext.stroke();
  73273. VirtualJoystick.vjCanvasContext.closePath();
  73274. touch.prevX = touch.x;
  73275. touch.prevY = touch.y;
  73276. }
  73277. ;
  73278. });
  73279. }
  73280. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  73281. };
  73282. VirtualJoystick.prototype.releaseCanvas = function () {
  73283. if (VirtualJoystick.vjCanvas) {
  73284. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  73285. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  73286. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  73287. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  73288. window.removeEventListener("resize", this._onResize);
  73289. document.body.removeChild(VirtualJoystick.vjCanvas);
  73290. VirtualJoystick.vjCanvas = null;
  73291. }
  73292. };
  73293. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  73294. VirtualJoystick._globalJoystickIndex = 0;
  73295. return VirtualJoystick;
  73296. }());
  73297. BABYLON.VirtualJoystick = VirtualJoystick;
  73298. })(BABYLON || (BABYLON = {}));
  73299. //# sourceMappingURL=babylon.virtualJoystick.js.map
  73300. var BABYLON;
  73301. (function (BABYLON) {
  73302. // We're mainly based on the logic defined into the FreeCamera code
  73303. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  73304. __extends(VirtualJoysticksCamera, _super);
  73305. function VirtualJoysticksCamera(name, position, scene) {
  73306. var _this = _super.call(this, name, position, scene) || this;
  73307. _this.inputs.addVirtualJoystick();
  73308. return _this;
  73309. }
  73310. VirtualJoysticksCamera.prototype.getClassName = function () {
  73311. return "VirtualJoysticksCamera";
  73312. };
  73313. return VirtualJoysticksCamera;
  73314. }(BABYLON.FreeCamera));
  73315. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  73316. })(BABYLON || (BABYLON = {}));
  73317. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  73318. var BABYLON;
  73319. (function (BABYLON) {
  73320. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  73321. function FreeCameraVirtualJoystickInput() {
  73322. }
  73323. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  73324. return this._leftjoystick;
  73325. };
  73326. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  73327. return this._rightjoystick;
  73328. };
  73329. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  73330. if (this._leftjoystick) {
  73331. var camera = this.camera;
  73332. var speed = camera._computeLocalCameraSpeed() * 50;
  73333. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  73334. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  73335. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  73336. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  73337. if (!this._leftjoystick.pressed) {
  73338. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  73339. }
  73340. if (!this._rightjoystick.pressed) {
  73341. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  73342. }
  73343. }
  73344. };
  73345. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  73346. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  73347. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  73348. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  73349. this._leftjoystick.setJoystickSensibility(0.15);
  73350. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  73351. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  73352. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  73353. this._rightjoystick.reverseUpDown = true;
  73354. this._rightjoystick.setJoystickSensibility(0.05);
  73355. this._rightjoystick.setJoystickColor("yellow");
  73356. };
  73357. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  73358. this._leftjoystick.releaseCanvas();
  73359. this._rightjoystick.releaseCanvas();
  73360. };
  73361. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  73362. return "FreeCameraVirtualJoystickInput";
  73363. };
  73364. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  73365. return "virtualJoystick";
  73366. };
  73367. return FreeCameraVirtualJoystickInput;
  73368. }());
  73369. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  73370. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  73371. })(BABYLON || (BABYLON = {}));
  73372. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  73373. var BABYLON;
  73374. (function (BABYLON) {
  73375. var SimplificationSettings = /** @class */ (function () {
  73376. function SimplificationSettings(quality, distance, optimizeMesh) {
  73377. this.quality = quality;
  73378. this.distance = distance;
  73379. this.optimizeMesh = optimizeMesh;
  73380. }
  73381. return SimplificationSettings;
  73382. }());
  73383. BABYLON.SimplificationSettings = SimplificationSettings;
  73384. var SimplificationQueue = /** @class */ (function () {
  73385. function SimplificationQueue() {
  73386. this.running = false;
  73387. this._simplificationArray = [];
  73388. }
  73389. SimplificationQueue.prototype.addTask = function (task) {
  73390. this._simplificationArray.push(task);
  73391. };
  73392. SimplificationQueue.prototype.executeNext = function () {
  73393. var task = this._simplificationArray.pop();
  73394. if (task) {
  73395. this.running = true;
  73396. this.runSimplification(task);
  73397. }
  73398. else {
  73399. this.running = false;
  73400. }
  73401. };
  73402. SimplificationQueue.prototype.runSimplification = function (task) {
  73403. var _this = this;
  73404. if (task.parallelProcessing) {
  73405. //parallel simplifier
  73406. task.settings.forEach(function (setting) {
  73407. var simplifier = _this.getSimplifier(task);
  73408. simplifier.simplify(setting, function (newMesh) {
  73409. task.mesh.addLODLevel(setting.distance, newMesh);
  73410. newMesh.isVisible = true;
  73411. //check if it is the last
  73412. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  73413. //all done, run the success callback.
  73414. task.successCallback();
  73415. }
  73416. _this.executeNext();
  73417. });
  73418. });
  73419. }
  73420. else {
  73421. //single simplifier.
  73422. var simplifier = this.getSimplifier(task);
  73423. var runDecimation = function (setting, callback) {
  73424. simplifier.simplify(setting, function (newMesh) {
  73425. task.mesh.addLODLevel(setting.distance, newMesh);
  73426. newMesh.isVisible = true;
  73427. //run the next quality level
  73428. callback();
  73429. });
  73430. };
  73431. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  73432. runDecimation(task.settings[loop.index], function () {
  73433. loop.executeNext();
  73434. });
  73435. }, function () {
  73436. //execution ended, run the success callback.
  73437. if (task.successCallback) {
  73438. task.successCallback();
  73439. }
  73440. _this.executeNext();
  73441. });
  73442. }
  73443. };
  73444. SimplificationQueue.prototype.getSimplifier = function (task) {
  73445. switch (task.simplificationType) {
  73446. case SimplificationType.QUADRATIC:
  73447. default:
  73448. return new QuadraticErrorSimplification(task.mesh);
  73449. }
  73450. };
  73451. return SimplificationQueue;
  73452. }());
  73453. BABYLON.SimplificationQueue = SimplificationQueue;
  73454. /**
  73455. * The implemented types of simplification.
  73456. * At the moment only Quadratic Error Decimation is implemented.
  73457. */
  73458. var SimplificationType;
  73459. (function (SimplificationType) {
  73460. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  73461. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  73462. var DecimationTriangle = /** @class */ (function () {
  73463. function DecimationTriangle(vertices) {
  73464. this.vertices = vertices;
  73465. this.error = new Array(4);
  73466. this.deleted = false;
  73467. this.isDirty = false;
  73468. this.deletePending = false;
  73469. this.borderFactor = 0;
  73470. }
  73471. return DecimationTriangle;
  73472. }());
  73473. BABYLON.DecimationTriangle = DecimationTriangle;
  73474. var DecimationVertex = /** @class */ (function () {
  73475. function DecimationVertex(position, id) {
  73476. this.position = position;
  73477. this.id = id;
  73478. this.isBorder = true;
  73479. this.q = new QuadraticMatrix();
  73480. this.triangleCount = 0;
  73481. this.triangleStart = 0;
  73482. this.originalOffsets = [];
  73483. }
  73484. DecimationVertex.prototype.updatePosition = function (newPosition) {
  73485. this.position.copyFrom(newPosition);
  73486. };
  73487. return DecimationVertex;
  73488. }());
  73489. BABYLON.DecimationVertex = DecimationVertex;
  73490. var QuadraticMatrix = /** @class */ (function () {
  73491. function QuadraticMatrix(data) {
  73492. this.data = new Array(10);
  73493. for (var i = 0; i < 10; ++i) {
  73494. if (data && data[i]) {
  73495. this.data[i] = data[i];
  73496. }
  73497. else {
  73498. this.data[i] = 0;
  73499. }
  73500. }
  73501. }
  73502. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  73503. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  73504. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  73505. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  73506. return det;
  73507. };
  73508. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  73509. for (var i = 0; i < 10; ++i) {
  73510. this.data[i] += matrix.data[i];
  73511. }
  73512. };
  73513. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  73514. for (var i = 0; i < 10; ++i) {
  73515. this.data[i] += data[i];
  73516. }
  73517. };
  73518. QuadraticMatrix.prototype.add = function (matrix) {
  73519. var m = new QuadraticMatrix();
  73520. for (var i = 0; i < 10; ++i) {
  73521. m.data[i] = this.data[i] + matrix.data[i];
  73522. }
  73523. return m;
  73524. };
  73525. QuadraticMatrix.FromData = function (a, b, c, d) {
  73526. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  73527. };
  73528. //returning an array to avoid garbage collection
  73529. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  73530. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  73531. };
  73532. return QuadraticMatrix;
  73533. }());
  73534. BABYLON.QuadraticMatrix = QuadraticMatrix;
  73535. var Reference = /** @class */ (function () {
  73536. function Reference(vertexId, triangleId) {
  73537. this.vertexId = vertexId;
  73538. this.triangleId = triangleId;
  73539. }
  73540. return Reference;
  73541. }());
  73542. BABYLON.Reference = Reference;
  73543. /**
  73544. * An implementation of the Quadratic Error simplification algorithm.
  73545. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  73546. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  73547. * @author RaananW
  73548. */
  73549. var QuadraticErrorSimplification = /** @class */ (function () {
  73550. function QuadraticErrorSimplification(_mesh) {
  73551. this._mesh = _mesh;
  73552. this.syncIterations = 5000;
  73553. this.aggressiveness = 7;
  73554. this.decimationIterations = 100;
  73555. this.boundingBoxEpsilon = BABYLON.Epsilon;
  73556. }
  73557. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  73558. var _this = this;
  73559. this.initDecimatedMesh();
  73560. //iterating through the submeshes array, one after the other.
  73561. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  73562. _this.initWithMesh(loop.index, function () {
  73563. _this.runDecimation(settings, loop.index, function () {
  73564. loop.executeNext();
  73565. });
  73566. }, settings.optimizeMesh);
  73567. }, function () {
  73568. setTimeout(function () {
  73569. successCallback(_this._reconstructedMesh);
  73570. }, 0);
  73571. });
  73572. };
  73573. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  73574. var _this = this;
  73575. var targetCount = ~~(this.triangles.length * settings.quality);
  73576. var deletedTriangles = 0;
  73577. var triangleCount = this.triangles.length;
  73578. var iterationFunction = function (iteration, callback) {
  73579. setTimeout(function () {
  73580. if (iteration % 5 === 0) {
  73581. _this.updateMesh(iteration === 0);
  73582. }
  73583. for (var i = 0; i < _this.triangles.length; ++i) {
  73584. _this.triangles[i].isDirty = false;
  73585. }
  73586. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  73587. var trianglesIterator = function (i) {
  73588. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  73589. var t = _this.triangles[tIdx];
  73590. if (!t)
  73591. return;
  73592. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  73593. return;
  73594. }
  73595. for (var j = 0; j < 3; ++j) {
  73596. if (t.error[j] < threshold) {
  73597. var deleted0 = [];
  73598. var deleted1 = [];
  73599. var v0 = t.vertices[j];
  73600. var v1 = t.vertices[(j + 1) % 3];
  73601. if (v0.isBorder || v1.isBorder)
  73602. continue;
  73603. var p = BABYLON.Vector3.Zero();
  73604. var n = BABYLON.Vector3.Zero();
  73605. var uv = BABYLON.Vector2.Zero();
  73606. var color = new BABYLON.Color4(0, 0, 0, 1);
  73607. _this.calculateError(v0, v1, p, n, uv, color);
  73608. var delTr = new Array();
  73609. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  73610. continue;
  73611. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  73612. continue;
  73613. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  73614. continue;
  73615. var uniqueArray = new Array();
  73616. delTr.forEach(function (deletedT) {
  73617. if (uniqueArray.indexOf(deletedT) === -1) {
  73618. deletedT.deletePending = true;
  73619. uniqueArray.push(deletedT);
  73620. }
  73621. });
  73622. if (uniqueArray.length % 2 !== 0) {
  73623. continue;
  73624. }
  73625. v0.q = v1.q.add(v0.q);
  73626. v0.updatePosition(p);
  73627. var tStart = _this.references.length;
  73628. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  73629. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  73630. var tCount = _this.references.length - tStart;
  73631. if (tCount <= v0.triangleCount) {
  73632. if (tCount) {
  73633. for (var c = 0; c < tCount; c++) {
  73634. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  73635. }
  73636. }
  73637. }
  73638. else {
  73639. v0.triangleStart = tStart;
  73640. }
  73641. v0.triangleCount = tCount;
  73642. break;
  73643. }
  73644. }
  73645. };
  73646. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  73647. }, 0);
  73648. };
  73649. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  73650. if (triangleCount - deletedTriangles <= targetCount)
  73651. loop.breakLoop();
  73652. else {
  73653. iterationFunction(loop.index, function () {
  73654. loop.executeNext();
  73655. });
  73656. }
  73657. }, function () {
  73658. setTimeout(function () {
  73659. //reconstruct this part of the mesh
  73660. _this.reconstructMesh(submeshIndex);
  73661. successCallback();
  73662. }, 0);
  73663. });
  73664. };
  73665. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  73666. var _this = this;
  73667. this.vertices = [];
  73668. this.triangles = [];
  73669. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  73670. var indices = this._mesh.getIndices();
  73671. var submesh = this._mesh.subMeshes[submeshIndex];
  73672. var findInVertices = function (positionToSearch) {
  73673. if (optimizeMesh) {
  73674. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  73675. if (_this.vertices[ii].position.equals(positionToSearch)) {
  73676. return _this.vertices[ii];
  73677. }
  73678. }
  73679. }
  73680. return null;
  73681. };
  73682. var vertexReferences = [];
  73683. var vertexInit = function (i) {
  73684. if (!positionData) {
  73685. return;
  73686. }
  73687. var offset = i + submesh.verticesStart;
  73688. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  73689. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  73690. vertex.originalOffsets.push(offset);
  73691. if (vertex.id === _this.vertices.length) {
  73692. _this.vertices.push(vertex);
  73693. }
  73694. vertexReferences.push(vertex.id);
  73695. };
  73696. //var totalVertices = mesh.getTotalVertices();
  73697. var totalVertices = submesh.verticesCount;
  73698. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  73699. var indicesInit = function (i) {
  73700. if (!indices) {
  73701. return;
  73702. }
  73703. var offset = (submesh.indexStart / 3) + i;
  73704. var pos = (offset * 3);
  73705. var i0 = indices[pos + 0];
  73706. var i1 = indices[pos + 1];
  73707. var i2 = indices[pos + 2];
  73708. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  73709. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  73710. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  73711. var triangle = new DecimationTriangle([v0, v1, v2]);
  73712. triangle.originalOffset = pos;
  73713. _this.triangles.push(triangle);
  73714. };
  73715. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  73716. _this.init(callback);
  73717. });
  73718. });
  73719. };
  73720. QuadraticErrorSimplification.prototype.init = function (callback) {
  73721. var _this = this;
  73722. var triangleInit1 = function (i) {
  73723. var t = _this.triangles[i];
  73724. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  73725. for (var j = 0; j < 3; j++) {
  73726. 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))));
  73727. }
  73728. };
  73729. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  73730. var triangleInit2 = function (i) {
  73731. var t = _this.triangles[i];
  73732. for (var j = 0; j < 3; ++j) {
  73733. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  73734. }
  73735. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73736. };
  73737. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  73738. callback();
  73739. });
  73740. });
  73741. };
  73742. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  73743. var newTriangles = [];
  73744. var i;
  73745. for (i = 0; i < this.vertices.length; ++i) {
  73746. this.vertices[i].triangleCount = 0;
  73747. }
  73748. var t;
  73749. var j;
  73750. for (i = 0; i < this.triangles.length; ++i) {
  73751. if (!this.triangles[i].deleted) {
  73752. t = this.triangles[i];
  73753. for (j = 0; j < 3; ++j) {
  73754. t.vertices[j].triangleCount = 1;
  73755. }
  73756. newTriangles.push(t);
  73757. }
  73758. }
  73759. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  73760. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  73761. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  73762. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  73763. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  73764. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73765. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  73766. var vertexCount = 0;
  73767. for (i = 0; i < this.vertices.length; ++i) {
  73768. var vertex = this.vertices[i];
  73769. vertex.id = vertexCount;
  73770. if (vertex.triangleCount) {
  73771. vertex.originalOffsets.forEach(function (originalOffset) {
  73772. if (!normalData) {
  73773. return;
  73774. }
  73775. newPositionData.push(vertex.position.x);
  73776. newPositionData.push(vertex.position.y);
  73777. newPositionData.push(vertex.position.z);
  73778. newNormalData.push(normalData[originalOffset * 3]);
  73779. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  73780. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  73781. if (uvs && uvs.length) {
  73782. newUVsData.push(uvs[(originalOffset * 2)]);
  73783. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  73784. }
  73785. else if (colorsData && colorsData.length) {
  73786. newColorsData.push(colorsData[(originalOffset * 4)]);
  73787. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  73788. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  73789. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  73790. }
  73791. ++vertexCount;
  73792. });
  73793. }
  73794. }
  73795. var startingIndex = this._reconstructedMesh.getTotalIndices();
  73796. var startingVertex = this._reconstructedMesh.getTotalVertices();
  73797. var submeshesArray = this._reconstructedMesh.subMeshes;
  73798. this._reconstructedMesh.subMeshes = [];
  73799. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  73800. var originalIndices = this._mesh.getIndices();
  73801. for (i = 0; i < newTriangles.length; ++i) {
  73802. t = newTriangles[i]; //now get the new referencing point for each vertex
  73803. [0, 1, 2].forEach(function (idx) {
  73804. var id = originalIndices[t.originalOffset + idx];
  73805. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  73806. if (offset < 0)
  73807. offset = 0;
  73808. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  73809. });
  73810. }
  73811. //overwriting the old vertex buffers and indices.
  73812. this._reconstructedMesh.setIndices(newIndicesArray);
  73813. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  73814. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  73815. if (newUVsData.length > 0)
  73816. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  73817. if (newColorsData.length > 0)
  73818. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  73819. //create submesh
  73820. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  73821. if (submeshIndex > 0) {
  73822. this._reconstructedMesh.subMeshes = [];
  73823. submeshesArray.forEach(function (submesh) {
  73824. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  73825. });
  73826. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  73827. }
  73828. };
  73829. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  73830. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  73831. this._reconstructedMesh.material = this._mesh.material;
  73832. this._reconstructedMesh.parent = this._mesh.parent;
  73833. this._reconstructedMesh.isVisible = false;
  73834. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  73835. };
  73836. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  73837. for (var i = 0; i < vertex1.triangleCount; ++i) {
  73838. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  73839. if (t.deleted)
  73840. continue;
  73841. var s = this.references[vertex1.triangleStart + i].vertexId;
  73842. var v1 = t.vertices[(s + 1) % 3];
  73843. var v2 = t.vertices[(s + 2) % 3];
  73844. if ((v1 === vertex2 || v2 === vertex2)) {
  73845. deletedArray[i] = true;
  73846. delTr.push(t);
  73847. continue;
  73848. }
  73849. var d1 = v1.position.subtract(point);
  73850. d1 = d1.normalize();
  73851. var d2 = v2.position.subtract(point);
  73852. d2 = d2.normalize();
  73853. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  73854. return true;
  73855. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  73856. deletedArray[i] = false;
  73857. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  73858. return true;
  73859. }
  73860. return false;
  73861. };
  73862. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  73863. var newDeleted = deletedTriangles;
  73864. for (var i = 0; i < vertex.triangleCount; ++i) {
  73865. var ref = this.references[vertex.triangleStart + i];
  73866. var t = this.triangles[ref.triangleId];
  73867. if (t.deleted)
  73868. continue;
  73869. if (deletedArray[i] && t.deletePending) {
  73870. t.deleted = true;
  73871. newDeleted++;
  73872. continue;
  73873. }
  73874. t.vertices[ref.vertexId] = origVertex;
  73875. t.isDirty = true;
  73876. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  73877. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  73878. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  73879. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  73880. this.references.push(ref);
  73881. }
  73882. return newDeleted;
  73883. };
  73884. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  73885. for (var i = 0; i < this.vertices.length; ++i) {
  73886. var vCount = [];
  73887. var vId = [];
  73888. var v = this.vertices[i];
  73889. var j;
  73890. for (j = 0; j < v.triangleCount; ++j) {
  73891. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  73892. for (var ii = 0; ii < 3; ii++) {
  73893. var ofs = 0;
  73894. var vv = triangle.vertices[ii];
  73895. while (ofs < vCount.length) {
  73896. if (vId[ofs] === vv.id)
  73897. break;
  73898. ++ofs;
  73899. }
  73900. if (ofs === vCount.length) {
  73901. vCount.push(1);
  73902. vId.push(vv.id);
  73903. }
  73904. else {
  73905. vCount[ofs]++;
  73906. }
  73907. }
  73908. }
  73909. for (j = 0; j < vCount.length; ++j) {
  73910. if (vCount[j] === 1) {
  73911. this.vertices[vId[j]].isBorder = true;
  73912. }
  73913. else {
  73914. this.vertices[vId[j]].isBorder = false;
  73915. }
  73916. }
  73917. }
  73918. };
  73919. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  73920. if (identifyBorders === void 0) { identifyBorders = false; }
  73921. var i;
  73922. if (!identifyBorders) {
  73923. var newTrianglesVector = [];
  73924. for (i = 0; i < this.triangles.length; ++i) {
  73925. if (!this.triangles[i].deleted) {
  73926. newTrianglesVector.push(this.triangles[i]);
  73927. }
  73928. }
  73929. this.triangles = newTrianglesVector;
  73930. }
  73931. for (i = 0; i < this.vertices.length; ++i) {
  73932. this.vertices[i].triangleCount = 0;
  73933. this.vertices[i].triangleStart = 0;
  73934. }
  73935. var t;
  73936. var j;
  73937. var v;
  73938. for (i = 0; i < this.triangles.length; ++i) {
  73939. t = this.triangles[i];
  73940. for (j = 0; j < 3; ++j) {
  73941. v = t.vertices[j];
  73942. v.triangleCount++;
  73943. }
  73944. }
  73945. var tStart = 0;
  73946. for (i = 0; i < this.vertices.length; ++i) {
  73947. this.vertices[i].triangleStart = tStart;
  73948. tStart += this.vertices[i].triangleCount;
  73949. this.vertices[i].triangleCount = 0;
  73950. }
  73951. var newReferences = new Array(this.triangles.length * 3);
  73952. for (i = 0; i < this.triangles.length; ++i) {
  73953. t = this.triangles[i];
  73954. for (j = 0; j < 3; ++j) {
  73955. v = t.vertices[j];
  73956. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  73957. v.triangleCount++;
  73958. }
  73959. }
  73960. this.references = newReferences;
  73961. if (identifyBorders) {
  73962. this.identifyBorder();
  73963. }
  73964. };
  73965. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  73966. var x = point.x;
  73967. var y = point.y;
  73968. var z = point.z;
  73969. 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
  73970. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  73971. };
  73972. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  73973. var q = vertex1.q.add(vertex2.q);
  73974. var border = vertex1.isBorder && vertex2.isBorder;
  73975. var error = 0;
  73976. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  73977. if (qDet !== 0 && !border) {
  73978. if (!pointResult) {
  73979. pointResult = BABYLON.Vector3.Zero();
  73980. }
  73981. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  73982. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  73983. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  73984. error = this.vertexError(q, pointResult);
  73985. }
  73986. else {
  73987. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  73988. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  73989. var error1 = this.vertexError(q, vertex1.position);
  73990. var error2 = this.vertexError(q, vertex2.position);
  73991. var error3 = this.vertexError(q, p3);
  73992. error = Math.min(error1, error2, error3);
  73993. if (error === error1) {
  73994. if (pointResult) {
  73995. pointResult.copyFrom(vertex1.position);
  73996. }
  73997. }
  73998. else if (error === error2) {
  73999. if (pointResult) {
  74000. pointResult.copyFrom(vertex2.position);
  74001. }
  74002. }
  74003. else {
  74004. if (pointResult) {
  74005. pointResult.copyFrom(p3);
  74006. }
  74007. }
  74008. }
  74009. return error;
  74010. };
  74011. return QuadraticErrorSimplification;
  74012. }());
  74013. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  74014. })(BABYLON || (BABYLON = {}));
  74015. //# sourceMappingURL=babylon.meshSimplification.js.map
  74016. var BABYLON;
  74017. (function (BABYLON) {
  74018. var Internals;
  74019. (function (Internals) {
  74020. var MeshLODLevel = /** @class */ (function () {
  74021. function MeshLODLevel(distance, mesh) {
  74022. this.distance = distance;
  74023. this.mesh = mesh;
  74024. }
  74025. return MeshLODLevel;
  74026. }());
  74027. Internals.MeshLODLevel = MeshLODLevel;
  74028. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  74029. })(BABYLON || (BABYLON = {}));
  74030. //# sourceMappingURL=babylon.meshLODLevel.js.map
  74031. var BABYLON;
  74032. (function (BABYLON) {
  74033. // Standard optimizations
  74034. var SceneOptimization = /** @class */ (function () {
  74035. function SceneOptimization(priority) {
  74036. if (priority === void 0) { priority = 0; }
  74037. this.priority = priority;
  74038. this.apply = function (scene) {
  74039. return true; // Return true if everything that can be done was applied
  74040. };
  74041. }
  74042. return SceneOptimization;
  74043. }());
  74044. BABYLON.SceneOptimization = SceneOptimization;
  74045. var TextureOptimization = /** @class */ (function (_super) {
  74046. __extends(TextureOptimization, _super);
  74047. function TextureOptimization(priority, maximumSize) {
  74048. if (priority === void 0) { priority = 0; }
  74049. if (maximumSize === void 0) { maximumSize = 1024; }
  74050. var _this = _super.call(this, priority) || this;
  74051. _this.priority = priority;
  74052. _this.maximumSize = maximumSize;
  74053. _this.apply = function (scene) {
  74054. var allDone = true;
  74055. for (var index = 0; index < scene.textures.length; index++) {
  74056. var texture = scene.textures[index];
  74057. if (!texture.canRescale || texture.getContext) {
  74058. continue;
  74059. }
  74060. var currentSize = texture.getSize();
  74061. var maxDimension = Math.max(currentSize.width, currentSize.height);
  74062. if (maxDimension > _this.maximumSize) {
  74063. texture.scale(0.5);
  74064. allDone = false;
  74065. }
  74066. }
  74067. return allDone;
  74068. };
  74069. return _this;
  74070. }
  74071. return TextureOptimization;
  74072. }(SceneOptimization));
  74073. BABYLON.TextureOptimization = TextureOptimization;
  74074. var HardwareScalingOptimization = /** @class */ (function (_super) {
  74075. __extends(HardwareScalingOptimization, _super);
  74076. function HardwareScalingOptimization(priority, maximumScale) {
  74077. if (priority === void 0) { priority = 0; }
  74078. if (maximumScale === void 0) { maximumScale = 2; }
  74079. var _this = _super.call(this, priority) || this;
  74080. _this.priority = priority;
  74081. _this.maximumScale = maximumScale;
  74082. _this._currentScale = 1;
  74083. _this.apply = function (scene) {
  74084. _this._currentScale++;
  74085. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  74086. return _this._currentScale >= _this.maximumScale;
  74087. };
  74088. return _this;
  74089. }
  74090. return HardwareScalingOptimization;
  74091. }(SceneOptimization));
  74092. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  74093. var ShadowsOptimization = /** @class */ (function (_super) {
  74094. __extends(ShadowsOptimization, _super);
  74095. function ShadowsOptimization() {
  74096. var _this = _super !== null && _super.apply(this, arguments) || this;
  74097. _this.apply = function (scene) {
  74098. scene.shadowsEnabled = false;
  74099. return true;
  74100. };
  74101. return _this;
  74102. }
  74103. return ShadowsOptimization;
  74104. }(SceneOptimization));
  74105. BABYLON.ShadowsOptimization = ShadowsOptimization;
  74106. var PostProcessesOptimization = /** @class */ (function (_super) {
  74107. __extends(PostProcessesOptimization, _super);
  74108. function PostProcessesOptimization() {
  74109. var _this = _super !== null && _super.apply(this, arguments) || this;
  74110. _this.apply = function (scene) {
  74111. scene.postProcessesEnabled = false;
  74112. return true;
  74113. };
  74114. return _this;
  74115. }
  74116. return PostProcessesOptimization;
  74117. }(SceneOptimization));
  74118. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  74119. var LensFlaresOptimization = /** @class */ (function (_super) {
  74120. __extends(LensFlaresOptimization, _super);
  74121. function LensFlaresOptimization() {
  74122. var _this = _super !== null && _super.apply(this, arguments) || this;
  74123. _this.apply = function (scene) {
  74124. scene.lensFlaresEnabled = false;
  74125. return true;
  74126. };
  74127. return _this;
  74128. }
  74129. return LensFlaresOptimization;
  74130. }(SceneOptimization));
  74131. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  74132. var ParticlesOptimization = /** @class */ (function (_super) {
  74133. __extends(ParticlesOptimization, _super);
  74134. function ParticlesOptimization() {
  74135. var _this = _super !== null && _super.apply(this, arguments) || this;
  74136. _this.apply = function (scene) {
  74137. scene.particlesEnabled = false;
  74138. return true;
  74139. };
  74140. return _this;
  74141. }
  74142. return ParticlesOptimization;
  74143. }(SceneOptimization));
  74144. BABYLON.ParticlesOptimization = ParticlesOptimization;
  74145. var RenderTargetsOptimization = /** @class */ (function (_super) {
  74146. __extends(RenderTargetsOptimization, _super);
  74147. function RenderTargetsOptimization() {
  74148. var _this = _super !== null && _super.apply(this, arguments) || this;
  74149. _this.apply = function (scene) {
  74150. scene.renderTargetsEnabled = false;
  74151. return true;
  74152. };
  74153. return _this;
  74154. }
  74155. return RenderTargetsOptimization;
  74156. }(SceneOptimization));
  74157. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  74158. var MergeMeshesOptimization = /** @class */ (function (_super) {
  74159. __extends(MergeMeshesOptimization, _super);
  74160. function MergeMeshesOptimization() {
  74161. var _this = _super !== null && _super.apply(this, arguments) || this;
  74162. _this._canBeMerged = function (abstractMesh) {
  74163. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  74164. return false;
  74165. }
  74166. var mesh = abstractMesh;
  74167. if (!mesh.isVisible || !mesh.isEnabled()) {
  74168. return false;
  74169. }
  74170. if (mesh.instances.length > 0) {
  74171. return false;
  74172. }
  74173. if (mesh.skeleton || mesh.hasLODLevels) {
  74174. return false;
  74175. }
  74176. if (mesh.parent) {
  74177. return false;
  74178. }
  74179. return true;
  74180. };
  74181. _this.apply = function (scene, updateSelectionTree) {
  74182. var globalPool = scene.meshes.slice(0);
  74183. var globalLength = globalPool.length;
  74184. for (var index = 0; index < globalLength; index++) {
  74185. var currentPool = new Array();
  74186. var current = globalPool[index];
  74187. // Checks
  74188. if (!_this._canBeMerged(current)) {
  74189. continue;
  74190. }
  74191. currentPool.push(current);
  74192. // Find compatible meshes
  74193. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  74194. var otherMesh = globalPool[subIndex];
  74195. if (!_this._canBeMerged(otherMesh)) {
  74196. continue;
  74197. }
  74198. if (otherMesh.material !== current.material) {
  74199. continue;
  74200. }
  74201. if (otherMesh.checkCollisions !== current.checkCollisions) {
  74202. continue;
  74203. }
  74204. currentPool.push(otherMesh);
  74205. globalLength--;
  74206. globalPool.splice(subIndex, 1);
  74207. subIndex--;
  74208. }
  74209. if (currentPool.length < 2) {
  74210. continue;
  74211. }
  74212. // Merge meshes
  74213. BABYLON.Mesh.MergeMeshes(currentPool);
  74214. }
  74215. if (updateSelectionTree != undefined) {
  74216. if (updateSelectionTree) {
  74217. scene.createOrUpdateSelectionOctree();
  74218. }
  74219. }
  74220. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  74221. scene.createOrUpdateSelectionOctree();
  74222. }
  74223. return true;
  74224. };
  74225. return _this;
  74226. }
  74227. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  74228. get: function () {
  74229. return MergeMeshesOptimization._UpdateSelectionTree;
  74230. },
  74231. set: function (value) {
  74232. MergeMeshesOptimization._UpdateSelectionTree = value;
  74233. },
  74234. enumerable: true,
  74235. configurable: true
  74236. });
  74237. MergeMeshesOptimization._UpdateSelectionTree = false;
  74238. return MergeMeshesOptimization;
  74239. }(SceneOptimization));
  74240. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  74241. // Options
  74242. var SceneOptimizerOptions = /** @class */ (function () {
  74243. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  74244. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  74245. if (trackerDuration === void 0) { trackerDuration = 2000; }
  74246. this.targetFrameRate = targetFrameRate;
  74247. this.trackerDuration = trackerDuration;
  74248. this.optimizations = new Array();
  74249. }
  74250. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  74251. var result = new SceneOptimizerOptions(targetFrameRate);
  74252. var priority = 0;
  74253. result.optimizations.push(new MergeMeshesOptimization(priority));
  74254. result.optimizations.push(new ShadowsOptimization(priority));
  74255. result.optimizations.push(new LensFlaresOptimization(priority));
  74256. // Next priority
  74257. priority++;
  74258. result.optimizations.push(new PostProcessesOptimization(priority));
  74259. result.optimizations.push(new ParticlesOptimization(priority));
  74260. // Next priority
  74261. priority++;
  74262. result.optimizations.push(new TextureOptimization(priority, 1024));
  74263. return result;
  74264. };
  74265. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  74266. var result = new SceneOptimizerOptions(targetFrameRate);
  74267. var priority = 0;
  74268. result.optimizations.push(new MergeMeshesOptimization(priority));
  74269. result.optimizations.push(new ShadowsOptimization(priority));
  74270. result.optimizations.push(new LensFlaresOptimization(priority));
  74271. // Next priority
  74272. priority++;
  74273. result.optimizations.push(new PostProcessesOptimization(priority));
  74274. result.optimizations.push(new ParticlesOptimization(priority));
  74275. // Next priority
  74276. priority++;
  74277. result.optimizations.push(new TextureOptimization(priority, 512));
  74278. // Next priority
  74279. priority++;
  74280. result.optimizations.push(new RenderTargetsOptimization(priority));
  74281. // Next priority
  74282. priority++;
  74283. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  74284. return result;
  74285. };
  74286. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  74287. var result = new SceneOptimizerOptions(targetFrameRate);
  74288. var priority = 0;
  74289. result.optimizations.push(new MergeMeshesOptimization(priority));
  74290. result.optimizations.push(new ShadowsOptimization(priority));
  74291. result.optimizations.push(new LensFlaresOptimization(priority));
  74292. // Next priority
  74293. priority++;
  74294. result.optimizations.push(new PostProcessesOptimization(priority));
  74295. result.optimizations.push(new ParticlesOptimization(priority));
  74296. // Next priority
  74297. priority++;
  74298. result.optimizations.push(new TextureOptimization(priority, 256));
  74299. // Next priority
  74300. priority++;
  74301. result.optimizations.push(new RenderTargetsOptimization(priority));
  74302. // Next priority
  74303. priority++;
  74304. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  74305. return result;
  74306. };
  74307. return SceneOptimizerOptions;
  74308. }());
  74309. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  74310. // Scene optimizer tool
  74311. var SceneOptimizer = /** @class */ (function () {
  74312. function SceneOptimizer() {
  74313. }
  74314. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  74315. // TODO: add an epsilon
  74316. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  74317. if (onSuccess) {
  74318. onSuccess();
  74319. }
  74320. return;
  74321. }
  74322. // Apply current level of optimizations
  74323. var allDone = true;
  74324. var noOptimizationApplied = true;
  74325. for (var index = 0; index < options.optimizations.length; index++) {
  74326. var optimization = options.optimizations[index];
  74327. if (optimization.priority === currentPriorityLevel) {
  74328. noOptimizationApplied = false;
  74329. allDone = allDone && optimization.apply(scene);
  74330. }
  74331. }
  74332. // If no optimization was applied, this is a failure :(
  74333. if (noOptimizationApplied) {
  74334. if (onFailure) {
  74335. onFailure();
  74336. }
  74337. return;
  74338. }
  74339. // If all optimizations were done, move to next level
  74340. if (allDone) {
  74341. currentPriorityLevel++;
  74342. }
  74343. // Let's the system running for a specific amount of time before checking FPS
  74344. scene.executeWhenReady(function () {
  74345. setTimeout(function () {
  74346. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  74347. }, options.trackerDuration);
  74348. });
  74349. };
  74350. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  74351. if (!options) {
  74352. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  74353. }
  74354. // Let's the system running for a specific amount of time before checking FPS
  74355. scene.executeWhenReady(function () {
  74356. setTimeout(function () {
  74357. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  74358. }, options.trackerDuration);
  74359. });
  74360. };
  74361. return SceneOptimizer;
  74362. }());
  74363. BABYLON.SceneOptimizer = SceneOptimizer;
  74364. })(BABYLON || (BABYLON = {}));
  74365. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  74366. var BABYLON;
  74367. (function (BABYLON) {
  74368. var OutlineRenderer = /** @class */ (function () {
  74369. function OutlineRenderer(scene) {
  74370. this.zOffset = 1;
  74371. this._scene = scene;
  74372. }
  74373. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  74374. var _this = this;
  74375. if (useOverlay === void 0) { useOverlay = false; }
  74376. var scene = this._scene;
  74377. var engine = this._scene.getEngine();
  74378. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74379. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  74380. return;
  74381. }
  74382. var mesh = subMesh.getRenderingMesh();
  74383. var material = subMesh.getMaterial();
  74384. if (!material || !scene.activeCamera) {
  74385. return;
  74386. }
  74387. engine.enableEffect(this._effect);
  74388. // Logarithmic depth
  74389. if (material.useLogarithmicDepth) {
  74390. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  74391. }
  74392. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  74393. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  74394. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74395. // Bones
  74396. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74397. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74398. }
  74399. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74400. // Alpha test
  74401. if (material && material.needAlphaTesting()) {
  74402. var alphaTexture = material.getAlphaTestTexture();
  74403. if (alphaTexture) {
  74404. this._effect.setTexture("diffuseSampler", alphaTexture);
  74405. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74406. }
  74407. }
  74408. engine.setZOffset(-this.zOffset);
  74409. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  74410. engine.setZOffset(0);
  74411. };
  74412. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  74413. var defines = [];
  74414. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74415. var mesh = subMesh.getMesh();
  74416. var material = subMesh.getMaterial();
  74417. if (material) {
  74418. // Alpha test
  74419. if (material.needAlphaTesting()) {
  74420. defines.push("#define ALPHATEST");
  74421. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74422. attribs.push(BABYLON.VertexBuffer.UVKind);
  74423. defines.push("#define UV1");
  74424. }
  74425. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74426. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74427. defines.push("#define UV2");
  74428. }
  74429. }
  74430. //Logarithmic depth
  74431. if (material.useLogarithmicDepth) {
  74432. defines.push("#define LOGARITHMICDEPTH");
  74433. }
  74434. }
  74435. // Bones
  74436. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74437. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74438. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74439. if (mesh.numBoneInfluencers > 4) {
  74440. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74441. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74442. }
  74443. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74444. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74445. }
  74446. else {
  74447. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74448. }
  74449. // Instances
  74450. if (useInstances) {
  74451. defines.push("#define INSTANCES");
  74452. attribs.push("world0");
  74453. attribs.push("world1");
  74454. attribs.push("world2");
  74455. attribs.push("world3");
  74456. }
  74457. // Get correct effect
  74458. var join = defines.join("\n");
  74459. if (this._cachedDefines !== join) {
  74460. this._cachedDefines = join;
  74461. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  74462. }
  74463. return this._effect.isReady();
  74464. };
  74465. return OutlineRenderer;
  74466. }());
  74467. BABYLON.OutlineRenderer = OutlineRenderer;
  74468. })(BABYLON || (BABYLON = {}));
  74469. //# sourceMappingURL=babylon.outlineRenderer.js.map
  74470. var BABYLON;
  74471. (function (BABYLON) {
  74472. var FaceAdjacencies = /** @class */ (function () {
  74473. function FaceAdjacencies() {
  74474. this.edges = new Array();
  74475. this.edgesConnectedCount = 0;
  74476. }
  74477. return FaceAdjacencies;
  74478. }());
  74479. var EdgesRenderer = /** @class */ (function () {
  74480. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  74481. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  74482. if (epsilon === void 0) { epsilon = 0.95; }
  74483. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  74484. this.edgesWidthScalerForOrthographic = 1000.0;
  74485. this.edgesWidthScalerForPerspective = 50.0;
  74486. this._linesPositions = new Array();
  74487. this._linesNormals = new Array();
  74488. this._linesIndices = new Array();
  74489. this._buffers = {};
  74490. this._checkVerticesInsteadOfIndices = false;
  74491. this._source = source;
  74492. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  74493. this._epsilon = epsilon;
  74494. this._prepareRessources();
  74495. this._generateEdgesLines();
  74496. }
  74497. EdgesRenderer.prototype._prepareRessources = function () {
  74498. if (this._lineShader) {
  74499. return;
  74500. }
  74501. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  74502. attributes: ["position", "normal"],
  74503. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  74504. });
  74505. this._lineShader.disableDepthWrite = true;
  74506. this._lineShader.backFaceCulling = false;
  74507. };
  74508. EdgesRenderer.prototype._rebuild = function () {
  74509. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  74510. if (buffer) {
  74511. buffer._rebuild();
  74512. }
  74513. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  74514. if (buffer) {
  74515. buffer._rebuild();
  74516. }
  74517. var scene = this._source.getScene();
  74518. var engine = scene.getEngine();
  74519. this._ib = engine.createIndexBuffer(this._linesIndices);
  74520. };
  74521. EdgesRenderer.prototype.dispose = function () {
  74522. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  74523. if (buffer) {
  74524. buffer.dispose();
  74525. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  74526. }
  74527. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  74528. if (buffer) {
  74529. buffer.dispose();
  74530. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  74531. }
  74532. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  74533. this._lineShader.dispose();
  74534. };
  74535. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  74536. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  74537. return 0;
  74538. }
  74539. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  74540. return 1;
  74541. }
  74542. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  74543. return 2;
  74544. }
  74545. return -1;
  74546. };
  74547. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  74548. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  74549. return 0;
  74550. }
  74551. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  74552. return 1;
  74553. }
  74554. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  74555. return 2;
  74556. }
  74557. return -1;
  74558. };
  74559. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  74560. var needToCreateLine;
  74561. if (edge === undefined) {
  74562. needToCreateLine = true;
  74563. }
  74564. else {
  74565. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  74566. needToCreateLine = dotProduct < this._epsilon;
  74567. }
  74568. if (needToCreateLine) {
  74569. var offset = this._linesPositions.length / 3;
  74570. var normal = p0.subtract(p1);
  74571. normal.normalize();
  74572. // Positions
  74573. this._linesPositions.push(p0.x);
  74574. this._linesPositions.push(p0.y);
  74575. this._linesPositions.push(p0.z);
  74576. this._linesPositions.push(p0.x);
  74577. this._linesPositions.push(p0.y);
  74578. this._linesPositions.push(p0.z);
  74579. this._linesPositions.push(p1.x);
  74580. this._linesPositions.push(p1.y);
  74581. this._linesPositions.push(p1.z);
  74582. this._linesPositions.push(p1.x);
  74583. this._linesPositions.push(p1.y);
  74584. this._linesPositions.push(p1.z);
  74585. // Normals
  74586. this._linesNormals.push(p1.x);
  74587. this._linesNormals.push(p1.y);
  74588. this._linesNormals.push(p1.z);
  74589. this._linesNormals.push(-1);
  74590. this._linesNormals.push(p1.x);
  74591. this._linesNormals.push(p1.y);
  74592. this._linesNormals.push(p1.z);
  74593. this._linesNormals.push(1);
  74594. this._linesNormals.push(p0.x);
  74595. this._linesNormals.push(p0.y);
  74596. this._linesNormals.push(p0.z);
  74597. this._linesNormals.push(-1);
  74598. this._linesNormals.push(p0.x);
  74599. this._linesNormals.push(p0.y);
  74600. this._linesNormals.push(p0.z);
  74601. this._linesNormals.push(1);
  74602. // Indices
  74603. this._linesIndices.push(offset);
  74604. this._linesIndices.push(offset + 1);
  74605. this._linesIndices.push(offset + 2);
  74606. this._linesIndices.push(offset);
  74607. this._linesIndices.push(offset + 2);
  74608. this._linesIndices.push(offset + 3);
  74609. }
  74610. };
  74611. EdgesRenderer.prototype._generateEdgesLines = function () {
  74612. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74613. var indices = this._source.getIndices();
  74614. if (!indices || !positions) {
  74615. return;
  74616. }
  74617. // First let's find adjacencies
  74618. var adjacencies = new Array();
  74619. var faceNormals = new Array();
  74620. var index;
  74621. var faceAdjacencies;
  74622. // Prepare faces
  74623. for (index = 0; index < indices.length; index += 3) {
  74624. faceAdjacencies = new FaceAdjacencies();
  74625. var p0Index = indices[index];
  74626. var p1Index = indices[index + 1];
  74627. var p2Index = indices[index + 2];
  74628. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  74629. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  74630. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  74631. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  74632. faceNormal.normalize();
  74633. faceNormals.push(faceNormal);
  74634. adjacencies.push(faceAdjacencies);
  74635. }
  74636. // Scan
  74637. for (index = 0; index < adjacencies.length; index++) {
  74638. faceAdjacencies = adjacencies[index];
  74639. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  74640. var otherFaceAdjacencies = adjacencies[otherIndex];
  74641. if (faceAdjacencies.edgesConnectedCount === 3) {
  74642. break;
  74643. }
  74644. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  74645. continue;
  74646. }
  74647. var otherP0 = indices[otherIndex * 3];
  74648. var otherP1 = indices[otherIndex * 3 + 1];
  74649. var otherP2 = indices[otherIndex * 3 + 2];
  74650. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  74651. var otherEdgeIndex = 0;
  74652. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  74653. continue;
  74654. }
  74655. switch (edgeIndex) {
  74656. case 0:
  74657. if (this._checkVerticesInsteadOfIndices) {
  74658. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74659. }
  74660. else {
  74661. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  74662. }
  74663. break;
  74664. case 1:
  74665. if (this._checkVerticesInsteadOfIndices) {
  74666. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74667. }
  74668. else {
  74669. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  74670. }
  74671. break;
  74672. case 2:
  74673. if (this._checkVerticesInsteadOfIndices) {
  74674. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  74675. }
  74676. else {
  74677. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  74678. }
  74679. break;
  74680. }
  74681. if (otherEdgeIndex === -1) {
  74682. continue;
  74683. }
  74684. faceAdjacencies.edges[edgeIndex] = otherIndex;
  74685. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  74686. faceAdjacencies.edgesConnectedCount++;
  74687. otherFaceAdjacencies.edgesConnectedCount++;
  74688. if (faceAdjacencies.edgesConnectedCount === 3) {
  74689. break;
  74690. }
  74691. }
  74692. }
  74693. }
  74694. // Create lines
  74695. for (index = 0; index < adjacencies.length; index++) {
  74696. // 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
  74697. var current = adjacencies[index];
  74698. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  74699. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  74700. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  74701. }
  74702. // Merge into a single mesh
  74703. var engine = this._source.getScene().getEngine();
  74704. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  74705. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  74706. this._ib = engine.createIndexBuffer(this._linesIndices);
  74707. this._indicesCount = this._linesIndices.length;
  74708. };
  74709. EdgesRenderer.prototype.render = function () {
  74710. var scene = this._source.getScene();
  74711. if (!this._lineShader.isReady() || !scene.activeCamera) {
  74712. return;
  74713. }
  74714. var engine = scene.getEngine();
  74715. this._lineShader._preBind();
  74716. // VBOs
  74717. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  74718. scene.resetCachedMaterial();
  74719. this._lineShader.setColor4("color", this._source.edgesColor);
  74720. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  74721. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  74722. }
  74723. else {
  74724. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  74725. }
  74726. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  74727. this._lineShader.bind(this._source.getWorldMatrix());
  74728. // Draw order
  74729. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  74730. this._lineShader.unbind();
  74731. engine.setDepthWrite(true);
  74732. };
  74733. return EdgesRenderer;
  74734. }());
  74735. BABYLON.EdgesRenderer = EdgesRenderer;
  74736. })(BABYLON || (BABYLON = {}));
  74737. //# sourceMappingURL=babylon.edgesRenderer.js.map
  74738. var BABYLON;
  74739. (function (BABYLON) {
  74740. /**
  74741. * Special Glow Blur post process only blurring the alpha channel
  74742. * It enforces keeping the most luminous color in the color channel.
  74743. */
  74744. var GlowBlurPostProcess = /** @class */ (function (_super) {
  74745. __extends(GlowBlurPostProcess, _super);
  74746. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  74747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74748. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  74749. _this.direction = direction;
  74750. _this.kernel = kernel;
  74751. _this.onApplyObservable.add(function (effect) {
  74752. effect.setFloat2("screenSize", _this.width, _this.height);
  74753. effect.setVector2("direction", _this.direction);
  74754. effect.setFloat("blurWidth", _this.kernel);
  74755. });
  74756. return _this;
  74757. }
  74758. return GlowBlurPostProcess;
  74759. }(BABYLON.PostProcess));
  74760. /**
  74761. * The highlight layer Helps adding a glow effect around a mesh.
  74762. *
  74763. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  74764. * glowy meshes to your scene.
  74765. *
  74766. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  74767. */
  74768. var HighlightLayer = /** @class */ (function () {
  74769. /**
  74770. * Instantiates a new highlight Layer and references it to the scene..
  74771. * @param name The name of the layer
  74772. * @param scene The scene to use the layer in
  74773. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  74774. */
  74775. function HighlightLayer(name, scene, options) {
  74776. this.name = name;
  74777. this._vertexBuffers = {};
  74778. this._mainTextureDesiredSize = { width: 0, height: 0 };
  74779. this._meshes = {};
  74780. this._maxSize = 0;
  74781. this._shouldRender = false;
  74782. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  74783. this._excludedMeshes = {};
  74784. /**
  74785. * Specifies whether or not the inner glow is ACTIVE in the layer.
  74786. */
  74787. this.innerGlow = true;
  74788. /**
  74789. * Specifies whether or not the outer glow is ACTIVE in the layer.
  74790. */
  74791. this.outerGlow = true;
  74792. /**
  74793. * Specifies wether the highlight layer is enabled or not.
  74794. */
  74795. this.isEnabled = true;
  74796. /**
  74797. * An event triggered when the highlight layer has been disposed.
  74798. * @type {BABYLON.Observable}
  74799. */
  74800. this.onDisposeObservable = new BABYLON.Observable();
  74801. /**
  74802. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  74803. * @type {BABYLON.Observable}
  74804. */
  74805. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  74806. /**
  74807. * An event triggered when the highlight layer is being blurred.
  74808. * @type {BABYLON.Observable}
  74809. */
  74810. this.onBeforeBlurObservable = new BABYLON.Observable();
  74811. /**
  74812. * An event triggered when the highlight layer has been blurred.
  74813. * @type {BABYLON.Observable}
  74814. */
  74815. this.onAfterBlurObservable = new BABYLON.Observable();
  74816. /**
  74817. * An event triggered when the glowing blurred texture is being merged in the scene.
  74818. * @type {BABYLON.Observable}
  74819. */
  74820. this.onBeforeComposeObservable = new BABYLON.Observable();
  74821. /**
  74822. * An event triggered when the glowing blurred texture has been merged in the scene.
  74823. * @type {BABYLON.Observable}
  74824. */
  74825. this.onAfterComposeObservable = new BABYLON.Observable();
  74826. /**
  74827. * An event triggered when the highlight layer changes its size.
  74828. * @type {BABYLON.Observable}
  74829. */
  74830. this.onSizeChangedObservable = new BABYLON.Observable();
  74831. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74832. var engine = scene.getEngine();
  74833. this._engine = engine;
  74834. this._maxSize = this._engine.getCaps().maxTextureSize;
  74835. this._scene.highlightLayers.push(this);
  74836. // Warn on stencil.
  74837. if (!this._engine.isStencilEnable) {
  74838. 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 }");
  74839. }
  74840. // Adapt options
  74841. this._options = options || {
  74842. mainTextureRatio: 0.5,
  74843. blurTextureSizeRatio: 0.5,
  74844. blurHorizontalSize: 1.0,
  74845. blurVerticalSize: 1.0,
  74846. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  74847. camera: null
  74848. };
  74849. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  74850. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  74851. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  74852. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  74853. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  74854. // VBO
  74855. var vertices = [];
  74856. vertices.push(1, 1);
  74857. vertices.push(-1, 1);
  74858. vertices.push(-1, -1);
  74859. vertices.push(1, -1);
  74860. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74861. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74862. this._createIndexBuffer();
  74863. // Effect
  74864. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  74865. // Render target
  74866. this.setMainTextureSize();
  74867. // Create Textures and post processes
  74868. this.createTextureAndPostProcesses();
  74869. }
  74870. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  74871. /**
  74872. * Gets the horizontal size of the blur.
  74873. */
  74874. get: function () {
  74875. return this._horizontalBlurPostprocess.kernel;
  74876. },
  74877. /**
  74878. * Specifies the horizontal size of the blur.
  74879. */
  74880. set: function (value) {
  74881. this._horizontalBlurPostprocess.kernel = value;
  74882. },
  74883. enumerable: true,
  74884. configurable: true
  74885. });
  74886. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  74887. /**
  74888. * Gets the vertical size of the blur.
  74889. */
  74890. get: function () {
  74891. return this._verticalBlurPostprocess.kernel;
  74892. },
  74893. /**
  74894. * Specifies the vertical size of the blur.
  74895. */
  74896. set: function (value) {
  74897. this._verticalBlurPostprocess.kernel = value;
  74898. },
  74899. enumerable: true,
  74900. configurable: true
  74901. });
  74902. Object.defineProperty(HighlightLayer.prototype, "camera", {
  74903. /**
  74904. * Gets the camera attached to the layer.
  74905. */
  74906. get: function () {
  74907. return this._options.camera;
  74908. },
  74909. enumerable: true,
  74910. configurable: true
  74911. });
  74912. HighlightLayer.prototype._createIndexBuffer = function () {
  74913. var engine = this._scene.getEngine();
  74914. // Indices
  74915. var indices = [];
  74916. indices.push(0);
  74917. indices.push(1);
  74918. indices.push(2);
  74919. indices.push(0);
  74920. indices.push(2);
  74921. indices.push(3);
  74922. this._indexBuffer = engine.createIndexBuffer(indices);
  74923. };
  74924. HighlightLayer.prototype._rebuild = function () {
  74925. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74926. if (vb) {
  74927. vb._rebuild();
  74928. }
  74929. this._createIndexBuffer();
  74930. };
  74931. /**
  74932. * Creates the render target textures and post processes used in the highlight layer.
  74933. */
  74934. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  74935. var _this = this;
  74936. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  74937. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  74938. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  74939. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  74940. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  74941. width: this._mainTextureDesiredSize.width,
  74942. height: this._mainTextureDesiredSize.height
  74943. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74944. this._mainTexture.activeCamera = this._options.camera;
  74945. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74946. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74947. this._mainTexture.anisotropicFilteringLevel = 1;
  74948. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74949. this._mainTexture.renderParticles = false;
  74950. this._mainTexture.renderList = null;
  74951. this._mainTexture.ignoreCameraViewport = true;
  74952. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  74953. width: blurTextureWidth,
  74954. height: blurTextureHeight
  74955. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74956. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74957. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74958. this._blurTexture.anisotropicFilteringLevel = 16;
  74959. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74960. this._blurTexture.renderParticles = false;
  74961. this._blurTexture.ignoreCameraViewport = true;
  74962. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74963. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  74964. effect.setTexture("textureSampler", _this._mainTexture);
  74965. });
  74966. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  74967. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74968. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74969. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74970. });
  74971. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74972. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74973. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74974. });
  74975. }
  74976. else {
  74977. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74978. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  74979. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74980. });
  74981. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  74982. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  74983. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  74984. });
  74985. }
  74986. this._mainTexture.onAfterUnbindObservable.add(function () {
  74987. _this.onBeforeBlurObservable.notifyObservers(_this);
  74988. var internalTexture = _this._blurTexture.getInternalTexture();
  74989. if (internalTexture) {
  74990. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  74991. }
  74992. _this.onAfterBlurObservable.notifyObservers(_this);
  74993. });
  74994. // Custom render function
  74995. var renderSubMesh = function (subMesh) {
  74996. if (!_this._meshes) {
  74997. return;
  74998. }
  74999. var material = subMesh.getMaterial();
  75000. var mesh = subMesh.getRenderingMesh();
  75001. var scene = _this._scene;
  75002. var engine = scene.getEngine();
  75003. if (!material) {
  75004. return;
  75005. }
  75006. // Do not block in blend mode.
  75007. if (material.needAlphaBlendingForMesh(mesh)) {
  75008. return;
  75009. }
  75010. // Culling
  75011. engine.setState(material.backFaceCulling);
  75012. // Managing instances
  75013. var batch = mesh._getInstancesRenderList(subMesh._id);
  75014. if (batch.mustReturn) {
  75015. return;
  75016. }
  75017. // Excluded Mesh
  75018. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75019. return;
  75020. }
  75021. ;
  75022. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75023. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  75024. var emissiveTexture = null;
  75025. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  75026. emissiveTexture = material.emissiveTexture;
  75027. }
  75028. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  75029. engine.enableEffect(_this._glowMapGenerationEffect);
  75030. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  75031. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  75032. if (highlightLayerMesh) {
  75033. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  75034. }
  75035. else {
  75036. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  75037. }
  75038. // Alpha test
  75039. if (material && material.needAlphaTesting()) {
  75040. var alphaTexture = material.getAlphaTestTexture();
  75041. if (alphaTexture) {
  75042. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  75043. var textureMatrix = alphaTexture.getTextureMatrix();
  75044. if (textureMatrix) {
  75045. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  75046. }
  75047. }
  75048. }
  75049. // Glow emissive only
  75050. if (emissiveTexture) {
  75051. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  75052. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  75053. }
  75054. // Bones
  75055. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75056. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75057. }
  75058. // Draw
  75059. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  75060. }
  75061. else {
  75062. // Need to reset refresh rate of the shadowMap
  75063. _this._mainTexture.resetRefreshCounter();
  75064. }
  75065. };
  75066. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75067. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  75068. var index;
  75069. var engine = _this._scene.getEngine();
  75070. if (depthOnlySubMeshes.length) {
  75071. engine.setColorWrite(false);
  75072. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75073. renderSubMesh(depthOnlySubMeshes.data[index]);
  75074. }
  75075. engine.setColorWrite(true);
  75076. }
  75077. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75078. renderSubMesh(opaqueSubMeshes.data[index]);
  75079. }
  75080. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75081. renderSubMesh(alphaTestSubMeshes.data[index]);
  75082. }
  75083. for (index = 0; index < transparentSubMeshes.length; index++) {
  75084. renderSubMesh(transparentSubMeshes.data[index]);
  75085. }
  75086. };
  75087. this._mainTexture.onClearObservable.add(function (engine) {
  75088. engine.clear(HighlightLayer.neutralColor, true, true, true);
  75089. });
  75090. };
  75091. /**
  75092. * Checks for the readiness of the element composing the layer.
  75093. * @param subMesh the mesh to check for
  75094. * @param useInstances specify wether or not to use instances to render the mesh
  75095. * @param emissiveTexture the associated emissive texture used to generate the glow
  75096. * @return true if ready otherwise, false
  75097. */
  75098. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  75099. var material = subMesh.getMaterial();
  75100. if (!material) {
  75101. return false;
  75102. }
  75103. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  75104. return false;
  75105. }
  75106. var defines = [];
  75107. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75108. var mesh = subMesh.getMesh();
  75109. var uv1 = false;
  75110. var uv2 = false;
  75111. // Alpha test
  75112. if (material && material.needAlphaTesting()) {
  75113. var alphaTexture = material.getAlphaTestTexture();
  75114. if (alphaTexture) {
  75115. defines.push("#define ALPHATEST");
  75116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75117. alphaTexture.coordinatesIndex === 1) {
  75118. defines.push("#define DIFFUSEUV2");
  75119. uv2 = true;
  75120. }
  75121. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75122. defines.push("#define DIFFUSEUV1");
  75123. uv1 = true;
  75124. }
  75125. }
  75126. }
  75127. // Emissive
  75128. if (emissiveTexture) {
  75129. defines.push("#define EMISSIVE");
  75130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  75131. emissiveTexture.coordinatesIndex === 1) {
  75132. defines.push("#define EMISSIVEUV2");
  75133. uv2 = true;
  75134. }
  75135. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75136. defines.push("#define EMISSIVEUV1");
  75137. uv1 = true;
  75138. }
  75139. }
  75140. if (uv1) {
  75141. attribs.push(BABYLON.VertexBuffer.UVKind);
  75142. defines.push("#define UV1");
  75143. }
  75144. if (uv2) {
  75145. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75146. defines.push("#define UV2");
  75147. }
  75148. // Bones
  75149. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75152. if (mesh.numBoneInfluencers > 4) {
  75153. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75154. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75155. }
  75156. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75157. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75158. }
  75159. else {
  75160. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75161. }
  75162. // Instances
  75163. if (useInstances) {
  75164. defines.push("#define INSTANCES");
  75165. attribs.push("world0");
  75166. attribs.push("world1");
  75167. attribs.push("world2");
  75168. attribs.push("world3");
  75169. }
  75170. // Get correct effect
  75171. var join = defines.join("\n");
  75172. if (this._cachedDefines !== join) {
  75173. this._cachedDefines = join;
  75174. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  75175. }
  75176. return this._glowMapGenerationEffect.isReady();
  75177. };
  75178. /**
  75179. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  75180. */
  75181. HighlightLayer.prototype.render = function () {
  75182. var currentEffect = this._glowMapMergeEffect;
  75183. // Check
  75184. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  75185. return;
  75186. var engine = this._scene.getEngine();
  75187. this.onBeforeComposeObservable.notifyObservers(this);
  75188. // Render
  75189. engine.enableEffect(currentEffect);
  75190. engine.setState(false);
  75191. // Cache
  75192. var previousStencilBuffer = engine.getStencilBuffer();
  75193. var previousStencilFunction = engine.getStencilFunction();
  75194. var previousStencilMask = engine.getStencilMask();
  75195. var previousStencilOperationPass = engine.getStencilOperationPass();
  75196. var previousStencilOperationFail = engine.getStencilOperationFail();
  75197. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  75198. var previousAlphaMode = engine.getAlphaMode();
  75199. // Texture
  75200. currentEffect.setTexture("textureSampler", this._blurTexture);
  75201. // VBOs
  75202. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  75203. // Stencil operations
  75204. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  75205. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  75206. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  75207. // Draw order
  75208. engine.setAlphaMode(this._options.alphaBlendingMode);
  75209. engine.setStencilMask(0x00);
  75210. engine.setStencilBuffer(true);
  75211. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  75212. if (this.outerGlow) {
  75213. currentEffect.setFloat("offset", 0);
  75214. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  75215. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75216. }
  75217. if (this.innerGlow) {
  75218. currentEffect.setFloat("offset", 1);
  75219. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  75220. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75221. }
  75222. // Restore Cache
  75223. engine.setStencilFunction(previousStencilFunction);
  75224. engine.setStencilMask(previousStencilMask);
  75225. engine.setAlphaMode(previousAlphaMode);
  75226. engine.setStencilBuffer(previousStencilBuffer);
  75227. engine.setStencilOperationPass(previousStencilOperationPass);
  75228. engine.setStencilOperationFail(previousStencilOperationFail);
  75229. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  75230. engine._stencilState.reset();
  75231. this.onAfterComposeObservable.notifyObservers(this);
  75232. // Handle size changes.
  75233. var size = this._mainTexture.getSize();
  75234. this.setMainTextureSize();
  75235. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  75236. // Recreate RTT and post processes on size change.
  75237. this.onSizeChangedObservable.notifyObservers(this);
  75238. this.disposeTextureAndPostProcesses();
  75239. this.createTextureAndPostProcesses();
  75240. }
  75241. };
  75242. /**
  75243. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  75244. * @param mesh The mesh to exclude from the highlight layer
  75245. */
  75246. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  75247. if (!this._excludedMeshes) {
  75248. return;
  75249. }
  75250. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75251. if (!meshExcluded) {
  75252. this._excludedMeshes[mesh.uniqueId] = {
  75253. mesh: mesh,
  75254. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  75255. mesh.getEngine().setStencilBuffer(false);
  75256. }),
  75257. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  75258. mesh.getEngine().setStencilBuffer(true);
  75259. }),
  75260. };
  75261. }
  75262. };
  75263. /**
  75264. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  75265. * @param mesh The mesh to highlight
  75266. */
  75267. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  75268. if (!this._excludedMeshes) {
  75269. return;
  75270. }
  75271. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  75272. if (meshExcluded) {
  75273. if (meshExcluded.beforeRender) {
  75274. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  75275. }
  75276. if (meshExcluded.afterRender) {
  75277. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  75278. }
  75279. }
  75280. this._excludedMeshes[mesh.uniqueId] = null;
  75281. };
  75282. /**
  75283. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  75284. * @param mesh The mesh to highlight
  75285. * @param color The color of the highlight
  75286. * @param glowEmissiveOnly Extract the glow from the emissive texture
  75287. */
  75288. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  75289. var _this = this;
  75290. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  75291. if (!this._meshes) {
  75292. return;
  75293. }
  75294. var meshHighlight = this._meshes[mesh.uniqueId];
  75295. if (meshHighlight) {
  75296. meshHighlight.color = color;
  75297. }
  75298. else {
  75299. this._meshes[mesh.uniqueId] = {
  75300. mesh: mesh,
  75301. color: color,
  75302. // Lambda required for capture due to Observable this context
  75303. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  75304. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  75305. _this.defaultStencilReference(mesh);
  75306. }
  75307. else {
  75308. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  75309. }
  75310. }),
  75311. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  75312. glowEmissiveOnly: glowEmissiveOnly
  75313. };
  75314. }
  75315. this._shouldRender = true;
  75316. };
  75317. /**
  75318. * Remove a mesh from the highlight layer in order to make it stop glowing.
  75319. * @param mesh The mesh to highlight
  75320. */
  75321. HighlightLayer.prototype.removeMesh = function (mesh) {
  75322. if (!this._meshes) {
  75323. return;
  75324. }
  75325. var meshHighlight = this._meshes[mesh.uniqueId];
  75326. if (meshHighlight) {
  75327. if (meshHighlight.observerHighlight) {
  75328. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75329. }
  75330. if (meshHighlight.observerDefault) {
  75331. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75332. }
  75333. delete this._meshes[mesh.uniqueId];
  75334. }
  75335. this._shouldRender = false;
  75336. for (var meshHighlightToCheck in this._meshes) {
  75337. if (this._meshes[meshHighlightToCheck]) {
  75338. this._shouldRender = true;
  75339. break;
  75340. }
  75341. }
  75342. };
  75343. /**
  75344. * Returns true if the layer contains information to display, otherwise false.
  75345. */
  75346. HighlightLayer.prototype.shouldRender = function () {
  75347. return this.isEnabled && this._shouldRender;
  75348. };
  75349. /**
  75350. * Sets the main texture desired size which is the closest power of two
  75351. * of the engine canvas size.
  75352. */
  75353. HighlightLayer.prototype.setMainTextureSize = function () {
  75354. if (this._options.mainTextureFixedSize) {
  75355. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  75356. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  75357. }
  75358. else {
  75359. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  75360. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  75361. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  75362. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  75363. }
  75364. };
  75365. /**
  75366. * Force the stencil to the normal expected value for none glowing parts
  75367. */
  75368. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  75369. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  75370. };
  75371. /**
  75372. * Dispose only the render target textures and post process.
  75373. */
  75374. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  75375. this._blurTexture.dispose();
  75376. this._mainTexture.dispose();
  75377. this._downSamplePostprocess.dispose();
  75378. this._horizontalBlurPostprocess.dispose();
  75379. this._verticalBlurPostprocess.dispose();
  75380. };
  75381. /**
  75382. * Dispose the highlight layer and free resources.
  75383. */
  75384. HighlightLayer.prototype.dispose = function () {
  75385. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75386. if (vertexBuffer) {
  75387. vertexBuffer.dispose();
  75388. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75389. }
  75390. if (this._indexBuffer) {
  75391. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75392. this._indexBuffer = null;
  75393. }
  75394. // Clean textures and post processes
  75395. this.disposeTextureAndPostProcesses();
  75396. if (this._meshes) {
  75397. // Clean mesh references
  75398. for (var id in this._meshes) {
  75399. var meshHighlight = this._meshes[id];
  75400. if (meshHighlight && meshHighlight.mesh) {
  75401. if (meshHighlight.observerHighlight) {
  75402. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  75403. }
  75404. if (meshHighlight.observerDefault) {
  75405. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  75406. }
  75407. }
  75408. }
  75409. this._meshes = null;
  75410. }
  75411. if (this._excludedMeshes) {
  75412. for (var id in this._excludedMeshes) {
  75413. var meshHighlight = this._excludedMeshes[id];
  75414. if (meshHighlight) {
  75415. if (meshHighlight.beforeRender) {
  75416. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  75417. }
  75418. if (meshHighlight.afterRender) {
  75419. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  75420. }
  75421. }
  75422. }
  75423. this._excludedMeshes = null;
  75424. }
  75425. // Remove from scene
  75426. var index = this._scene.highlightLayers.indexOf(this, 0);
  75427. if (index > -1) {
  75428. this._scene.highlightLayers.splice(index, 1);
  75429. }
  75430. // Callback
  75431. this.onDisposeObservable.notifyObservers(this);
  75432. this.onDisposeObservable.clear();
  75433. this.onBeforeRenderMainTextureObservable.clear();
  75434. this.onBeforeBlurObservable.clear();
  75435. this.onBeforeComposeObservable.clear();
  75436. this.onAfterComposeObservable.clear();
  75437. this.onSizeChangedObservable.clear();
  75438. };
  75439. /**
  75440. * The neutral color used during the preparation of the glow effect.
  75441. * This is black by default as the blend operation is a blend operation.
  75442. */
  75443. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  75444. /**
  75445. * Stencil value used for glowing meshes.
  75446. */
  75447. HighlightLayer.glowingMeshStencilReference = 0x02;
  75448. /**
  75449. * Stencil value used for the other meshes in the scene.
  75450. */
  75451. HighlightLayer.normalMeshStencilReference = 0x01;
  75452. return HighlightLayer;
  75453. }());
  75454. BABYLON.HighlightLayer = HighlightLayer;
  75455. })(BABYLON || (BABYLON = {}));
  75456. //# sourceMappingURL=babylon.highlightlayer.js.map
  75457. var BABYLON;
  75458. (function (BABYLON) {
  75459. var AssetTaskState;
  75460. (function (AssetTaskState) {
  75461. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  75462. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  75463. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  75464. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  75465. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  75466. var AbstractAssetTask = /** @class */ (function () {
  75467. function AbstractAssetTask(name) {
  75468. this.name = name;
  75469. this.isCompleted = false;
  75470. this.taskState = AssetTaskState.INIT;
  75471. }
  75472. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  75473. var _this = this;
  75474. this.taskState = AssetTaskState.RUNNING;
  75475. this.runTask(scene, function () {
  75476. _this.onDoneCallback(onSuccess, onError);
  75477. }, function (msg, exception) {
  75478. _this.onErrorCallback(onError, msg, exception);
  75479. });
  75480. };
  75481. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75482. throw new Error("runTask is not implemented");
  75483. };
  75484. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  75485. this.taskState = AssetTaskState.ERROR;
  75486. this.errorObject = {
  75487. message: message,
  75488. exception: exception
  75489. };
  75490. if (this.onError) {
  75491. this.onError(this, message, exception);
  75492. }
  75493. onError();
  75494. };
  75495. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  75496. try {
  75497. this.taskState = AssetTaskState.DONE;
  75498. this.isCompleted = true;
  75499. if (this.onSuccess) {
  75500. this.onSuccess(this);
  75501. }
  75502. onSuccess();
  75503. }
  75504. catch (e) {
  75505. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  75506. }
  75507. };
  75508. return AbstractAssetTask;
  75509. }());
  75510. BABYLON.AbstractAssetTask = AbstractAssetTask;
  75511. var AssetsProgressEvent = /** @class */ (function () {
  75512. function AssetsProgressEvent(remainingCount, totalCount, task) {
  75513. this.remainingCount = remainingCount;
  75514. this.totalCount = totalCount;
  75515. this.task = task;
  75516. }
  75517. return AssetsProgressEvent;
  75518. }());
  75519. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  75520. var MeshAssetTask = /** @class */ (function (_super) {
  75521. __extends(MeshAssetTask, _super);
  75522. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  75523. var _this = _super.call(this, name) || this;
  75524. _this.name = name;
  75525. _this.meshesNames = meshesNames;
  75526. _this.rootUrl = rootUrl;
  75527. _this.sceneFilename = sceneFilename;
  75528. return _this;
  75529. }
  75530. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75531. var _this = this;
  75532. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  75533. _this.loadedMeshes = meshes;
  75534. _this.loadedParticleSystems = particleSystems;
  75535. _this.loadedSkeletons = skeletons;
  75536. onSuccess();
  75537. }, null, function (scene, message, exception) {
  75538. onError(message, exception);
  75539. });
  75540. };
  75541. return MeshAssetTask;
  75542. }(AbstractAssetTask));
  75543. BABYLON.MeshAssetTask = MeshAssetTask;
  75544. var TextFileAssetTask = /** @class */ (function (_super) {
  75545. __extends(TextFileAssetTask, _super);
  75546. function TextFileAssetTask(name, url) {
  75547. var _this = _super.call(this, name) || this;
  75548. _this.name = name;
  75549. _this.url = url;
  75550. return _this;
  75551. }
  75552. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75553. var _this = this;
  75554. BABYLON.Tools.LoadFile(this.url, function (data) {
  75555. _this.text = data;
  75556. onSuccess();
  75557. }, undefined, scene.database, false, function (request, exception) {
  75558. if (request) {
  75559. onError(request.status + " " + request.statusText, exception);
  75560. }
  75561. });
  75562. };
  75563. return TextFileAssetTask;
  75564. }(AbstractAssetTask));
  75565. BABYLON.TextFileAssetTask = TextFileAssetTask;
  75566. var BinaryFileAssetTask = /** @class */ (function (_super) {
  75567. __extends(BinaryFileAssetTask, _super);
  75568. function BinaryFileAssetTask(name, url) {
  75569. var _this = _super.call(this, name) || this;
  75570. _this.name = name;
  75571. _this.url = url;
  75572. return _this;
  75573. }
  75574. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75575. var _this = this;
  75576. BABYLON.Tools.LoadFile(this.url, function (data) {
  75577. _this.data = data;
  75578. onSuccess();
  75579. }, undefined, scene.database, true, function (request, exception) {
  75580. if (request) {
  75581. onError(request.status + " " + request.statusText, exception);
  75582. }
  75583. });
  75584. };
  75585. return BinaryFileAssetTask;
  75586. }(AbstractAssetTask));
  75587. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  75588. var ImageAssetTask = /** @class */ (function (_super) {
  75589. __extends(ImageAssetTask, _super);
  75590. function ImageAssetTask(name, url) {
  75591. var _this = _super.call(this, name) || this;
  75592. _this.name = name;
  75593. _this.url = url;
  75594. return _this;
  75595. }
  75596. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75597. var _this = this;
  75598. var img = new Image();
  75599. BABYLON.Tools.SetCorsBehavior(this.url, img);
  75600. img.onload = function () {
  75601. _this.image = img;
  75602. onSuccess();
  75603. };
  75604. img.onerror = function (err) {
  75605. onError("Error loading image", err);
  75606. };
  75607. img.src = this.url;
  75608. };
  75609. return ImageAssetTask;
  75610. }(AbstractAssetTask));
  75611. BABYLON.ImageAssetTask = ImageAssetTask;
  75612. var TextureAssetTask = /** @class */ (function (_super) {
  75613. __extends(TextureAssetTask, _super);
  75614. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  75615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75616. var _this = _super.call(this, name) || this;
  75617. _this.name = name;
  75618. _this.url = url;
  75619. _this.noMipmap = noMipmap;
  75620. _this.invertY = invertY;
  75621. _this.samplingMode = samplingMode;
  75622. return _this;
  75623. }
  75624. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75625. var onload = function () {
  75626. onSuccess();
  75627. };
  75628. var onerror = function (message, exception) {
  75629. onError(message, exception);
  75630. };
  75631. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  75632. };
  75633. return TextureAssetTask;
  75634. }(AbstractAssetTask));
  75635. BABYLON.TextureAssetTask = TextureAssetTask;
  75636. var CubeTextureAssetTask = /** @class */ (function (_super) {
  75637. __extends(CubeTextureAssetTask, _super);
  75638. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  75639. var _this = _super.call(this, name) || this;
  75640. _this.name = name;
  75641. _this.url = url;
  75642. _this.extensions = extensions;
  75643. _this.noMipmap = noMipmap;
  75644. _this.files = files;
  75645. return _this;
  75646. }
  75647. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  75648. var onload = function () {
  75649. onSuccess();
  75650. };
  75651. var onerror = function (message, exception) {
  75652. onError(message, exception);
  75653. };
  75654. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  75655. };
  75656. return CubeTextureAssetTask;
  75657. }(AbstractAssetTask));
  75658. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  75659. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  75660. __extends(HDRCubeTextureAssetTask, _super);
  75661. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  75662. if (noMipmap === void 0) { noMipmap = false; }
  75663. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75664. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75665. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75666. var _this = _super.call(this, name) || this;
  75667. _this.name = name;
  75668. _this.url = url;
  75669. _this.size = size;
  75670. _this.noMipmap = noMipmap;
  75671. _this.generateHarmonics = generateHarmonics;
  75672. _this.useInGammaSpace = useInGammaSpace;
  75673. _this.usePMREMGenerator = usePMREMGenerator;
  75674. return _this;
  75675. }
  75676. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  75677. var onload = function () {
  75678. onSuccess();
  75679. };
  75680. var onerror = function (message, exception) {
  75681. onError(message, exception);
  75682. };
  75683. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  75684. };
  75685. return HDRCubeTextureAssetTask;
  75686. }(AbstractAssetTask));
  75687. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  75688. var AssetsManager = /** @class */ (function () {
  75689. function AssetsManager(scene) {
  75690. this.tasks = new Array();
  75691. this.waitingTasksCount = 0;
  75692. //Observables
  75693. this.onTaskSuccessObservable = new BABYLON.Observable();
  75694. this.onTaskErrorObservable = new BABYLON.Observable();
  75695. this.onTasksDoneObservable = new BABYLON.Observable();
  75696. this.onProgressObservable = new BABYLON.Observable();
  75697. this.useDefaultLoadingScreen = true;
  75698. this._scene = scene;
  75699. }
  75700. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  75701. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  75702. this.tasks.push(task);
  75703. return task;
  75704. };
  75705. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  75706. var task = new TextFileAssetTask(taskName, url);
  75707. this.tasks.push(task);
  75708. return task;
  75709. };
  75710. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  75711. var task = new BinaryFileAssetTask(taskName, url);
  75712. this.tasks.push(task);
  75713. return task;
  75714. };
  75715. AssetsManager.prototype.addImageTask = function (taskName, url) {
  75716. var task = new ImageAssetTask(taskName, url);
  75717. this.tasks.push(task);
  75718. return task;
  75719. };
  75720. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  75721. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75722. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  75723. this.tasks.push(task);
  75724. return task;
  75725. };
  75726. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  75727. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  75728. this.tasks.push(task);
  75729. return task;
  75730. };
  75731. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  75732. if (noMipmap === void 0) { noMipmap = false; }
  75733. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75734. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75735. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75736. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  75737. this.tasks.push(task);
  75738. return task;
  75739. };
  75740. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  75741. this.waitingTasksCount--;
  75742. try {
  75743. if (this.onProgress) {
  75744. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  75745. }
  75746. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  75747. }
  75748. catch (e) {
  75749. BABYLON.Tools.Error("Error running progress callbacks.");
  75750. console.log(e);
  75751. }
  75752. if (this.waitingTasksCount === 0) {
  75753. try {
  75754. if (this.onFinish) {
  75755. this.onFinish(this.tasks);
  75756. }
  75757. this.onTasksDoneObservable.notifyObservers(this.tasks);
  75758. }
  75759. catch (e) {
  75760. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  75761. console.log(e);
  75762. }
  75763. this._scene.getEngine().hideLoadingUI();
  75764. }
  75765. };
  75766. AssetsManager.prototype._runTask = function (task) {
  75767. var _this = this;
  75768. var done = function () {
  75769. try {
  75770. if (_this.onTaskSuccess) {
  75771. _this.onTaskSuccess(task);
  75772. }
  75773. _this.onTaskSuccessObservable.notifyObservers(task);
  75774. _this._decreaseWaitingTasksCount(task);
  75775. }
  75776. catch (e) {
  75777. error("Error executing task success callbacks", e);
  75778. }
  75779. };
  75780. var error = function (message, exception) {
  75781. task.errorObject = task.errorObject || {
  75782. message: message,
  75783. exception: exception
  75784. };
  75785. if (_this.onTaskError) {
  75786. _this.onTaskError(task);
  75787. }
  75788. _this.onTaskErrorObservable.notifyObservers(task);
  75789. _this._decreaseWaitingTasksCount(task);
  75790. };
  75791. task.run(this._scene, done, error);
  75792. };
  75793. AssetsManager.prototype.reset = function () {
  75794. this.tasks = new Array();
  75795. return this;
  75796. };
  75797. AssetsManager.prototype.load = function () {
  75798. this.waitingTasksCount = this.tasks.length;
  75799. if (this.waitingTasksCount === 0) {
  75800. if (this.onFinish) {
  75801. this.onFinish(this.tasks);
  75802. }
  75803. this.onTasksDoneObservable.notifyObservers(this.tasks);
  75804. return this;
  75805. }
  75806. if (this.useDefaultLoadingScreen) {
  75807. this._scene.getEngine().displayLoadingUI();
  75808. }
  75809. for (var index = 0; index < this.tasks.length; index++) {
  75810. var task = this.tasks[index];
  75811. this._runTask(task);
  75812. }
  75813. return this;
  75814. };
  75815. return AssetsManager;
  75816. }());
  75817. BABYLON.AssetsManager = AssetsManager;
  75818. })(BABYLON || (BABYLON = {}));
  75819. //# sourceMappingURL=babylon.assetsManager.js.map
  75820. var BABYLON;
  75821. (function (BABYLON) {
  75822. var serializedGeometries = [];
  75823. var serializeGeometry = function (geometry, serializationGeometries) {
  75824. if (serializedGeometries[geometry.id]) {
  75825. return;
  75826. }
  75827. if (geometry.doNotSerialize) {
  75828. return;
  75829. }
  75830. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  75831. serializationGeometries.boxes.push(geometry.serialize());
  75832. }
  75833. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  75834. serializationGeometries.spheres.push(geometry.serialize());
  75835. }
  75836. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  75837. serializationGeometries.cylinders.push(geometry.serialize());
  75838. }
  75839. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  75840. serializationGeometries.toruses.push(geometry.serialize());
  75841. }
  75842. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  75843. serializationGeometries.grounds.push(geometry.serialize());
  75844. }
  75845. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  75846. serializationGeometries.planes.push(geometry.serialize());
  75847. }
  75848. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  75849. serializationGeometries.torusKnots.push(geometry.serialize());
  75850. }
  75851. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  75852. throw new Error("Unknown primitive type");
  75853. }
  75854. else {
  75855. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  75856. }
  75857. serializedGeometries[geometry.id] = true;
  75858. };
  75859. var serializeMesh = function (mesh, serializationScene) {
  75860. var serializationObject = {};
  75861. // Geometry
  75862. var geometry = mesh._geometry;
  75863. if (geometry) {
  75864. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  75865. // 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
  75866. serializeGeometry(geometry, serializationScene.geometries);
  75867. }
  75868. }
  75869. // Custom
  75870. if (mesh.serialize) {
  75871. mesh.serialize(serializationObject);
  75872. }
  75873. return serializationObject;
  75874. };
  75875. var finalizeSingleMesh = function (mesh, serializationObject) {
  75876. //only works if the mesh is already loaded
  75877. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  75878. //serialize material
  75879. if (mesh.material) {
  75880. if (mesh.material instanceof BABYLON.StandardMaterial) {
  75881. serializationObject.materials = serializationObject.materials || [];
  75882. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75883. serializationObject.materials.push(mesh.material.serialize());
  75884. }
  75885. }
  75886. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  75887. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  75888. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  75889. serializationObject.multiMaterials.push(mesh.material.serialize());
  75890. }
  75891. }
  75892. }
  75893. //serialize geometry
  75894. var geometry = mesh._geometry;
  75895. if (geometry) {
  75896. if (!serializationObject.geometries) {
  75897. serializationObject.geometries = {};
  75898. serializationObject.geometries.boxes = [];
  75899. serializationObject.geometries.spheres = [];
  75900. serializationObject.geometries.cylinders = [];
  75901. serializationObject.geometries.toruses = [];
  75902. serializationObject.geometries.grounds = [];
  75903. serializationObject.geometries.planes = [];
  75904. serializationObject.geometries.torusKnots = [];
  75905. serializationObject.geometries.vertexData = [];
  75906. }
  75907. serializeGeometry(geometry, serializationObject.geometries);
  75908. }
  75909. // Skeletons
  75910. if (mesh.skeleton) {
  75911. serializationObject.skeletons = serializationObject.skeletons || [];
  75912. serializationObject.skeletons.push(mesh.skeleton.serialize());
  75913. }
  75914. //serialize the actual mesh
  75915. serializationObject.meshes = serializationObject.meshes || [];
  75916. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  75917. }
  75918. };
  75919. var SceneSerializer = /** @class */ (function () {
  75920. function SceneSerializer() {
  75921. }
  75922. SceneSerializer.ClearCache = function () {
  75923. serializedGeometries = [];
  75924. };
  75925. SceneSerializer.Serialize = function (scene) {
  75926. var serializationObject = {};
  75927. SceneSerializer.ClearCache();
  75928. // Scene
  75929. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  75930. serializationObject.autoClear = scene.autoClear;
  75931. serializationObject.clearColor = scene.clearColor.asArray();
  75932. serializationObject.ambientColor = scene.ambientColor.asArray();
  75933. serializationObject.gravity = scene.gravity.asArray();
  75934. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  75935. serializationObject.workerCollisions = scene.workerCollisions;
  75936. // Fog
  75937. if (scene.fogMode && scene.fogMode !== 0) {
  75938. serializationObject.fogMode = scene.fogMode;
  75939. serializationObject.fogColor = scene.fogColor.asArray();
  75940. serializationObject.fogStart = scene.fogStart;
  75941. serializationObject.fogEnd = scene.fogEnd;
  75942. serializationObject.fogDensity = scene.fogDensity;
  75943. }
  75944. //Physics
  75945. if (scene.isPhysicsEnabled()) {
  75946. var physicEngine = scene.getPhysicsEngine();
  75947. if (physicEngine) {
  75948. serializationObject.physicsEnabled = true;
  75949. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  75950. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  75951. }
  75952. }
  75953. // Metadata
  75954. if (scene.metadata) {
  75955. serializationObject.metadata = scene.metadata;
  75956. }
  75957. // Morph targets
  75958. serializationObject.morphTargetManagers = [];
  75959. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  75960. var abstractMesh = _a[_i];
  75961. var manager = abstractMesh.morphTargetManager;
  75962. if (manager) {
  75963. serializationObject.morphTargetManagers.push(manager.serialize());
  75964. }
  75965. }
  75966. // Lights
  75967. serializationObject.lights = [];
  75968. var index;
  75969. var light;
  75970. for (index = 0; index < scene.lights.length; index++) {
  75971. light = scene.lights[index];
  75972. if (!light.doNotSerialize) {
  75973. serializationObject.lights.push(light.serialize());
  75974. }
  75975. }
  75976. // Cameras
  75977. serializationObject.cameras = [];
  75978. for (index = 0; index < scene.cameras.length; index++) {
  75979. var camera = scene.cameras[index];
  75980. if (!camera.doNotSerialize) {
  75981. serializationObject.cameras.push(camera.serialize());
  75982. }
  75983. }
  75984. if (scene.activeCamera) {
  75985. serializationObject.activeCameraID = scene.activeCamera.id;
  75986. }
  75987. // Animations
  75988. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  75989. // Materials
  75990. serializationObject.materials = [];
  75991. serializationObject.multiMaterials = [];
  75992. var material;
  75993. for (index = 0; index < scene.materials.length; index++) {
  75994. material = scene.materials[index];
  75995. if (!material.doNotSerialize) {
  75996. serializationObject.materials.push(material.serialize());
  75997. }
  75998. }
  75999. // MultiMaterials
  76000. serializationObject.multiMaterials = [];
  76001. for (index = 0; index < scene.multiMaterials.length; index++) {
  76002. var multiMaterial = scene.multiMaterials[index];
  76003. serializationObject.multiMaterials.push(multiMaterial.serialize());
  76004. }
  76005. // Skeletons
  76006. serializationObject.skeletons = [];
  76007. for (index = 0; index < scene.skeletons.length; index++) {
  76008. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  76009. }
  76010. // Transform nodes
  76011. serializationObject.transformNodes = [];
  76012. for (index = 0; index < scene.transformNodes.length; index++) {
  76013. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  76014. }
  76015. // Geometries
  76016. serializationObject.geometries = {};
  76017. serializationObject.geometries.boxes = [];
  76018. serializationObject.geometries.spheres = [];
  76019. serializationObject.geometries.cylinders = [];
  76020. serializationObject.geometries.toruses = [];
  76021. serializationObject.geometries.grounds = [];
  76022. serializationObject.geometries.planes = [];
  76023. serializationObject.geometries.torusKnots = [];
  76024. serializationObject.geometries.vertexData = [];
  76025. serializedGeometries = [];
  76026. var geometries = scene.getGeometries();
  76027. for (index = 0; index < geometries.length; index++) {
  76028. var geometry = geometries[index];
  76029. if (geometry.isReady()) {
  76030. serializeGeometry(geometry, serializationObject.geometries);
  76031. }
  76032. }
  76033. // Meshes
  76034. serializationObject.meshes = [];
  76035. for (index = 0; index < scene.meshes.length; index++) {
  76036. var abstractMesh = scene.meshes[index];
  76037. if (abstractMesh instanceof BABYLON.Mesh) {
  76038. var mesh = abstractMesh;
  76039. if (!mesh.doNotSerialize) {
  76040. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76041. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76042. }
  76043. }
  76044. }
  76045. }
  76046. // Particles Systems
  76047. serializationObject.particleSystems = [];
  76048. for (index = 0; index < scene.particleSystems.length; index++) {
  76049. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  76050. }
  76051. // Lens flares
  76052. serializationObject.lensFlareSystems = [];
  76053. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  76054. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  76055. }
  76056. // Shadows
  76057. serializationObject.shadowGenerators = [];
  76058. for (index = 0; index < scene.lights.length; index++) {
  76059. light = scene.lights[index];
  76060. var shadowGenerator = light.getShadowGenerator();
  76061. if (shadowGenerator) {
  76062. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  76063. }
  76064. }
  76065. // Action Manager
  76066. if (scene.actionManager) {
  76067. serializationObject.actions = scene.actionManager.serialize("scene");
  76068. }
  76069. // Audio
  76070. serializationObject.sounds = [];
  76071. for (index = 0; index < scene.soundTracks.length; index++) {
  76072. var soundtrack = scene.soundTracks[index];
  76073. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  76074. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  76075. }
  76076. }
  76077. return serializationObject;
  76078. };
  76079. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  76080. if (withParents === void 0) { withParents = false; }
  76081. if (withChildren === void 0) { withChildren = false; }
  76082. var serializationObject = {};
  76083. SceneSerializer.ClearCache();
  76084. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  76085. if (withParents || withChildren) {
  76086. //deliberate for loop! not for each, appended should be processed as well.
  76087. for (var i = 0; i < toSerialize.length; ++i) {
  76088. if (withChildren) {
  76089. toSerialize[i].getDescendants().forEach(function (node) {
  76090. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  76091. toSerialize.push(node);
  76092. }
  76093. });
  76094. }
  76095. //make sure the array doesn't contain the object already
  76096. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  76097. toSerialize.push(toSerialize[i].parent);
  76098. }
  76099. }
  76100. }
  76101. toSerialize.forEach(function (mesh) {
  76102. finalizeSingleMesh(mesh, serializationObject);
  76103. });
  76104. return serializationObject;
  76105. };
  76106. return SceneSerializer;
  76107. }());
  76108. BABYLON.SceneSerializer = SceneSerializer;
  76109. })(BABYLON || (BABYLON = {}));
  76110. //# sourceMappingURL=babylon.sceneSerializer.js.map
  76111. var BABYLON;
  76112. (function (BABYLON) {
  76113. var ReflectionProbe = /** @class */ (function () {
  76114. function ReflectionProbe(name, size, scene, generateMipMaps) {
  76115. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76116. var _this = this;
  76117. this.name = name;
  76118. this._viewMatrix = BABYLON.Matrix.Identity();
  76119. this._target = BABYLON.Vector3.Zero();
  76120. this._add = BABYLON.Vector3.Zero();
  76121. this.invertYAxis = false;
  76122. this.position = BABYLON.Vector3.Zero();
  76123. this._scene = scene;
  76124. this._scene.reflectionProbes.push(this);
  76125. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  76126. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  76127. switch (faceIndex) {
  76128. case 0:
  76129. _this._add.copyFromFloats(1, 0, 0);
  76130. break;
  76131. case 1:
  76132. _this._add.copyFromFloats(-1, 0, 0);
  76133. break;
  76134. case 2:
  76135. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  76136. break;
  76137. case 3:
  76138. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  76139. break;
  76140. case 4:
  76141. _this._add.copyFromFloats(0, 0, 1);
  76142. break;
  76143. case 5:
  76144. _this._add.copyFromFloats(0, 0, -1);
  76145. break;
  76146. }
  76147. if (_this._attachedMesh) {
  76148. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  76149. }
  76150. _this.position.addToRef(_this._add, _this._target);
  76151. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  76152. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  76153. scene._forcedViewPosition = _this.position;
  76154. });
  76155. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  76156. scene._forcedViewPosition = null;
  76157. scene.updateTransformMatrix(true);
  76158. });
  76159. if (scene.activeCamera) {
  76160. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  76161. }
  76162. }
  76163. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  76164. get: function () {
  76165. return this._renderTargetTexture.samples;
  76166. },
  76167. set: function (value) {
  76168. this._renderTargetTexture.samples = value;
  76169. },
  76170. enumerable: true,
  76171. configurable: true
  76172. });
  76173. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  76174. get: function () {
  76175. return this._renderTargetTexture.refreshRate;
  76176. },
  76177. set: function (value) {
  76178. this._renderTargetTexture.refreshRate = value;
  76179. },
  76180. enumerable: true,
  76181. configurable: true
  76182. });
  76183. ReflectionProbe.prototype.getScene = function () {
  76184. return this._scene;
  76185. };
  76186. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  76187. get: function () {
  76188. return this._renderTargetTexture;
  76189. },
  76190. enumerable: true,
  76191. configurable: true
  76192. });
  76193. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  76194. get: function () {
  76195. return this._renderTargetTexture.renderList;
  76196. },
  76197. enumerable: true,
  76198. configurable: true
  76199. });
  76200. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  76201. this._attachedMesh = mesh;
  76202. };
  76203. /**
  76204. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  76205. *
  76206. * @param renderingGroupId The rendering group id corresponding to its index
  76207. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  76208. */
  76209. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  76210. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  76211. };
  76212. ReflectionProbe.prototype.dispose = function () {
  76213. var index = this._scene.reflectionProbes.indexOf(this);
  76214. if (index !== -1) {
  76215. // Remove from the scene if found
  76216. this._scene.reflectionProbes.splice(index, 1);
  76217. }
  76218. if (this._renderTargetTexture) {
  76219. this._renderTargetTexture.dispose();
  76220. this._renderTargetTexture = null;
  76221. }
  76222. };
  76223. return ReflectionProbe;
  76224. }());
  76225. BABYLON.ReflectionProbe = ReflectionProbe;
  76226. })(BABYLON || (BABYLON = {}));
  76227. //# sourceMappingURL=babylon.reflectionProbe.js.map
  76228. var BABYLON;
  76229. (function (BABYLON) {
  76230. var Layer = /** @class */ (function () {
  76231. function Layer(name, imgUrl, scene, isBackground, color) {
  76232. this.name = name;
  76233. this.scale = new BABYLON.Vector2(1, 1);
  76234. this.offset = new BABYLON.Vector2(0, 0);
  76235. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  76236. this.layerMask = 0x0FFFFFFF;
  76237. this._vertexBuffers = {};
  76238. // Events
  76239. /**
  76240. * An event triggered when the layer is disposed.
  76241. * @type {BABYLON.Observable}
  76242. */
  76243. this.onDisposeObservable = new BABYLON.Observable();
  76244. /**
  76245. * An event triggered before rendering the scene
  76246. * @type {BABYLON.Observable}
  76247. */
  76248. this.onBeforeRenderObservable = new BABYLON.Observable();
  76249. /**
  76250. * An event triggered after rendering the scene
  76251. * @type {BABYLON.Observable}
  76252. */
  76253. this.onAfterRenderObservable = new BABYLON.Observable();
  76254. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  76255. this.isBackground = isBackground === undefined ? true : isBackground;
  76256. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  76257. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  76258. this._scene.layers.push(this);
  76259. var engine = this._scene.getEngine();
  76260. // VBO
  76261. var vertices = [];
  76262. vertices.push(1, 1);
  76263. vertices.push(-1, 1);
  76264. vertices.push(-1, -1);
  76265. vertices.push(1, -1);
  76266. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76267. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76268. this._createIndexBuffer();
  76269. // Effects
  76270. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  76271. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  76272. }
  76273. Object.defineProperty(Layer.prototype, "onDispose", {
  76274. set: function (callback) {
  76275. if (this._onDisposeObserver) {
  76276. this.onDisposeObservable.remove(this._onDisposeObserver);
  76277. }
  76278. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  76279. },
  76280. enumerable: true,
  76281. configurable: true
  76282. });
  76283. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  76284. set: function (callback) {
  76285. if (this._onBeforeRenderObserver) {
  76286. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  76287. }
  76288. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  76289. },
  76290. enumerable: true,
  76291. configurable: true
  76292. });
  76293. Object.defineProperty(Layer.prototype, "onAfterRender", {
  76294. set: function (callback) {
  76295. if (this._onAfterRenderObserver) {
  76296. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76297. }
  76298. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  76299. },
  76300. enumerable: true,
  76301. configurable: true
  76302. });
  76303. Layer.prototype._createIndexBuffer = function () {
  76304. var engine = this._scene.getEngine();
  76305. // Indices
  76306. var indices = [];
  76307. indices.push(0);
  76308. indices.push(1);
  76309. indices.push(2);
  76310. indices.push(0);
  76311. indices.push(2);
  76312. indices.push(3);
  76313. this._indexBuffer = engine.createIndexBuffer(indices);
  76314. };
  76315. Layer.prototype._rebuild = function () {
  76316. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76317. if (vb) {
  76318. vb._rebuild();
  76319. }
  76320. this._createIndexBuffer();
  76321. };
  76322. Layer.prototype.render = function () {
  76323. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  76324. // Check
  76325. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  76326. return;
  76327. var engine = this._scene.getEngine();
  76328. this.onBeforeRenderObservable.notifyObservers(this);
  76329. // Render
  76330. engine.enableEffect(currentEffect);
  76331. engine.setState(false);
  76332. // Texture
  76333. currentEffect.setTexture("textureSampler", this.texture);
  76334. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  76335. // Color
  76336. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  76337. // Scale / offset
  76338. currentEffect.setVector2("offset", this.offset);
  76339. currentEffect.setVector2("scale", this.scale);
  76340. // VBOs
  76341. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76342. // Draw order
  76343. if (!this.alphaTest) {
  76344. engine.setAlphaMode(this.alphaBlendingMode);
  76345. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76346. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76347. }
  76348. else {
  76349. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76350. }
  76351. this.onAfterRenderObservable.notifyObservers(this);
  76352. };
  76353. Layer.prototype.dispose = function () {
  76354. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76355. if (vertexBuffer) {
  76356. vertexBuffer.dispose();
  76357. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76358. }
  76359. if (this._indexBuffer) {
  76360. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76361. this._indexBuffer = null;
  76362. }
  76363. if (this.texture) {
  76364. this.texture.dispose();
  76365. this.texture = null;
  76366. }
  76367. // Remove from scene
  76368. var index = this._scene.layers.indexOf(this);
  76369. this._scene.layers.splice(index, 1);
  76370. // Callback
  76371. this.onDisposeObservable.notifyObservers(this);
  76372. this.onDisposeObservable.clear();
  76373. this.onAfterRenderObservable.clear();
  76374. this.onBeforeRenderObservable.clear();
  76375. };
  76376. return Layer;
  76377. }());
  76378. BABYLON.Layer = Layer;
  76379. })(BABYLON || (BABYLON = {}));
  76380. //# sourceMappingURL=babylon.layer.js.map
  76381. var BABYLON;
  76382. (function (BABYLON) {
  76383. var TextureTools = /** @class */ (function () {
  76384. function TextureTools() {
  76385. }
  76386. /**
  76387. * Uses the GPU to create a copy texture rescaled at a given size
  76388. * @param texture Texture to copy from
  76389. * @param width Desired width
  76390. * @param height Desired height
  76391. * @return Generated texture
  76392. */
  76393. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  76394. if (useBilinearMode === void 0) { useBilinearMode = true; }
  76395. var scene = texture.getScene();
  76396. var engine = scene.getEngine();
  76397. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  76398. rtt.wrapU = texture.wrapU;
  76399. rtt.wrapV = texture.wrapV;
  76400. rtt.uOffset = texture.uOffset;
  76401. rtt.vOffset = texture.vOffset;
  76402. rtt.uScale = texture.uScale;
  76403. rtt.vScale = texture.vScale;
  76404. rtt.uAng = texture.uAng;
  76405. rtt.vAng = texture.vAng;
  76406. rtt.wAng = texture.wAng;
  76407. rtt.coordinatesIndex = texture.coordinatesIndex;
  76408. rtt.level = texture.level;
  76409. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  76410. rtt._texture.isReady = false;
  76411. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76412. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76413. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76414. passPostProcess.getEffect().executeWhenCompiled(function () {
  76415. passPostProcess.onApply = function (effect) {
  76416. effect.setTexture("textureSampler", texture);
  76417. };
  76418. var internalTexture = rtt.getInternalTexture();
  76419. if (internalTexture) {
  76420. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  76421. engine.unBindFramebuffer(internalTexture);
  76422. rtt.disposeFramebufferObjects();
  76423. passPostProcess.dispose();
  76424. internalTexture.isReady = true;
  76425. }
  76426. });
  76427. return rtt;
  76428. };
  76429. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  76430. if (!scene._environmentBRDFTexture) {
  76431. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76432. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76433. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76434. scene._environmentBRDFTexture = texture;
  76435. }
  76436. return scene._environmentBRDFTexture;
  76437. };
  76438. 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=";
  76439. return TextureTools;
  76440. }());
  76441. BABYLON.TextureTools = TextureTools;
  76442. })(BABYLON || (BABYLON = {}));
  76443. //# sourceMappingURL=babylon.textureTools.js.map
  76444. var BABYLON;
  76445. (function (BABYLON) {
  76446. var FramingBehavior = /** @class */ (function () {
  76447. function FramingBehavior() {
  76448. this._mode = FramingBehavior.FitFrustumSidesMode;
  76449. this._radiusScale = 1.0;
  76450. this._positionScale = 0.5;
  76451. this._defaultElevation = 0.3;
  76452. this._elevationReturnTime = 1500;
  76453. this._elevationReturnWaitTime = 1000;
  76454. this._zoomStopsAnimation = false;
  76455. this._framingTime = 1500;
  76456. this._isPointerDown = false;
  76457. this._lastInteractionTime = -Infinity;
  76458. // Framing control
  76459. this._animatables = new Array();
  76460. this._betaIsAnimating = false;
  76461. }
  76462. Object.defineProperty(FramingBehavior.prototype, "name", {
  76463. get: function () {
  76464. return "Framing";
  76465. },
  76466. enumerable: true,
  76467. configurable: true
  76468. });
  76469. Object.defineProperty(FramingBehavior.prototype, "mode", {
  76470. /**
  76471. * Gets current mode used by the behavior.
  76472. */
  76473. get: function () {
  76474. return this._mode;
  76475. },
  76476. /**
  76477. * Sets the current mode used by the behavior
  76478. */
  76479. set: function (mode) {
  76480. this._mode = mode;
  76481. },
  76482. enumerable: true,
  76483. configurable: true
  76484. });
  76485. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  76486. /**
  76487. * Gets the scale applied to the radius
  76488. */
  76489. get: function () {
  76490. return this._radiusScale;
  76491. },
  76492. /**
  76493. * Sets the scale applied to the radius (1 by default)
  76494. */
  76495. set: function (radius) {
  76496. this._radiusScale = radius;
  76497. },
  76498. enumerable: true,
  76499. configurable: true
  76500. });
  76501. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  76502. /**
  76503. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  76504. */
  76505. get: function () {
  76506. return this._positionScale;
  76507. },
  76508. /**
  76509. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  76510. */
  76511. set: function (scale) {
  76512. this._positionScale = scale;
  76513. },
  76514. enumerable: true,
  76515. configurable: true
  76516. });
  76517. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  76518. /**
  76519. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  76520. * behaviour is triggered, in radians.
  76521. */
  76522. get: function () {
  76523. return this._defaultElevation;
  76524. },
  76525. /**
  76526. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  76527. * behaviour is triggered, in radians.
  76528. */
  76529. set: function (elevation) {
  76530. this._defaultElevation = elevation;
  76531. },
  76532. enumerable: true,
  76533. configurable: true
  76534. });
  76535. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  76536. /**
  76537. * Gets the time (in milliseconds) taken to return to the default beta position.
  76538. * Negative value indicates camera should not return to default.
  76539. */
  76540. get: function () {
  76541. return this._elevationReturnTime;
  76542. },
  76543. /**
  76544. * Sets the time (in milliseconds) taken to return to the default beta position.
  76545. * Negative value indicates camera should not return to default.
  76546. */
  76547. set: function (speed) {
  76548. this._elevationReturnTime = speed;
  76549. },
  76550. enumerable: true,
  76551. configurable: true
  76552. });
  76553. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  76554. /**
  76555. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  76556. */
  76557. get: function () {
  76558. return this._elevationReturnWaitTime;
  76559. },
  76560. /**
  76561. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  76562. */
  76563. set: function (time) {
  76564. this._elevationReturnWaitTime = time;
  76565. },
  76566. enumerable: true,
  76567. configurable: true
  76568. });
  76569. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  76570. /**
  76571. * Gets the flag that indicates if user zooming should stop animation.
  76572. */
  76573. get: function () {
  76574. return this._zoomStopsAnimation;
  76575. },
  76576. /**
  76577. * Sets the flag that indicates if user zooming should stop animation.
  76578. */
  76579. set: function (flag) {
  76580. this._zoomStopsAnimation = flag;
  76581. },
  76582. enumerable: true,
  76583. configurable: true
  76584. });
  76585. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  76586. /**
  76587. * Gets the transition time when framing the mesh, in milliseconds
  76588. */
  76589. get: function () {
  76590. return this._framingTime;
  76591. },
  76592. /**
  76593. * Sets the transition time when framing the mesh, in milliseconds
  76594. */
  76595. set: function (time) {
  76596. this._framingTime = time;
  76597. },
  76598. enumerable: true,
  76599. configurable: true
  76600. });
  76601. FramingBehavior.prototype.init = function () {
  76602. // Do notihng
  76603. };
  76604. FramingBehavior.prototype.attach = function (camera) {
  76605. var _this = this;
  76606. this._attachedCamera = camera;
  76607. var scene = this._attachedCamera.getScene();
  76608. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  76609. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  76610. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76611. _this._isPointerDown = true;
  76612. return;
  76613. }
  76614. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  76615. _this._isPointerDown = false;
  76616. }
  76617. });
  76618. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76619. if (mesh) {
  76620. _this.zoomOnMesh(mesh);
  76621. }
  76622. });
  76623. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  76624. // Stop the animation if there is user interaction and the animation should stop for this interaction
  76625. _this._applyUserInteraction();
  76626. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  76627. // back to the default position after a given timeout
  76628. _this._maintainCameraAboveGround();
  76629. });
  76630. };
  76631. FramingBehavior.prototype.detach = function () {
  76632. if (!this._attachedCamera) {
  76633. return;
  76634. }
  76635. var scene = this._attachedCamera.getScene();
  76636. if (this._onPrePointerObservableObserver) {
  76637. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  76638. }
  76639. if (this._onAfterCheckInputsObserver) {
  76640. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  76641. }
  76642. if (this._onMeshTargetChangedObserver) {
  76643. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76644. }
  76645. this._attachedCamera = null;
  76646. };
  76647. /**
  76648. * Targets the given mesh and updates zoom level accordingly.
  76649. * @param mesh The mesh to target.
  76650. * @param radius Optional. If a cached radius position already exists, overrides default.
  76651. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76652. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76653. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76654. */
  76655. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  76656. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76657. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76658. mesh.computeWorldMatrix(true);
  76659. var boundingBox = mesh.getBoundingInfo().boundingBox;
  76660. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  76661. };
  76662. /**
  76663. * Targets the given mesh with its children and updates zoom level accordingly.
  76664. * @param mesh The mesh to target.
  76665. * @param radius Optional. If a cached radius position already exists, overrides default.
  76666. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76667. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76668. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76669. */
  76670. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  76671. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76672. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76673. mesh.computeWorldMatrix(true);
  76674. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  76675. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  76676. };
  76677. /**
  76678. * Targets the given meshes with their children and updates zoom level accordingly.
  76679. * @param meshes The mesh to target.
  76680. * @param radius Optional. If a cached radius position already exists, overrides default.
  76681. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76682. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76683. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76684. */
  76685. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  76686. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76687. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76688. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76689. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  76690. for (var i = 0; i < meshes.length; i++) {
  76691. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  76692. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  76693. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  76694. }
  76695. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  76696. };
  76697. /**
  76698. * Targets the given mesh and updates zoom level accordingly.
  76699. * @param mesh The mesh to target.
  76700. * @param radius Optional. If a cached radius position already exists, overrides default.
  76701. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  76702. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  76703. * @param onAnimationEnd Callback triggered at the end of the framing animation
  76704. */
  76705. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  76706. var _this = this;
  76707. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  76708. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  76709. var zoomTarget;
  76710. if (!this._attachedCamera) {
  76711. return;
  76712. }
  76713. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  76714. var bottom = minimumWorld.y;
  76715. var top = maximumWorld.y;
  76716. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  76717. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  76718. if (focusOnOriginXZ) {
  76719. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  76720. }
  76721. else {
  76722. var centerWorld = minimumWorld.add(radiusWorld);
  76723. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  76724. }
  76725. if (!this._vectorTransition) {
  76726. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  76727. }
  76728. this._betaIsAnimating = true;
  76729. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  76730. if (animatable) {
  76731. this._animatables.push(animatable);
  76732. }
  76733. // sets the radius and lower radius bounds
  76734. // Small delta ensures camera is not always at lower zoom limit.
  76735. var radius = 0;
  76736. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  76737. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  76738. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  76739. radius = position;
  76740. }
  76741. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76742. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  76743. if (this._attachedCamera.lowerRadiusLimit === null) {
  76744. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  76745. }
  76746. }
  76747. // Set sensibilities
  76748. var extend = maximumWorld.subtract(minimumWorld).length();
  76749. this._attachedCamera.panningSensibility = 5000 / extend;
  76750. this._attachedCamera.wheelPrecision = 100 / radius;
  76751. // transition to new radius
  76752. if (!this._radiusTransition) {
  76753. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  76754. }
  76755. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  76756. if (onAnimationEnd) {
  76757. onAnimationEnd();
  76758. }
  76759. if (_this._attachedCamera) {
  76760. _this._attachedCamera.storeState();
  76761. }
  76762. });
  76763. if (animatable) {
  76764. this._animatables.push(animatable);
  76765. }
  76766. };
  76767. /**
  76768. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  76769. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  76770. * frustum width.
  76771. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  76772. * to fully enclose the mesh in the viewing frustum.
  76773. */
  76774. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  76775. var size = maximumWorld.subtract(minimumWorld);
  76776. var boxVectorGlobalDiagonal = size.length();
  76777. var frustumSlope = this._getFrustumSlope();
  76778. // Formula for setting distance
  76779. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  76780. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  76781. // Horizon distance
  76782. var radius = radiusWithoutFraming * this._radiusScale;
  76783. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  76784. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  76785. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  76786. var camera = this._attachedCamera;
  76787. if (!camera) {
  76788. return 0;
  76789. }
  76790. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  76791. // Don't exceed the requested limit
  76792. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  76793. }
  76794. // Don't exceed the upper radius limit
  76795. if (camera.upperRadiusLimit) {
  76796. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  76797. }
  76798. return distance;
  76799. };
  76800. /**
  76801. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  76802. * is automatically returned to its default position (expected to be above ground plane).
  76803. */
  76804. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  76805. var _this = this;
  76806. if (this._elevationReturnTime < 0) {
  76807. return;
  76808. }
  76809. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  76810. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  76811. var limitBeta = Math.PI * 0.5;
  76812. // Bring the camera back up if below the ground plane
  76813. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  76814. this._betaIsAnimating = true;
  76815. //Transition to new position
  76816. this.stopAllAnimations();
  76817. if (!this._betaTransition) {
  76818. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  76819. }
  76820. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  76821. _this._clearAnimationLocks();
  76822. _this.stopAllAnimations();
  76823. });
  76824. if (animatabe) {
  76825. this._animatables.push(animatabe);
  76826. }
  76827. }
  76828. };
  76829. /**
  76830. * Returns the frustum slope based on the canvas ratio and camera FOV
  76831. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  76832. */
  76833. FramingBehavior.prototype._getFrustumSlope = function () {
  76834. // Calculate the viewport ratio
  76835. // Aspect Ratio is Height/Width.
  76836. var camera = this._attachedCamera;
  76837. if (!camera) {
  76838. return BABYLON.Vector2.Zero();
  76839. }
  76840. var engine = camera.getScene().getEngine();
  76841. var aspectRatio = engine.getAspectRatio(camera);
  76842. // Camera FOV is the vertical field of view (top-bottom) in radians.
  76843. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  76844. var frustumSlopeY = Math.tan(camera.fov / 2);
  76845. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  76846. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  76847. // along the forward vector.
  76848. var frustumSlopeX = frustumSlopeY * aspectRatio;
  76849. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  76850. };
  76851. /**
  76852. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  76853. */
  76854. FramingBehavior.prototype._clearAnimationLocks = function () {
  76855. this._betaIsAnimating = false;
  76856. };
  76857. /**
  76858. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  76859. */
  76860. FramingBehavior.prototype._applyUserInteraction = function () {
  76861. if (this.isUserIsMoving) {
  76862. this._lastInteractionTime = BABYLON.Tools.Now;
  76863. this.stopAllAnimations();
  76864. this._clearAnimationLocks();
  76865. }
  76866. };
  76867. /**
  76868. * Stops and removes all animations that have been applied to the camera
  76869. */
  76870. FramingBehavior.prototype.stopAllAnimations = function () {
  76871. if (this._attachedCamera) {
  76872. this._attachedCamera.animations = [];
  76873. }
  76874. while (this._animatables.length) {
  76875. if (this._animatables[0]) {
  76876. this._animatables[0].onAnimationEnd = null;
  76877. this._animatables[0].stop();
  76878. }
  76879. this._animatables.shift();
  76880. }
  76881. };
  76882. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  76883. /**
  76884. * Gets a value indicating if the user is moving the camera
  76885. */
  76886. get: function () {
  76887. if (!this._attachedCamera) {
  76888. return false;
  76889. }
  76890. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  76891. this._attachedCamera.inertialBetaOffset !== 0 ||
  76892. this._attachedCamera.inertialRadiusOffset !== 0 ||
  76893. this._attachedCamera.inertialPanningX !== 0 ||
  76894. this._attachedCamera.inertialPanningY !== 0 ||
  76895. this._isPointerDown;
  76896. },
  76897. enumerable: true,
  76898. configurable: true
  76899. });
  76900. /**
  76901. * The easing function used by animations
  76902. */
  76903. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  76904. /**
  76905. * The easing mode used by animations
  76906. */
  76907. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  76908. // Statics
  76909. /**
  76910. * The camera can move all the way towards the mesh.
  76911. */
  76912. FramingBehavior.IgnoreBoundsSizeMode = 0;
  76913. /**
  76914. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  76915. */
  76916. FramingBehavior.FitFrustumSidesMode = 1;
  76917. return FramingBehavior;
  76918. }());
  76919. BABYLON.FramingBehavior = FramingBehavior;
  76920. })(BABYLON || (BABYLON = {}));
  76921. //# sourceMappingURL=babylon.framingBehavior.js.map
  76922. var BABYLON;
  76923. (function (BABYLON) {
  76924. /**
  76925. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  76926. */
  76927. var BouncingBehavior = /** @class */ (function () {
  76928. function BouncingBehavior() {
  76929. /**
  76930. * The duration of the animation, in milliseconds
  76931. */
  76932. this.transitionDuration = 450;
  76933. /**
  76934. * Length of the distance animated by the transition when lower radius is reached
  76935. */
  76936. this.lowerRadiusTransitionRange = 2;
  76937. /**
  76938. * Length of the distance animated by the transition when upper radius is reached
  76939. */
  76940. this.upperRadiusTransitionRange = -2;
  76941. this._autoTransitionRange = false;
  76942. // Animations
  76943. this._radiusIsAnimating = false;
  76944. this._radiusBounceTransition = null;
  76945. this._animatables = new Array();
  76946. }
  76947. Object.defineProperty(BouncingBehavior.prototype, "name", {
  76948. get: function () {
  76949. return "Bouncing";
  76950. },
  76951. enumerable: true,
  76952. configurable: true
  76953. });
  76954. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  76955. /**
  76956. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76957. */
  76958. get: function () {
  76959. return this._autoTransitionRange;
  76960. },
  76961. /**
  76962. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  76963. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  76964. */
  76965. set: function (value) {
  76966. var _this = this;
  76967. if (this._autoTransitionRange === value) {
  76968. return;
  76969. }
  76970. this._autoTransitionRange = value;
  76971. var camera = this._attachedCamera;
  76972. if (!camera) {
  76973. return;
  76974. }
  76975. if (value) {
  76976. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  76977. if (!mesh) {
  76978. return;
  76979. }
  76980. mesh.computeWorldMatrix(true);
  76981. var diagonal = mesh.getBoundingInfo().diagonalLength;
  76982. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  76983. _this.upperRadiusTransitionRange = diagonal * 0.05;
  76984. });
  76985. }
  76986. else if (this._onMeshTargetChangedObserver) {
  76987. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  76988. }
  76989. },
  76990. enumerable: true,
  76991. configurable: true
  76992. });
  76993. BouncingBehavior.prototype.init = function () {
  76994. // Do notihng
  76995. };
  76996. BouncingBehavior.prototype.attach = function (camera) {
  76997. var _this = this;
  76998. this._attachedCamera = camera;
  76999. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77000. if (!_this._attachedCamera) {
  77001. return;
  77002. }
  77003. // Add the bounce animation to the lower radius limit
  77004. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  77005. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  77006. }
  77007. // Add the bounce animation to the upper radius limit
  77008. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  77009. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  77010. }
  77011. });
  77012. };
  77013. BouncingBehavior.prototype.detach = function () {
  77014. if (!this._attachedCamera) {
  77015. return;
  77016. }
  77017. if (this._onAfterCheckInputsObserver) {
  77018. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77019. }
  77020. if (this._onMeshTargetChangedObserver) {
  77021. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77022. }
  77023. this._attachedCamera = null;
  77024. };
  77025. /**
  77026. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  77027. * @param radiusLimit The limit to check against.
  77028. * @return Bool to indicate if at limit.
  77029. */
  77030. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  77031. if (!this._attachedCamera) {
  77032. return false;
  77033. }
  77034. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  77035. return true;
  77036. }
  77037. return false;
  77038. };
  77039. /**
  77040. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  77041. * @param radiusDelta The delta by which to animate to. Can be negative.
  77042. */
  77043. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  77044. var _this = this;
  77045. if (!this._attachedCamera) {
  77046. return;
  77047. }
  77048. if (!this._radiusBounceTransition) {
  77049. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  77050. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  77051. }
  77052. // Prevent zoom until bounce has completed
  77053. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  77054. this._attachedCamera.wheelPrecision = Infinity;
  77055. this._attachedCamera.inertialRadiusOffset = 0;
  77056. // Animate to the radius limit
  77057. this.stopAllAnimations();
  77058. this._radiusIsAnimating = true;
  77059. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  77060. if (animatable) {
  77061. this._animatables.push(animatable);
  77062. }
  77063. };
  77064. /**
  77065. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  77066. */
  77067. BouncingBehavior.prototype._clearAnimationLocks = function () {
  77068. this._radiusIsAnimating = false;
  77069. if (this._attachedCamera) {
  77070. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  77071. }
  77072. };
  77073. /**
  77074. * Stops and removes all animations that have been applied to the camera
  77075. */
  77076. BouncingBehavior.prototype.stopAllAnimations = function () {
  77077. if (this._attachedCamera) {
  77078. this._attachedCamera.animations = [];
  77079. }
  77080. while (this._animatables.length) {
  77081. this._animatables[0].onAnimationEnd = null;
  77082. this._animatables[0].stop();
  77083. this._animatables.shift();
  77084. }
  77085. };
  77086. /**
  77087. * The easing function used by animations
  77088. */
  77089. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  77090. /**
  77091. * The easing mode used by animations
  77092. */
  77093. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  77094. return BouncingBehavior;
  77095. }());
  77096. BABYLON.BouncingBehavior = BouncingBehavior;
  77097. })(BABYLON || (BABYLON = {}));
  77098. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  77099. var BABYLON;
  77100. (function (BABYLON) {
  77101. var AutoRotationBehavior = /** @class */ (function () {
  77102. function AutoRotationBehavior() {
  77103. this._zoomStopsAnimation = false;
  77104. this._idleRotationSpeed = 0.05;
  77105. this._idleRotationWaitTime = 2000;
  77106. this._idleRotationSpinupTime = 2000;
  77107. this._isPointerDown = false;
  77108. this._lastFrameTime = null;
  77109. this._lastInteractionTime = -Infinity;
  77110. this._cameraRotationSpeed = 0;
  77111. this._lastFrameRadius = 0;
  77112. }
  77113. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  77114. get: function () {
  77115. return "AutoRotation";
  77116. },
  77117. enumerable: true,
  77118. configurable: true
  77119. });
  77120. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  77121. /**
  77122. * Gets the flag that indicates if user zooming should stop animation.
  77123. */
  77124. get: function () {
  77125. return this._zoomStopsAnimation;
  77126. },
  77127. /**
  77128. * Sets the flag that indicates if user zooming should stop animation.
  77129. */
  77130. set: function (flag) {
  77131. this._zoomStopsAnimation = flag;
  77132. },
  77133. enumerable: true,
  77134. configurable: true
  77135. });
  77136. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  77137. /**
  77138. * Gets the default speed at which the camera rotates around the model.
  77139. */
  77140. get: function () {
  77141. return this._idleRotationSpeed;
  77142. },
  77143. /**
  77144. * Sets the default speed at which the camera rotates around the model.
  77145. */
  77146. set: function (speed) {
  77147. this._idleRotationSpeed = speed;
  77148. },
  77149. enumerable: true,
  77150. configurable: true
  77151. });
  77152. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  77153. /**
  77154. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  77155. */
  77156. get: function () {
  77157. return this._idleRotationWaitTime;
  77158. },
  77159. /**
  77160. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  77161. */
  77162. set: function (time) {
  77163. this._idleRotationWaitTime = time;
  77164. },
  77165. enumerable: true,
  77166. configurable: true
  77167. });
  77168. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  77169. /**
  77170. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77171. */
  77172. get: function () {
  77173. return this._idleRotationSpinupTime;
  77174. },
  77175. /**
  77176. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  77177. */
  77178. set: function (time) {
  77179. this._idleRotationSpinupTime = time;
  77180. },
  77181. enumerable: true,
  77182. configurable: true
  77183. });
  77184. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  77185. /**
  77186. * Gets a value indicating if the camera is currently rotating because of this behavior
  77187. */
  77188. get: function () {
  77189. return Math.abs(this._cameraRotationSpeed) > 0;
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. AutoRotationBehavior.prototype.init = function () {
  77195. // Do notihng
  77196. };
  77197. AutoRotationBehavior.prototype.attach = function (camera) {
  77198. var _this = this;
  77199. this._attachedCamera = camera;
  77200. var scene = this._attachedCamera.getScene();
  77201. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77202. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77203. _this._isPointerDown = true;
  77204. return;
  77205. }
  77206. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77207. _this._isPointerDown = false;
  77208. }
  77209. });
  77210. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77211. var now = BABYLON.Tools.Now;
  77212. var dt = 0;
  77213. if (_this._lastFrameTime != null) {
  77214. dt = now - _this._lastFrameTime;
  77215. }
  77216. _this._lastFrameTime = now;
  77217. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77218. _this._applyUserInteraction();
  77219. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  77220. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  77221. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  77222. // Step camera rotation by rotation speed
  77223. if (_this._attachedCamera) {
  77224. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  77225. }
  77226. });
  77227. };
  77228. AutoRotationBehavior.prototype.detach = function () {
  77229. if (!this._attachedCamera) {
  77230. return;
  77231. }
  77232. var scene = this._attachedCamera.getScene();
  77233. if (this._onPrePointerObservableObserver) {
  77234. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77235. }
  77236. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77237. this._attachedCamera = null;
  77238. };
  77239. /**
  77240. * Returns true if user is scrolling.
  77241. * @return true if user is scrolling.
  77242. */
  77243. AutoRotationBehavior.prototype._userIsZooming = function () {
  77244. if (!this._attachedCamera) {
  77245. return false;
  77246. }
  77247. return this._attachedCamera.inertialRadiusOffset !== 0;
  77248. };
  77249. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  77250. if (!this._attachedCamera) {
  77251. return false;
  77252. }
  77253. var zoomHasHitLimit = false;
  77254. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  77255. zoomHasHitLimit = true;
  77256. }
  77257. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  77258. this._lastFrameRadius = this._attachedCamera.radius;
  77259. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  77260. };
  77261. /**
  77262. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77263. */
  77264. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  77265. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  77266. this._lastInteractionTime = BABYLON.Tools.Now;
  77267. }
  77268. };
  77269. // Tools
  77270. AutoRotationBehavior.prototype._userIsMoving = function () {
  77271. if (!this._attachedCamera) {
  77272. return false;
  77273. }
  77274. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77275. this._attachedCamera.inertialBetaOffset !== 0 ||
  77276. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77277. this._attachedCamera.inertialPanningX !== 0 ||
  77278. this._attachedCamera.inertialPanningY !== 0 ||
  77279. this._isPointerDown;
  77280. };
  77281. return AutoRotationBehavior;
  77282. }());
  77283. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  77284. })(BABYLON || (BABYLON = {}));
  77285. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  77286. var BABYLON;
  77287. (function (BABYLON) {
  77288. /**
  77289. * This class can be used to get instrumentation data from a Babylon engine
  77290. */
  77291. var EngineInstrumentation = /** @class */ (function () {
  77292. function EngineInstrumentation(engine) {
  77293. this.engine = engine;
  77294. this._captureGPUFrameTime = false;
  77295. this._gpuFrameTime = new BABYLON.PerfCounter();
  77296. this._captureShaderCompilationTime = false;
  77297. this._shaderCompilationTime = new BABYLON.PerfCounter();
  77298. // Observers
  77299. this._onBeginFrameObserver = null;
  77300. this._onEndFrameObserver = null;
  77301. this._onBeforeShaderCompilationObserver = null;
  77302. this._onAfterShaderCompilationObserver = null;
  77303. }
  77304. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  77305. // Properties
  77306. /**
  77307. * Gets the perf counter used for GPU frame time
  77308. */
  77309. get: function () {
  77310. return this._gpuFrameTime;
  77311. },
  77312. enumerable: true,
  77313. configurable: true
  77314. });
  77315. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  77316. /**
  77317. * Gets the GPU frame time capture status
  77318. */
  77319. get: function () {
  77320. return this._captureGPUFrameTime;
  77321. },
  77322. /**
  77323. * Enable or disable the GPU frame time capture
  77324. */
  77325. set: function (value) {
  77326. var _this = this;
  77327. if (value === this._captureGPUFrameTime) {
  77328. return;
  77329. }
  77330. this._captureGPUFrameTime = value;
  77331. if (value) {
  77332. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  77333. if (!_this._gpuFrameTimeToken) {
  77334. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  77335. }
  77336. });
  77337. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  77338. if (!_this._gpuFrameTimeToken) {
  77339. return;
  77340. }
  77341. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  77342. if (time > -1) {
  77343. _this._gpuFrameTimeToken = null;
  77344. _this._gpuFrameTime.fetchNewFrame();
  77345. _this._gpuFrameTime.addCount(time, true);
  77346. }
  77347. });
  77348. }
  77349. else {
  77350. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77351. this._onBeginFrameObserver = null;
  77352. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77353. this._onEndFrameObserver = null;
  77354. }
  77355. },
  77356. enumerable: true,
  77357. configurable: true
  77358. });
  77359. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  77360. /**
  77361. * Gets the perf counter used for shader compilation time
  77362. */
  77363. get: function () {
  77364. return this._shaderCompilationTime;
  77365. },
  77366. enumerable: true,
  77367. configurable: true
  77368. });
  77369. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  77370. /**
  77371. * Gets the shader compilation time capture status
  77372. */
  77373. get: function () {
  77374. return this._captureShaderCompilationTime;
  77375. },
  77376. /**
  77377. * Enable or disable the shader compilation time capture
  77378. */
  77379. set: function (value) {
  77380. var _this = this;
  77381. if (value === this._captureShaderCompilationTime) {
  77382. return;
  77383. }
  77384. this._captureShaderCompilationTime = value;
  77385. if (value) {
  77386. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  77387. _this._shaderCompilationTime.fetchNewFrame();
  77388. _this._shaderCompilationTime.beginMonitoring();
  77389. });
  77390. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  77391. _this._shaderCompilationTime.endMonitoring();
  77392. });
  77393. }
  77394. else {
  77395. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77396. this._onBeforeShaderCompilationObserver = null;
  77397. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77398. this._onAfterShaderCompilationObserver = null;
  77399. }
  77400. },
  77401. enumerable: true,
  77402. configurable: true
  77403. });
  77404. EngineInstrumentation.prototype.dispose = function () {
  77405. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  77406. this._onBeginFrameObserver = null;
  77407. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  77408. this._onEndFrameObserver = null;
  77409. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  77410. this._onBeforeShaderCompilationObserver = null;
  77411. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  77412. this._onAfterShaderCompilationObserver = null;
  77413. this.engine = null;
  77414. };
  77415. return EngineInstrumentation;
  77416. }());
  77417. BABYLON.EngineInstrumentation = EngineInstrumentation;
  77418. })(BABYLON || (BABYLON = {}));
  77419. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  77420. var BABYLON;
  77421. (function (BABYLON) {
  77422. /**
  77423. * This class can be used to get instrumentation data from a Babylon engine
  77424. */
  77425. var SceneInstrumentation = /** @class */ (function () {
  77426. function SceneInstrumentation(scene) {
  77427. var _this = this;
  77428. this.scene = scene;
  77429. this._captureActiveMeshesEvaluationTime = false;
  77430. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  77431. this._captureRenderTargetsRenderTime = false;
  77432. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  77433. this._captureFrameTime = false;
  77434. this._frameTime = new BABYLON.PerfCounter();
  77435. this._captureRenderTime = false;
  77436. this._renderTime = new BABYLON.PerfCounter();
  77437. this._captureInterFrameTime = false;
  77438. this._interFrameTime = new BABYLON.PerfCounter();
  77439. this._captureParticlesRenderTime = false;
  77440. this._particlesRenderTime = new BABYLON.PerfCounter();
  77441. this._captureSpritesRenderTime = false;
  77442. this._spritesRenderTime = new BABYLON.PerfCounter();
  77443. this._capturePhysicsTime = false;
  77444. this._physicsTime = new BABYLON.PerfCounter();
  77445. this._captureAnimationsTime = false;
  77446. this._animationsTime = new BABYLON.PerfCounter();
  77447. // Observers
  77448. this._onBeforeActiveMeshesEvaluationObserver = null;
  77449. this._onAfterActiveMeshesEvaluationObserver = null;
  77450. this._onBeforeRenderTargetsRenderObserver = null;
  77451. this._onAfterRenderTargetsRenderObserver = null;
  77452. this._onAfterRenderObserver = null;
  77453. this._onBeforeDrawPhaseObserver = null;
  77454. this._onAfterDrawPhaseObserver = null;
  77455. this._onBeforeAnimationsObserver = null;
  77456. this._onBeforeParticlesRenderingObserver = null;
  77457. this._onAfterParticlesRenderingObserver = null;
  77458. this._onBeforeSpritesRenderingObserver = null;
  77459. this._onAfterSpritesRenderingObserver = null;
  77460. this._onBeforePhysicsObserver = null;
  77461. this._onAfterPhysicsObserver = null;
  77462. this._onAfterAnimationsObserver = null;
  77463. // Before render
  77464. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  77465. if (_this._captureActiveMeshesEvaluationTime) {
  77466. _this._activeMeshesEvaluationTime.fetchNewFrame();
  77467. }
  77468. if (_this._captureRenderTargetsRenderTime) {
  77469. _this._renderTargetsRenderTime.fetchNewFrame();
  77470. }
  77471. if (_this._captureFrameTime) {
  77472. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  77473. _this._frameTime.beginMonitoring();
  77474. }
  77475. if (_this._captureInterFrameTime) {
  77476. _this._interFrameTime.endMonitoring();
  77477. }
  77478. if (_this._captureParticlesRenderTime) {
  77479. _this._particlesRenderTime.fetchNewFrame();
  77480. }
  77481. if (_this._captureSpritesRenderTime) {
  77482. _this._spritesRenderTime.fetchNewFrame();
  77483. }
  77484. if (_this._captureAnimationsTime) {
  77485. _this._animationsTime.beginMonitoring();
  77486. }
  77487. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  77488. });
  77489. // After render
  77490. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  77491. if (_this._captureFrameTime) {
  77492. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  77493. _this._frameTime.endMonitoring();
  77494. }
  77495. if (_this._captureRenderTime) {
  77496. _this._renderTime.endMonitoring(false);
  77497. }
  77498. if (_this._captureInterFrameTime) {
  77499. _this._interFrameTime.beginMonitoring();
  77500. }
  77501. });
  77502. }
  77503. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  77504. // Properties
  77505. /**
  77506. * Gets the perf counter used for active meshes evaluation time
  77507. */
  77508. get: function () {
  77509. return this._activeMeshesEvaluationTime;
  77510. },
  77511. enumerable: true,
  77512. configurable: true
  77513. });
  77514. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  77515. /**
  77516. * Gets the active meshes evaluation time capture status
  77517. */
  77518. get: function () {
  77519. return this._captureActiveMeshesEvaluationTime;
  77520. },
  77521. /**
  77522. * Enable or disable the active meshes evaluation time capture
  77523. */
  77524. set: function (value) {
  77525. var _this = this;
  77526. if (value === this._captureActiveMeshesEvaluationTime) {
  77527. return;
  77528. }
  77529. this._captureActiveMeshesEvaluationTime = value;
  77530. if (value) {
  77531. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  77532. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  77533. _this._activeMeshesEvaluationTime.beginMonitoring();
  77534. });
  77535. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  77536. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  77537. _this._activeMeshesEvaluationTime.endMonitoring();
  77538. });
  77539. }
  77540. else {
  77541. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  77542. this._onBeforeActiveMeshesEvaluationObserver = null;
  77543. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  77544. this._onAfterActiveMeshesEvaluationObserver = null;
  77545. }
  77546. },
  77547. enumerable: true,
  77548. configurable: true
  77549. });
  77550. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  77551. /**
  77552. * Gets the perf counter used for render targets render time
  77553. */
  77554. get: function () {
  77555. return this._renderTargetsRenderTime;
  77556. },
  77557. enumerable: true,
  77558. configurable: true
  77559. });
  77560. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  77561. /**
  77562. * Gets the render targets render time capture status
  77563. */
  77564. get: function () {
  77565. return this._captureRenderTargetsRenderTime;
  77566. },
  77567. /**
  77568. * Enable or disable the render targets render time capture
  77569. */
  77570. set: function (value) {
  77571. var _this = this;
  77572. if (value === this._captureRenderTargetsRenderTime) {
  77573. return;
  77574. }
  77575. this._captureRenderTargetsRenderTime = value;
  77576. if (value) {
  77577. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  77578. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  77579. _this._renderTargetsRenderTime.beginMonitoring();
  77580. });
  77581. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  77582. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  77583. _this._renderTargetsRenderTime.endMonitoring(false);
  77584. });
  77585. }
  77586. else {
  77587. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  77588. this._onBeforeRenderTargetsRenderObserver = null;
  77589. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  77590. this._onAfterRenderTargetsRenderObserver = null;
  77591. }
  77592. },
  77593. enumerable: true,
  77594. configurable: true
  77595. });
  77596. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  77597. /**
  77598. * Gets the perf counter used for particles render time
  77599. */
  77600. get: function () {
  77601. return this._particlesRenderTime;
  77602. },
  77603. enumerable: true,
  77604. configurable: true
  77605. });
  77606. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  77607. /**
  77608. * Gets the particles render time capture status
  77609. */
  77610. get: function () {
  77611. return this._captureParticlesRenderTime;
  77612. },
  77613. /**
  77614. * Enable or disable the particles render time capture
  77615. */
  77616. set: function (value) {
  77617. var _this = this;
  77618. if (value === this._captureParticlesRenderTime) {
  77619. return;
  77620. }
  77621. this._captureParticlesRenderTime = value;
  77622. if (value) {
  77623. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  77624. BABYLON.Tools.StartPerformanceCounter("Particles");
  77625. _this._particlesRenderTime.beginMonitoring();
  77626. });
  77627. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  77628. BABYLON.Tools.EndPerformanceCounter("Particles");
  77629. _this._particlesRenderTime.endMonitoring(false);
  77630. });
  77631. }
  77632. else {
  77633. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77634. this._onBeforeParticlesRenderingObserver = null;
  77635. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77636. this._onAfterParticlesRenderingObserver = null;
  77637. }
  77638. },
  77639. enumerable: true,
  77640. configurable: true
  77641. });
  77642. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  77643. /**
  77644. * Gets the perf counter used for sprites render time
  77645. */
  77646. get: function () {
  77647. return this._spritesRenderTime;
  77648. },
  77649. enumerable: true,
  77650. configurable: true
  77651. });
  77652. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  77653. /**
  77654. * Gets the sprites render time capture status
  77655. */
  77656. get: function () {
  77657. return this._captureSpritesRenderTime;
  77658. },
  77659. /**
  77660. * Enable or disable the sprites render time capture
  77661. */
  77662. set: function (value) {
  77663. var _this = this;
  77664. if (value === this._captureSpritesRenderTime) {
  77665. return;
  77666. }
  77667. this._captureSpritesRenderTime = value;
  77668. if (value) {
  77669. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  77670. BABYLON.Tools.StartPerformanceCounter("Sprites");
  77671. _this._spritesRenderTime.beginMonitoring();
  77672. });
  77673. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  77674. BABYLON.Tools.EndPerformanceCounter("Sprites");
  77675. _this._spritesRenderTime.endMonitoring(false);
  77676. });
  77677. }
  77678. else {
  77679. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77680. this._onBeforeSpritesRenderingObserver = null;
  77681. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77682. this._onAfterSpritesRenderingObserver = null;
  77683. }
  77684. },
  77685. enumerable: true,
  77686. configurable: true
  77687. });
  77688. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  77689. /**
  77690. * Gets the perf counter used for physics time
  77691. */
  77692. get: function () {
  77693. return this._physicsTime;
  77694. },
  77695. enumerable: true,
  77696. configurable: true
  77697. });
  77698. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  77699. /**
  77700. * Gets the physics time capture status
  77701. */
  77702. get: function () {
  77703. return this._capturePhysicsTime;
  77704. },
  77705. /**
  77706. * Enable or disable the physics time capture
  77707. */
  77708. set: function (value) {
  77709. var _this = this;
  77710. if (value === this._capturePhysicsTime) {
  77711. return;
  77712. }
  77713. this._capturePhysicsTime = value;
  77714. if (value) {
  77715. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  77716. BABYLON.Tools.StartPerformanceCounter("Physics");
  77717. _this._physicsTime.beginMonitoring();
  77718. });
  77719. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  77720. BABYLON.Tools.EndPerformanceCounter("Physics");
  77721. _this._physicsTime.endMonitoring();
  77722. });
  77723. }
  77724. else {
  77725. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77726. this._onBeforePhysicsObserver = null;
  77727. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77728. this._onAfterPhysicsObserver = null;
  77729. }
  77730. },
  77731. enumerable: true,
  77732. configurable: true
  77733. });
  77734. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  77735. /**
  77736. * Gets the perf counter used for animations time
  77737. */
  77738. get: function () {
  77739. return this._animationsTime;
  77740. },
  77741. enumerable: true,
  77742. configurable: true
  77743. });
  77744. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  77745. /**
  77746. * Gets the animations time capture status
  77747. */
  77748. get: function () {
  77749. return this._captureAnimationsTime;
  77750. },
  77751. /**
  77752. * Enable or disable the animations time capture
  77753. */
  77754. set: function (value) {
  77755. var _this = this;
  77756. if (value === this._captureAnimationsTime) {
  77757. return;
  77758. }
  77759. this._captureAnimationsTime = value;
  77760. if (value) {
  77761. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  77762. _this._animationsTime.endMonitoring();
  77763. });
  77764. }
  77765. else {
  77766. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77767. this._onAfterAnimationsObserver = null;
  77768. }
  77769. },
  77770. enumerable: true,
  77771. configurable: true
  77772. });
  77773. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  77774. /**
  77775. * Gets the perf counter used for frame time capture
  77776. */
  77777. get: function () {
  77778. return this._frameTime;
  77779. },
  77780. enumerable: true,
  77781. configurable: true
  77782. });
  77783. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  77784. /**
  77785. * Gets the frame time capture status
  77786. */
  77787. get: function () {
  77788. return this._captureFrameTime;
  77789. },
  77790. /**
  77791. * Enable or disable the frame time capture
  77792. */
  77793. set: function (value) {
  77794. this._captureFrameTime = value;
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  77800. /**
  77801. * Gets the perf counter used for inter-frames time capture
  77802. */
  77803. get: function () {
  77804. return this._interFrameTime;
  77805. },
  77806. enumerable: true,
  77807. configurable: true
  77808. });
  77809. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  77810. /**
  77811. * Gets the inter-frames time capture status
  77812. */
  77813. get: function () {
  77814. return this._captureInterFrameTime;
  77815. },
  77816. /**
  77817. * Enable or disable the inter-frames time capture
  77818. */
  77819. set: function (value) {
  77820. this._captureInterFrameTime = value;
  77821. },
  77822. enumerable: true,
  77823. configurable: true
  77824. });
  77825. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  77826. /**
  77827. * Gets the perf counter used for render time capture
  77828. */
  77829. get: function () {
  77830. return this._renderTime;
  77831. },
  77832. enumerable: true,
  77833. configurable: true
  77834. });
  77835. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  77836. /**
  77837. * Gets the render time capture status
  77838. */
  77839. get: function () {
  77840. return this._captureRenderTime;
  77841. },
  77842. /**
  77843. * Enable or disable the render time capture
  77844. */
  77845. set: function (value) {
  77846. var _this = this;
  77847. if (value === this._captureRenderTime) {
  77848. return;
  77849. }
  77850. this._captureRenderTime = value;
  77851. if (value) {
  77852. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  77853. _this._renderTime.beginMonitoring();
  77854. BABYLON.Tools.StartPerformanceCounter("Main render");
  77855. });
  77856. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  77857. _this._renderTime.endMonitoring(false);
  77858. BABYLON.Tools.EndPerformanceCounter("Main render");
  77859. });
  77860. }
  77861. else {
  77862. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77863. this._onBeforeDrawPhaseObserver = null;
  77864. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77865. this._onAfterDrawPhaseObserver = null;
  77866. }
  77867. },
  77868. enumerable: true,
  77869. configurable: true
  77870. });
  77871. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  77872. /**
  77873. * Gets the perf counter used for frame time capture
  77874. */
  77875. get: function () {
  77876. return this.scene.getEngine()._drawCalls;
  77877. },
  77878. enumerable: true,
  77879. configurable: true
  77880. });
  77881. SceneInstrumentation.prototype.dispose = function () {
  77882. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  77883. this._onAfterRenderObserver = null;
  77884. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  77885. this._onBeforeActiveMeshesEvaluationObserver = null;
  77886. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  77887. this._onAfterActiveMeshesEvaluationObserver = null;
  77888. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  77889. this._onBeforeRenderTargetsRenderObserver = null;
  77890. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  77891. this._onAfterRenderTargetsRenderObserver = null;
  77892. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  77893. this._onBeforeAnimationsObserver = null;
  77894. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  77895. this._onBeforeParticlesRenderingObserver = null;
  77896. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  77897. this._onAfterParticlesRenderingObserver = null;
  77898. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  77899. this._onBeforeSpritesRenderingObserver = null;
  77900. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  77901. this._onAfterSpritesRenderingObserver = null;
  77902. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  77903. this._onBeforeDrawPhaseObserver = null;
  77904. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  77905. this._onAfterDrawPhaseObserver = null;
  77906. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  77907. this._onBeforePhysicsObserver = null;
  77908. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  77909. this._onAfterPhysicsObserver = null;
  77910. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  77911. this._onAfterAnimationsObserver = null;
  77912. this.scene = null;
  77913. };
  77914. return SceneInstrumentation;
  77915. }());
  77916. BABYLON.SceneInstrumentation = SceneInstrumentation;
  77917. })(BABYLON || (BABYLON = {}));
  77918. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  77919. var BABYLON;
  77920. (function (BABYLON) {
  77921. var _TimeToken = /** @class */ (function () {
  77922. function _TimeToken() {
  77923. this._timeElapsedQueryEnded = false;
  77924. }
  77925. return _TimeToken;
  77926. }());
  77927. BABYLON._TimeToken = _TimeToken;
  77928. })(BABYLON || (BABYLON = {}));
  77929. //# sourceMappingURL=babylon.timeToken.js.map
  77930. var BABYLON;
  77931. (function (BABYLON) {
  77932. /**
  77933. * Background material defines definition.
  77934. */
  77935. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  77936. __extends(BackgroundMaterialDefines, _super);
  77937. /**
  77938. * Constructor of the defines.
  77939. */
  77940. function BackgroundMaterialDefines() {
  77941. var _this = _super.call(this) || this;
  77942. /**
  77943. * True if the diffuse texture is in use.
  77944. */
  77945. _this.DIFFUSE = false;
  77946. /**
  77947. * The direct UV channel to use.
  77948. */
  77949. _this.DIFFUSEDIRECTUV = 0;
  77950. /**
  77951. * True if the diffuse texture is in gamma space.
  77952. */
  77953. _this.GAMMADIFFUSE = false;
  77954. /**
  77955. * True if the diffuse texture has opacity in the alpha channel.
  77956. */
  77957. _this.DIFFUSEHASALPHA = false;
  77958. /**
  77959. * True if you want the material to fade to transparent at grazing angle.
  77960. */
  77961. _this.OPACITYFRESNEL = false;
  77962. /**
  77963. * True if an extra blur needs to be added in the reflection.
  77964. */
  77965. _this.REFLECTIONBLUR = false;
  77966. /**
  77967. * True if you want the material to fade to reflection at grazing angle.
  77968. */
  77969. _this.REFLECTIONFRESNEL = false;
  77970. /**
  77971. * True if you want the material to falloff as far as you move away from the scene center.
  77972. */
  77973. _this.REFLECTIONFALLOFF = false;
  77974. /**
  77975. * False if the current Webgl implementation does not support the texture lod extension.
  77976. */
  77977. _this.TEXTURELODSUPPORT = false;
  77978. /**
  77979. * True to ensure the data are premultiplied.
  77980. */
  77981. _this.PREMULTIPLYALPHA = false;
  77982. /**
  77983. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  77984. */
  77985. _this.USERGBCOLOR = false;
  77986. /**
  77987. * True to add noise in order to reduce the banding effect.
  77988. */
  77989. _this.NOISE = false;
  77990. // Image Processing Configuration.
  77991. _this.IMAGEPROCESSING = false;
  77992. _this.VIGNETTE = false;
  77993. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  77994. _this.VIGNETTEBLENDMODEOPAQUE = false;
  77995. _this.TONEMAPPING = false;
  77996. _this.CONTRAST = false;
  77997. _this.COLORCURVES = false;
  77998. _this.COLORGRADING = false;
  77999. _this.COLORGRADING3D = false;
  78000. _this.SAMPLER3DGREENDEPTH = false;
  78001. _this.SAMPLER3DBGRMAP = false;
  78002. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  78003. _this.EXPOSURE = false;
  78004. // Reflection.
  78005. _this.REFLECTION = false;
  78006. _this.REFLECTIONMAP_3D = false;
  78007. _this.REFLECTIONMAP_SPHERICAL = false;
  78008. _this.REFLECTIONMAP_PLANAR = false;
  78009. _this.REFLECTIONMAP_CUBIC = false;
  78010. _this.REFLECTIONMAP_PROJECTION = false;
  78011. _this.REFLECTIONMAP_SKYBOX = false;
  78012. _this.REFLECTIONMAP_EXPLICIT = false;
  78013. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78014. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78015. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78016. _this.INVERTCUBICMAP = false;
  78017. _this.REFLECTIONMAP_OPPOSITEZ = false;
  78018. _this.LODINREFLECTIONALPHA = false;
  78019. _this.GAMMAREFLECTION = false;
  78020. // Default BJS.
  78021. _this.MAINUV1 = false;
  78022. _this.MAINUV2 = false;
  78023. _this.UV1 = false;
  78024. _this.UV2 = false;
  78025. _this.CLIPPLANE = false;
  78026. _this.POINTSIZE = false;
  78027. _this.FOG = false;
  78028. _this.NORMAL = false;
  78029. _this.NUM_BONE_INFLUENCERS = 0;
  78030. _this.BonesPerMesh = 0;
  78031. _this.INSTANCES = false;
  78032. _this.SHADOWFLOAT = false;
  78033. _this.rebuild();
  78034. return _this;
  78035. }
  78036. return BackgroundMaterialDefines;
  78037. }(BABYLON.MaterialDefines));
  78038. /**
  78039. * Background material used to create an efficient environement around your scene.
  78040. */
  78041. var BackgroundMaterial = /** @class */ (function (_super) {
  78042. __extends(BackgroundMaterial, _super);
  78043. /**
  78044. * constructor
  78045. * @param name The name of the material
  78046. * @param scene The scene to add the material to
  78047. */
  78048. function BackgroundMaterial(name, scene) {
  78049. var _this = _super.call(this, name, scene) || this;
  78050. _this.primaryColor = BABYLON.Color3.White();
  78051. _this.primaryLevel = 1;
  78052. _this.secondaryColor = BABYLON.Color3.Gray();
  78053. _this.secondaryLevel = 1;
  78054. _this.tertiaryColor = BABYLON.Color3.Black();
  78055. _this.tertiaryLevel = 1;
  78056. _this.reflectionTexture = null;
  78057. _this.reflectionBlur = 0;
  78058. _this.diffuseTexture = null;
  78059. /**
  78060. * Specify the list of lights casting shadow on the material.
  78061. * All scene shadow lights will be included if null.
  78062. */
  78063. _this._shadowLights = null;
  78064. _this.shadowLights = null;
  78065. _this.shadowBlurScale = 1;
  78066. _this.shadowLevel = 0;
  78067. _this.sceneCenter = BABYLON.Vector3.Zero();
  78068. _this.opacityFresnel = true;
  78069. _this.reflectionFresnel = false;
  78070. _this.reflectionFalloffDistance = 0.0;
  78071. _this.reflectionAmount = 1.0;
  78072. _this.reflectionReflectance0 = 0.05;
  78073. _this.reflectionReflectance90 = 0.5;
  78074. _this.useRGBColor = true;
  78075. _this.enableNoise = false;
  78076. /**
  78077. * Number of Simultaneous lights allowed on the material.
  78078. */
  78079. _this._maxSimultaneousLights = 4;
  78080. _this.maxSimultaneousLights = 4;
  78081. /**
  78082. * Keep track of the image processing observer to allow dispose and replace.
  78083. */
  78084. _this._imageProcessingObserver = null;
  78085. // Temp values kept as cache in the material.
  78086. _this._renderTargets = new BABYLON.SmartArray(16);
  78087. _this._reflectionControls = BABYLON.Vector4.Zero();
  78088. // Setup the default processing configuration to the scene.
  78089. _this._attachImageProcessingConfiguration(null);
  78090. _this.getRenderTargetTextures = function () {
  78091. _this._renderTargets.reset();
  78092. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  78093. _this._renderTargets.push(_this._diffuseTexture);
  78094. }
  78095. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  78096. _this._renderTargets.push(_this._reflectionTexture);
  78097. }
  78098. return _this._renderTargets;
  78099. };
  78100. return _this;
  78101. }
  78102. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  78103. /**
  78104. * Sets the reflection reflectance fresnel values according to the default standard
  78105. * empirically know to work well :-)
  78106. */
  78107. set: function (value) {
  78108. var reflectionWeight = value;
  78109. if (reflectionWeight < 0.5) {
  78110. reflectionWeight = reflectionWeight * 2.0;
  78111. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  78112. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  78113. }
  78114. else {
  78115. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  78116. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  78117. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  78118. }
  78119. },
  78120. enumerable: true,
  78121. configurable: true
  78122. });
  78123. /**
  78124. * Attaches a new image processing configuration to the PBR Material.
  78125. * @param configuration (if null the scene configuration will be use)
  78126. */
  78127. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  78128. var _this = this;
  78129. if (configuration === this._imageProcessingConfiguration) {
  78130. return;
  78131. }
  78132. // Detaches observer.
  78133. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78134. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78135. }
  78136. // Pick the scene configuration if needed.
  78137. if (!configuration) {
  78138. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  78139. }
  78140. else {
  78141. this._imageProcessingConfiguration = configuration;
  78142. }
  78143. // Attaches observer.
  78144. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78145. _this._markAllSubMeshesAsImageProcessingDirty();
  78146. });
  78147. };
  78148. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  78149. /**
  78150. * Gets the image processing configuration used either in this material.
  78151. */
  78152. get: function () {
  78153. return this._imageProcessingConfiguration;
  78154. },
  78155. /**
  78156. * Sets the Default image processing configuration used either in the this material.
  78157. *
  78158. * If sets to null, the scene one is in use.
  78159. */
  78160. set: function (value) {
  78161. this._attachImageProcessingConfiguration(value);
  78162. // Ensure the effect will be rebuilt.
  78163. this._markAllSubMeshesAsTexturesDirty();
  78164. },
  78165. enumerable: true,
  78166. configurable: true
  78167. });
  78168. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  78169. /**
  78170. * Gets wether the color curves effect is enabled.
  78171. */
  78172. get: function () {
  78173. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78174. },
  78175. /**
  78176. * Sets wether the color curves effect is enabled.
  78177. */
  78178. set: function (value) {
  78179. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78180. },
  78181. enumerable: true,
  78182. configurable: true
  78183. });
  78184. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  78185. /**
  78186. * Gets wether the color grading effect is enabled.
  78187. */
  78188. get: function () {
  78189. return this.imageProcessingConfiguration.colorGradingEnabled;
  78190. },
  78191. /**
  78192. * Gets wether the color grading effect is enabled.
  78193. */
  78194. set: function (value) {
  78195. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78196. },
  78197. enumerable: true,
  78198. configurable: true
  78199. });
  78200. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  78201. /**
  78202. * Gets wether tonemapping is enabled or not.
  78203. */
  78204. get: function () {
  78205. return this._imageProcessingConfiguration.toneMappingEnabled;
  78206. },
  78207. /**
  78208. * Sets wether tonemapping is enabled or not
  78209. */
  78210. set: function (value) {
  78211. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78212. },
  78213. enumerable: true,
  78214. configurable: true
  78215. });
  78216. ;
  78217. ;
  78218. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  78219. /**
  78220. * The camera exposure used on this material.
  78221. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78222. * This corresponds to a photographic exposure.
  78223. */
  78224. get: function () {
  78225. return this._imageProcessingConfiguration.exposure;
  78226. },
  78227. /**
  78228. * The camera exposure used on this material.
  78229. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  78230. * This corresponds to a photographic exposure.
  78231. */
  78232. set: function (value) {
  78233. this._imageProcessingConfiguration.exposure = value;
  78234. },
  78235. enumerable: true,
  78236. configurable: true
  78237. });
  78238. ;
  78239. ;
  78240. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  78241. /**
  78242. * Gets The camera contrast used on this material.
  78243. */
  78244. get: function () {
  78245. return this._imageProcessingConfiguration.contrast;
  78246. },
  78247. /**
  78248. * Sets The camera contrast used on this material.
  78249. */
  78250. set: function (value) {
  78251. this._imageProcessingConfiguration.contrast = value;
  78252. },
  78253. enumerable: true,
  78254. configurable: true
  78255. });
  78256. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  78257. /**
  78258. * Gets the Color Grading 2D Lookup Texture.
  78259. */
  78260. get: function () {
  78261. return this._imageProcessingConfiguration.colorGradingTexture;
  78262. },
  78263. /**
  78264. * Sets the Color Grading 2D Lookup Texture.
  78265. */
  78266. set: function (value) {
  78267. this.imageProcessingConfiguration.colorGradingTexture = value;
  78268. },
  78269. enumerable: true,
  78270. configurable: true
  78271. });
  78272. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  78273. /**
  78274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78276. * 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;
  78277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78278. */
  78279. get: function () {
  78280. return this.imageProcessingConfiguration.colorCurves;
  78281. },
  78282. /**
  78283. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78284. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78285. * 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;
  78286. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78287. */
  78288. set: function (value) {
  78289. this.imageProcessingConfiguration.colorCurves = value;
  78290. },
  78291. enumerable: true,
  78292. configurable: true
  78293. });
  78294. /**
  78295. * The entire material has been created in order to prevent overdraw.
  78296. * @returns false
  78297. */
  78298. BackgroundMaterial.prototype.needAlphaTesting = function () {
  78299. return true;
  78300. };
  78301. /**
  78302. * The entire material has been created in order to prevent overdraw.
  78303. * @returns true if blending is enable
  78304. */
  78305. BackgroundMaterial.prototype.needAlphaBlending = function () {
  78306. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  78307. };
  78308. /**
  78309. * Checks wether the material is ready to be rendered for a given mesh.
  78310. * @param mesh The mesh to render
  78311. * @param subMesh The submesh to check against
  78312. * @param useInstances Specify wether or not the material is used with instances
  78313. */
  78314. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78315. var _this = this;
  78316. if (useInstances === void 0) { useInstances = false; }
  78317. if (subMesh.effect && this.isFrozen) {
  78318. if (this._wasPreviouslyReady) {
  78319. return true;
  78320. }
  78321. }
  78322. if (!subMesh._materialDefines) {
  78323. subMesh._materialDefines = new BackgroundMaterialDefines();
  78324. }
  78325. var scene = this.getScene();
  78326. var defines = subMesh._materialDefines;
  78327. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  78328. if (defines._renderId === scene.getRenderId()) {
  78329. return true;
  78330. }
  78331. }
  78332. var engine = scene.getEngine();
  78333. // Lights
  78334. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  78335. defines._needNormals = true;
  78336. // Textures
  78337. if (defines._areTexturesDirty) {
  78338. defines._needUVs = false;
  78339. if (scene.texturesEnabled) {
  78340. if (scene.getEngine().getCaps().textureLOD) {
  78341. defines.TEXTURELODSUPPORT = true;
  78342. }
  78343. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78344. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  78345. return false;
  78346. }
  78347. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  78348. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  78349. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  78350. defines.OPACITYFRESNEL = this._opacityFresnel;
  78351. }
  78352. else {
  78353. defines.DIFFUSE = false;
  78354. defines.DIFFUSEHASALPHA = false;
  78355. defines.GAMMADIFFUSE = false;
  78356. defines.OPACITYFRESNEL = false;
  78357. }
  78358. var reflectionTexture = this._reflectionTexture;
  78359. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78360. if (!reflectionTexture.isReadyOrNotBlocking()) {
  78361. return false;
  78362. }
  78363. defines.REFLECTION = true;
  78364. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  78365. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  78366. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  78367. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  78368. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  78369. defines.INVERTCUBICMAP = true;
  78370. }
  78371. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  78372. switch (reflectionTexture.coordinatesMode) {
  78373. case BABYLON.Texture.CUBIC_MODE:
  78374. case BABYLON.Texture.INVCUBIC_MODE:
  78375. defines.REFLECTIONMAP_CUBIC = true;
  78376. break;
  78377. case BABYLON.Texture.EXPLICIT_MODE:
  78378. defines.REFLECTIONMAP_EXPLICIT = true;
  78379. break;
  78380. case BABYLON.Texture.PLANAR_MODE:
  78381. defines.REFLECTIONMAP_PLANAR = true;
  78382. break;
  78383. case BABYLON.Texture.PROJECTION_MODE:
  78384. defines.REFLECTIONMAP_PROJECTION = true;
  78385. break;
  78386. case BABYLON.Texture.SKYBOX_MODE:
  78387. defines.REFLECTIONMAP_SKYBOX = true;
  78388. break;
  78389. case BABYLON.Texture.SPHERICAL_MODE:
  78390. defines.REFLECTIONMAP_SPHERICAL = true;
  78391. break;
  78392. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  78393. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  78394. break;
  78395. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  78396. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  78397. break;
  78398. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  78399. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  78400. break;
  78401. }
  78402. if (this.reflectionFresnel) {
  78403. defines.REFLECTIONFRESNEL = true;
  78404. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  78405. this._reflectionControls.x = this.reflectionAmount;
  78406. this._reflectionControls.y = this.reflectionReflectance0;
  78407. this._reflectionControls.z = this.reflectionReflectance90;
  78408. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  78409. }
  78410. else {
  78411. defines.REFLECTIONFRESNEL = false;
  78412. defines.REFLECTIONFALLOFF = false;
  78413. }
  78414. }
  78415. else {
  78416. defines.REFLECTION = false;
  78417. defines.REFLECTIONFALLOFF = false;
  78418. defines.REFLECTIONBLUR = false;
  78419. defines.REFLECTIONMAP_3D = false;
  78420. defines.REFLECTIONMAP_SPHERICAL = false;
  78421. defines.REFLECTIONMAP_PLANAR = false;
  78422. defines.REFLECTIONMAP_CUBIC = false;
  78423. defines.REFLECTIONMAP_PROJECTION = false;
  78424. defines.REFLECTIONMAP_SKYBOX = false;
  78425. defines.REFLECTIONMAP_EXPLICIT = false;
  78426. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  78427. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  78428. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  78429. defines.INVERTCUBICMAP = false;
  78430. defines.REFLECTIONMAP_OPPOSITEZ = false;
  78431. defines.LODINREFLECTIONALPHA = false;
  78432. defines.GAMMAREFLECTION = false;
  78433. }
  78434. }
  78435. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  78436. defines.USERGBCOLOR = this._useRGBColor;
  78437. defines.NOISE = this._enableNoise;
  78438. }
  78439. if (defines._areImageProcessingDirty) {
  78440. if (!this._imageProcessingConfiguration.isReady()) {
  78441. return false;
  78442. }
  78443. this._imageProcessingConfiguration.prepareDefines(defines);
  78444. }
  78445. // Misc.
  78446. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  78447. // Values that need to be evaluated on every frame
  78448. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  78449. // Attribs
  78450. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  78451. if (mesh) {
  78452. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78453. mesh.createNormals(true);
  78454. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  78455. }
  78456. }
  78457. }
  78458. // Get correct effect
  78459. if (defines.isDirty) {
  78460. defines.markAsProcessed();
  78461. scene.resetCachedMaterial();
  78462. // Fallbacks
  78463. var fallbacks = new BABYLON.EffectFallbacks();
  78464. if (defines.FOG) {
  78465. fallbacks.addFallback(0, "FOG");
  78466. }
  78467. if (defines.POINTSIZE) {
  78468. fallbacks.addFallback(1, "POINTSIZE");
  78469. }
  78470. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  78471. if (defines.NUM_BONE_INFLUENCERS > 0) {
  78472. fallbacks.addCPUSkinningFallback(0, mesh);
  78473. }
  78474. //Attributes
  78475. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78476. if (defines.NORMAL) {
  78477. attribs.push(BABYLON.VertexBuffer.NormalKind);
  78478. }
  78479. if (defines.UV1) {
  78480. attribs.push(BABYLON.VertexBuffer.UVKind);
  78481. }
  78482. if (defines.UV2) {
  78483. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78484. }
  78485. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  78486. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  78487. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  78488. "vFogInfos", "vFogColor", "pointSize",
  78489. "vClipPlane", "mBones",
  78490. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  78491. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  78492. "shadowLevel", "alpha",
  78493. "vBackgroundCenter", "vReflectionControl",
  78494. "vDiffuseInfos", "diffuseMatrix",
  78495. ];
  78496. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  78497. var uniformBuffers = ["Material", "Scene"];
  78498. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  78499. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  78500. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  78501. uniformsNames: uniforms,
  78502. uniformBuffersNames: uniformBuffers,
  78503. samplers: samplers,
  78504. defines: defines,
  78505. maxSimultaneousLights: this._maxSimultaneousLights
  78506. });
  78507. var onCompiled = function (effect) {
  78508. if (_this.onCompiled) {
  78509. _this.onCompiled(effect);
  78510. }
  78511. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  78512. };
  78513. var join = defines.toString();
  78514. subMesh.setEffect(scene.getEngine().createEffect("background", {
  78515. attributes: attribs,
  78516. uniformsNames: uniforms,
  78517. uniformBuffersNames: uniformBuffers,
  78518. samplers: samplers,
  78519. defines: join,
  78520. fallbacks: fallbacks,
  78521. onCompiled: onCompiled,
  78522. onError: this.onError,
  78523. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  78524. }, engine), defines);
  78525. this.buildUniformLayout();
  78526. }
  78527. if (!subMesh.effect || !subMesh.effect.isReady()) {
  78528. return false;
  78529. }
  78530. defines._renderId = scene.getRenderId();
  78531. this._wasPreviouslyReady = true;
  78532. return true;
  78533. };
  78534. /**
  78535. * Build the uniform buffer used in the material.
  78536. */
  78537. BackgroundMaterial.prototype.buildUniformLayout = function () {
  78538. // Order is important !
  78539. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  78540. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  78541. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  78542. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  78543. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  78544. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  78545. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  78546. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  78547. this._uniformBuffer.addUniform("pointSize", 1);
  78548. this._uniformBuffer.addUniform("shadowLevel", 1);
  78549. this._uniformBuffer.addUniform("alpha", 1);
  78550. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  78551. this._uniformBuffer.addUniform("vReflectionControl", 4);
  78552. this._uniformBuffer.create();
  78553. };
  78554. /**
  78555. * Unbind the material.
  78556. */
  78557. BackgroundMaterial.prototype.unbind = function () {
  78558. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  78559. this._uniformBuffer.setTexture("diffuseSampler", null);
  78560. }
  78561. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  78562. this._uniformBuffer.setTexture("reflectionSampler", null);
  78563. }
  78564. _super.prototype.unbind.call(this);
  78565. };
  78566. /**
  78567. * Bind only the world matrix to the material.
  78568. * @param world The world matrix to bind.
  78569. */
  78570. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  78571. this._activeEffect.setMatrix("world", world);
  78572. };
  78573. /**
  78574. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  78575. * @param world The world matrix to bind.
  78576. * @param subMesh The submesh to bind for.
  78577. */
  78578. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  78579. var scene = this.getScene();
  78580. var defines = subMesh._materialDefines;
  78581. if (!defines) {
  78582. return;
  78583. }
  78584. var effect = subMesh.effect;
  78585. if (!effect) {
  78586. return;
  78587. }
  78588. this._activeEffect = effect;
  78589. // Matrices
  78590. this.bindOnlyWorldMatrix(world);
  78591. // Bones
  78592. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  78593. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  78594. if (mustRebind) {
  78595. this._uniformBuffer.bindToEffect(effect, "Material");
  78596. this.bindViewProjection(effect);
  78597. var reflectionTexture = this._reflectionTexture;
  78598. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  78599. // Texture uniforms
  78600. if (scene.texturesEnabled) {
  78601. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78602. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  78603. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  78604. }
  78605. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78606. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  78607. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  78608. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  78609. }
  78610. }
  78611. if (this.shadowLevel > 0) {
  78612. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  78613. }
  78614. this._uniformBuffer.updateFloat("alpha", this.alpha);
  78615. // Point size
  78616. if (this.pointsCloud) {
  78617. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  78618. }
  78619. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  78620. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  78621. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  78622. }
  78623. // Textures
  78624. if (scene.texturesEnabled) {
  78625. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  78626. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  78627. }
  78628. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  78629. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  78630. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  78631. }
  78632. else if (!defines.REFLECTIONBLUR) {
  78633. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  78634. }
  78635. else {
  78636. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  78637. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  78638. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  78639. }
  78640. if (defines.REFLECTIONFRESNEL) {
  78641. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  78642. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  78643. }
  78644. }
  78645. }
  78646. // Clip plane
  78647. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  78648. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  78649. }
  78650. if (mustRebind || !this.isFrozen) {
  78651. if (scene.lightsEnabled) {
  78652. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  78653. }
  78654. // View
  78655. this.bindView(effect);
  78656. // Fog
  78657. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  78658. // image processing
  78659. this._imageProcessingConfiguration.bind(this._activeEffect);
  78660. }
  78661. this._uniformBuffer.update();
  78662. this._afterBind(mesh);
  78663. };
  78664. /**
  78665. * Dispose the material.
  78666. * @forceDisposeEffect Force disposal of the associated effect.
  78667. * @forceDisposeTextures Force disposal of the associated textures.
  78668. */
  78669. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78670. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  78671. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  78672. if (forceDisposeTextures) {
  78673. if (this.diffuseTexture) {
  78674. this.diffuseTexture.dispose();
  78675. }
  78676. if (this.reflectionTexture) {
  78677. this.reflectionTexture.dispose();
  78678. }
  78679. }
  78680. this._renderTargets.dispose();
  78681. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78682. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78683. }
  78684. _super.prototype.dispose.call(this, forceDisposeEffect);
  78685. };
  78686. /**
  78687. * Clones the material.
  78688. * @name The cloned name.
  78689. * @returns The cloned material.
  78690. */
  78691. BackgroundMaterial.prototype.clone = function (name) {
  78692. var _this = this;
  78693. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  78694. };
  78695. /**
  78696. * Serializes the current material to its JSON representation.
  78697. * @returns The JSON representation.
  78698. */
  78699. BackgroundMaterial.prototype.serialize = function () {
  78700. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78701. serializationObject.customType = "BABYLON.BackgroundMaterial";
  78702. return serializationObject;
  78703. };
  78704. /**
  78705. * Gets the class name of the material
  78706. * @returns "BackgroundMaterial"
  78707. */
  78708. BackgroundMaterial.prototype.getClassName = function () {
  78709. return "BackgroundMaterial";
  78710. };
  78711. /**
  78712. * Parse a JSON input to create back a background material.
  78713. * @param source
  78714. * @param scene
  78715. * @param rootUrl
  78716. * @returns the instantiated BackgroundMaterial.
  78717. */
  78718. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  78719. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  78720. };
  78721. /**
  78722. * Standard reflectance value at parallel view angle.
  78723. */
  78724. BackgroundMaterial.standardReflectance0 = 0.05;
  78725. /**
  78726. * Standard reflectance value at grazing angle.
  78727. */
  78728. BackgroundMaterial.standardReflectance90 = 0.5;
  78729. __decorate([
  78730. BABYLON.serializeAsColor3()
  78731. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  78732. __decorate([
  78733. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78734. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  78735. __decorate([
  78736. BABYLON.serialize()
  78737. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  78738. __decorate([
  78739. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78740. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  78741. __decorate([
  78742. BABYLON.serializeAsColor3()
  78743. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  78744. __decorate([
  78745. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78746. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  78747. __decorate([
  78748. BABYLON.serialize()
  78749. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  78750. __decorate([
  78751. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78752. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  78753. __decorate([
  78754. BABYLON.serializeAsColor3()
  78755. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  78756. __decorate([
  78757. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78758. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  78759. __decorate([
  78760. BABYLON.serialize()
  78761. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  78762. __decorate([
  78763. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  78764. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  78765. __decorate([
  78766. BABYLON.serializeAsTexture()
  78767. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  78768. __decorate([
  78769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78770. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  78771. __decorate([
  78772. BABYLON.serialize()
  78773. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  78774. __decorate([
  78775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78776. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  78777. __decorate([
  78778. BABYLON.serializeAsTexture()
  78779. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  78780. __decorate([
  78781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78782. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  78783. __decorate([
  78784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78785. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  78786. __decorate([
  78787. BABYLON.serialize()
  78788. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  78789. __decorate([
  78790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78791. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  78792. __decorate([
  78793. BABYLON.serialize()
  78794. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  78795. __decorate([
  78796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78797. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  78798. __decorate([
  78799. BABYLON.serializeAsVector3()
  78800. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  78801. __decorate([
  78802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78803. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  78804. __decorate([
  78805. BABYLON.serialize()
  78806. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  78807. __decorate([
  78808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78809. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  78810. __decorate([
  78811. BABYLON.serialize()
  78812. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  78813. __decorate([
  78814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78815. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  78816. __decorate([
  78817. BABYLON.serialize()
  78818. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  78819. __decorate([
  78820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78821. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  78822. __decorate([
  78823. BABYLON.serialize()
  78824. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  78825. __decorate([
  78826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78827. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  78828. __decorate([
  78829. BABYLON.serialize()
  78830. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  78831. __decorate([
  78832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78833. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  78834. __decorate([
  78835. BABYLON.serialize()
  78836. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  78837. __decorate([
  78838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78839. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  78840. __decorate([
  78841. BABYLON.serialize()
  78842. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  78843. __decorate([
  78844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78845. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  78846. __decorate([
  78847. BABYLON.serialize()
  78848. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  78849. __decorate([
  78850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78851. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  78852. __decorate([
  78853. BABYLON.serialize()
  78854. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  78855. __decorate([
  78856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  78857. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  78858. __decorate([
  78859. BABYLON.serializeAsImageProcessingConfiguration()
  78860. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  78861. return BackgroundMaterial;
  78862. }(BABYLON.PushMaterial));
  78863. BABYLON.BackgroundMaterial = BackgroundMaterial;
  78864. })(BABYLON || (BABYLON = {}));
  78865. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  78866. var __assign = (this && this.__assign) || Object.assign || function(t) {
  78867. for (var s, i = 1, n = arguments.length; i < n; i++) {
  78868. s = arguments[i];
  78869. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  78870. t[p] = s[p];
  78871. }
  78872. return t;
  78873. };
  78874. var BABYLON;
  78875. (function (BABYLON) {
  78876. /**
  78877. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  78878. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  78879. * It also helps with the default setup of your imageProcessing configuration.
  78880. */
  78881. var EnvironmentHelper = /** @class */ (function () {
  78882. /**
  78883. * constructor
  78884. * @param options
  78885. * @param scene The scene to add the material to
  78886. */
  78887. function EnvironmentHelper(options, scene) {
  78888. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  78889. this._scene = scene;
  78890. this._setupBackground();
  78891. this._setupImageProcessing();
  78892. }
  78893. /**
  78894. * Creates the default options for the helper.
  78895. */
  78896. EnvironmentHelper._getDefaultOptions = function () {
  78897. return {
  78898. createGround: true,
  78899. groundSize: 15,
  78900. groundTexture: this._groundTextureCDNUrl,
  78901. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78902. groundOpacity: 0.9,
  78903. enableGroundShadow: true,
  78904. groundShadowLevel: 0.5,
  78905. enableGroundMirror: false,
  78906. groundMirrorSizeRatio: 0.3,
  78907. groundMirrorBlurKernel: 64,
  78908. groundMirrorAmount: 1,
  78909. groundMirrorFresnelWeight: 1,
  78910. groundMirrorFallOffDistance: 0,
  78911. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  78912. createSkybox: true,
  78913. skyboxSize: 20,
  78914. skyboxTexture: this._skyboxTextureCDNUrl,
  78915. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  78916. backgroundYRotation: 0,
  78917. sizeAuto: true,
  78918. rootPosition: BABYLON.Vector3.Zero(),
  78919. setupImageProcessing: true,
  78920. environmentTexture: this._environmentTextureCDNUrl,
  78921. cameraExposure: 0.8,
  78922. cameraContrast: 1.2,
  78923. toneMappingEnabled: true,
  78924. };
  78925. };
  78926. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  78927. /**
  78928. * Gets the root mesh created by the helper.
  78929. */
  78930. get: function () {
  78931. return this._rootMesh;
  78932. },
  78933. enumerable: true,
  78934. configurable: true
  78935. });
  78936. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  78937. /**
  78938. * Gets the skybox created by the helper.
  78939. */
  78940. get: function () {
  78941. return this._skybox;
  78942. },
  78943. enumerable: true,
  78944. configurable: true
  78945. });
  78946. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  78947. /**
  78948. * Gets the skybox texture created by the helper.
  78949. */
  78950. get: function () {
  78951. return this._skyboxTexture;
  78952. },
  78953. enumerable: true,
  78954. configurable: true
  78955. });
  78956. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  78957. /**
  78958. * Gets the skybox material created by the helper.
  78959. */
  78960. get: function () {
  78961. return this._skyboxMaterial;
  78962. },
  78963. enumerable: true,
  78964. configurable: true
  78965. });
  78966. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  78967. /**
  78968. * Gets the ground mesh created by the helper.
  78969. */
  78970. get: function () {
  78971. return this._ground;
  78972. },
  78973. enumerable: true,
  78974. configurable: true
  78975. });
  78976. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  78977. /**
  78978. * Gets the ground texture created by the helper.
  78979. */
  78980. get: function () {
  78981. return this._groundTexture;
  78982. },
  78983. enumerable: true,
  78984. configurable: true
  78985. });
  78986. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  78987. /**
  78988. * Gets the ground mirror created by the helper.
  78989. */
  78990. get: function () {
  78991. return this._groundMirror;
  78992. },
  78993. enumerable: true,
  78994. configurable: true
  78995. });
  78996. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  78997. /**
  78998. * Gets the ground mirror render list to helps pushing the meshes
  78999. * you wish in the ground reflection.
  79000. */
  79001. get: function () {
  79002. if (this._groundMirror) {
  79003. return this._groundMirror.renderList;
  79004. }
  79005. return null;
  79006. },
  79007. enumerable: true,
  79008. configurable: true
  79009. });
  79010. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  79011. /**
  79012. * Gets the ground material created by the helper.
  79013. */
  79014. get: function () {
  79015. return this._groundMaterial;
  79016. },
  79017. enumerable: true,
  79018. configurable: true
  79019. });
  79020. /**
  79021. * Updates the background according to the new options
  79022. * @param options
  79023. */
  79024. EnvironmentHelper.prototype.updateOptions = function (options) {
  79025. var newOptions = __assign({}, this._options, options);
  79026. if (this._ground && !newOptions.createGround) {
  79027. this._ground.dispose();
  79028. this._ground = null;
  79029. }
  79030. if (this._groundMaterial && !newOptions.createGround) {
  79031. this._groundMaterial.dispose();
  79032. this._groundMaterial = null;
  79033. }
  79034. if (this._groundTexture) {
  79035. if (this._options.groundTexture != newOptions.groundTexture) {
  79036. this._groundTexture.dispose();
  79037. this._groundTexture = null;
  79038. }
  79039. }
  79040. if (this._skybox && !newOptions.createSkybox) {
  79041. this._skybox.dispose();
  79042. this._skybox = null;
  79043. }
  79044. if (this._skyboxMaterial && !newOptions.createSkybox) {
  79045. this._skyboxMaterial.dispose();
  79046. this._skyboxMaterial = null;
  79047. }
  79048. if (this._skyboxTexture) {
  79049. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  79050. this._skyboxTexture.dispose();
  79051. this._skyboxTexture = null;
  79052. }
  79053. }
  79054. if (this._groundMirror && !newOptions.enableGroundMirror) {
  79055. this._groundMirror.dispose();
  79056. this._groundMirror = null;
  79057. }
  79058. if (this._scene.environmentTexture) {
  79059. if (this._options.environmentTexture != newOptions.environmentTexture) {
  79060. this._scene.environmentTexture.dispose();
  79061. }
  79062. }
  79063. this._options = newOptions;
  79064. this._setupBackground();
  79065. this._setupImageProcessing();
  79066. };
  79067. /**
  79068. * Sets the primary color of all the available elements.
  79069. * @param color
  79070. */
  79071. EnvironmentHelper.prototype.setMainColor = function (color) {
  79072. if (this.groundMaterial) {
  79073. this.groundMaterial.primaryColor = color;
  79074. }
  79075. if (this.skyboxMaterial) {
  79076. this.skyboxMaterial.primaryColor = color;
  79077. }
  79078. if (this.groundMirror) {
  79079. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  79080. }
  79081. };
  79082. /**
  79083. * Setup the image processing according to the specified options.
  79084. */
  79085. EnvironmentHelper.prototype._setupImageProcessing = function () {
  79086. if (this._options.setupImageProcessing) {
  79087. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  79088. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  79089. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  79090. this._setupEnvironmentTexture();
  79091. }
  79092. };
  79093. /**
  79094. * Setup the environment texture according to the specified options.
  79095. */
  79096. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  79097. if (this._scene.environmentTexture) {
  79098. return;
  79099. }
  79100. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  79101. this._scene.environmentTexture = this._options.environmentTexture;
  79102. return;
  79103. }
  79104. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  79105. this._scene.environmentTexture = environmentTexture;
  79106. };
  79107. /**
  79108. * Setup the background according to the specified options.
  79109. */
  79110. EnvironmentHelper.prototype._setupBackground = function () {
  79111. if (!this._rootMesh) {
  79112. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  79113. }
  79114. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  79115. var sceneSize = this._getSceneSize();
  79116. if (this._options.createGround) {
  79117. this._setupGround(sceneSize);
  79118. this._setupGroundMaterial();
  79119. this._setupGroundDiffuseTexture();
  79120. if (this._options.enableGroundMirror) {
  79121. this._setupGroundMirrorTexture(sceneSize);
  79122. }
  79123. this._setupMirrorInGroundMaterial();
  79124. }
  79125. if (this._options.createSkybox) {
  79126. this._setupSkybox(sceneSize);
  79127. this._setupSkyboxMaterial();
  79128. this._setupSkyboxReflectionTexture();
  79129. }
  79130. this._rootMesh.position.x = sceneSize.rootPosition.x;
  79131. this._rootMesh.position.z = sceneSize.rootPosition.z;
  79132. this._rootMesh.position.y = sceneSize.rootPosition.y;
  79133. };
  79134. /**
  79135. * Get the scene sizes according to the setup.
  79136. */
  79137. EnvironmentHelper.prototype._getSceneSize = function () {
  79138. var groundSize = this._options.groundSize;
  79139. var skyboxSize = this._options.skyboxSize;
  79140. var rootPosition = this._options.rootPosition;
  79141. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  79142. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79143. }
  79144. var sceneExtends = this._scene.getWorldExtends();
  79145. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  79146. var bias = 0.0001;
  79147. if (this._options.sizeAuto) {
  79148. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  79149. this._scene.activeCamera.upperRadiusLimit) {
  79150. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  79151. }
  79152. if (this._scene.activeCamera) {
  79153. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  79154. }
  79155. var sceneDiagonalLenght = sceneDiagonal.length();
  79156. if (sceneDiagonalLenght > groundSize) {
  79157. groundSize = sceneDiagonalLenght * 2;
  79158. }
  79159. // 10 % bigger.
  79160. groundSize *= 1.1;
  79161. skyboxSize *= 1.5;
  79162. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  79163. rootPosition.y = sceneExtends.min.y - bias;
  79164. }
  79165. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  79166. };
  79167. /**
  79168. * Setup the ground according to the specified options.
  79169. */
  79170. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  79171. var _this = this;
  79172. if (!this._ground) {
  79173. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  79174. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  79175. this._ground.parent = this._rootMesh;
  79176. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  79177. }
  79178. this._ground.receiveShadows = this._options.enableGroundShadow;
  79179. };
  79180. /**
  79181. * Setup the ground material according to the specified options.
  79182. */
  79183. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  79184. if (!this._groundMaterial) {
  79185. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  79186. }
  79187. this._groundMaterial.alpha = this._options.groundOpacity;
  79188. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  79189. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  79190. this._groundMaterial.primaryLevel = 1;
  79191. this._groundMaterial.primaryColor = this._options.groundColor;
  79192. this._groundMaterial.secondaryLevel = 0;
  79193. this._groundMaterial.tertiaryLevel = 0;
  79194. this._groundMaterial.useRGBColor = false;
  79195. this._groundMaterial.enableNoise = true;
  79196. if (this._ground) {
  79197. this._ground.material = this._groundMaterial;
  79198. }
  79199. };
  79200. /**
  79201. * Setup the ground diffuse texture according to the specified options.
  79202. */
  79203. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  79204. if (!this._groundMaterial) {
  79205. return;
  79206. }
  79207. if (this._groundTexture) {
  79208. return;
  79209. }
  79210. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  79211. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  79212. return;
  79213. }
  79214. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  79215. diffuseTexture.gammaSpace = false;
  79216. diffuseTexture.hasAlpha = true;
  79217. this._groundMaterial.diffuseTexture = diffuseTexture;
  79218. };
  79219. /**
  79220. * Setup the ground mirror texture according to the specified options.
  79221. */
  79222. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  79223. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79224. if (!this._groundMirror) {
  79225. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  79226. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  79227. this._groundMirror.anisotropicFilteringLevel = 1;
  79228. this._groundMirror.wrapU = wrapping;
  79229. this._groundMirror.wrapV = wrapping;
  79230. this._groundMirror.gammaSpace = false;
  79231. if (this._groundMirror.renderList) {
  79232. for (var i = 0; i < this._scene.meshes.length; i++) {
  79233. var mesh = this._scene.meshes[i];
  79234. if (mesh !== this._ground &&
  79235. mesh !== this._skybox &&
  79236. mesh !== this._rootMesh) {
  79237. this._groundMirror.renderList.push(mesh);
  79238. }
  79239. }
  79240. }
  79241. }
  79242. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  79243. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  79244. };
  79245. /**
  79246. * Setup the ground to receive the mirror texture.
  79247. */
  79248. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  79249. if (this._groundMaterial) {
  79250. this._groundMaterial.reflectionTexture = this._groundMirror;
  79251. this._groundMaterial.reflectionFresnel = true;
  79252. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  79253. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  79254. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  79255. }
  79256. };
  79257. /**
  79258. * Setup the skybox according to the specified options.
  79259. */
  79260. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  79261. var _this = this;
  79262. if (!this._skybox) {
  79263. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  79264. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  79265. }
  79266. this._skybox.parent = this._rootMesh;
  79267. };
  79268. /**
  79269. * Setup the skybox material according to the specified options.
  79270. */
  79271. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  79272. if (!this._skybox) {
  79273. return;
  79274. }
  79275. if (!this._skyboxMaterial) {
  79276. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  79277. }
  79278. this._skyboxMaterial.useRGBColor = false;
  79279. this._skyboxMaterial.primaryLevel = 1;
  79280. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  79281. this._skyboxMaterial.secondaryLevel = 0;
  79282. this._skyboxMaterial.tertiaryLevel = 0;
  79283. this._skyboxMaterial.enableNoise = true;
  79284. this._skybox.material = this._skyboxMaterial;
  79285. };
  79286. /**
  79287. * Setup the skybox reflection texture according to the specified options.
  79288. */
  79289. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  79290. if (!this._skyboxMaterial) {
  79291. return;
  79292. }
  79293. if (this._skyboxTexture) {
  79294. return;
  79295. }
  79296. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  79297. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79298. return;
  79299. }
  79300. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  79301. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  79302. this._skyboxTexture.gammaSpace = false;
  79303. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  79304. };
  79305. /**
  79306. * Dispose all the elements created by the Helper.
  79307. */
  79308. EnvironmentHelper.prototype.dispose = function () {
  79309. if (this._groundMaterial) {
  79310. this._groundMaterial.dispose(true, true);
  79311. }
  79312. if (this._skyboxMaterial) {
  79313. this._skyboxMaterial.dispose(true, true);
  79314. }
  79315. this._rootMesh.dispose(false);
  79316. };
  79317. /**
  79318. * Default ground texture URL.
  79319. */
  79320. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  79321. /**
  79322. * Default skybox texture URL.
  79323. */
  79324. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  79325. /**
  79326. * Default environment texture URL.
  79327. */
  79328. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  79329. return EnvironmentHelper;
  79330. }());
  79331. BABYLON.EnvironmentHelper = EnvironmentHelper;
  79332. })(BABYLON || (BABYLON = {}));
  79333. //# sourceMappingURL=babylon.environmentHelper.js.map
  79334. 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}"};
  79335. 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.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\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};"};
  79336. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  79337. var BABYLON;
  79338. (function (BABYLON) {
  79339. var GridMaterialDefines = /** @class */ (function (_super) {
  79340. __extends(GridMaterialDefines, _super);
  79341. function GridMaterialDefines() {
  79342. var _this = _super.call(this) || this;
  79343. _this.TRANSPARENT = false;
  79344. _this.FOG = false;
  79345. _this.PREMULTIPLYALPHA = false;
  79346. _this.rebuild();
  79347. return _this;
  79348. }
  79349. return GridMaterialDefines;
  79350. }(BABYLON.MaterialDefines));
  79351. /**
  79352. * The grid materials allows you to wrap any shape with a grid.
  79353. * Colors are customizable.
  79354. */
  79355. var GridMaterial = /** @class */ (function (_super) {
  79356. __extends(GridMaterial, _super);
  79357. /**
  79358. * constructor
  79359. * @param name The name given to the material in order to identify it afterwards.
  79360. * @param scene The scene the material is used in.
  79361. */
  79362. function GridMaterial(name, scene) {
  79363. var _this = _super.call(this, name, scene) || this;
  79364. /**
  79365. * Main color of the grid (e.g. between lines)
  79366. */
  79367. _this.mainColor = BABYLON.Color3.Black();
  79368. /**
  79369. * Color of the grid lines.
  79370. */
  79371. _this.lineColor = BABYLON.Color3.Teal();
  79372. /**
  79373. * The scale of the grid compared to unit.
  79374. */
  79375. _this.gridRatio = 1.0;
  79376. /**
  79377. * Allows setting an offset for the grid lines.
  79378. */
  79379. _this.gridOffset = BABYLON.Vector3.Zero();
  79380. /**
  79381. * The frequency of thicker lines.
  79382. */
  79383. _this.majorUnitFrequency = 10;
  79384. /**
  79385. * The visibility of minor units in the grid.
  79386. */
  79387. _this.minorUnitVisibility = 0.33;
  79388. /**
  79389. * The grid opacity outside of the lines.
  79390. */
  79391. _this.opacity = 1.0;
  79392. /**
  79393. * Determine RBG output is premultiplied by alpha value.
  79394. */
  79395. _this.preMultiplyAlpha = false;
  79396. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  79397. return _this;
  79398. }
  79399. /**
  79400. * Returns wehter or not the grid requires alpha blending.
  79401. */
  79402. GridMaterial.prototype.needAlphaBlending = function () {
  79403. return this.opacity < 1.0;
  79404. };
  79405. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  79406. return this.needAlphaBlending();
  79407. };
  79408. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79409. if (this.isFrozen) {
  79410. if (this._wasPreviouslyReady && subMesh.effect) {
  79411. return true;
  79412. }
  79413. }
  79414. if (!subMesh._materialDefines) {
  79415. subMesh._materialDefines = new GridMaterialDefines();
  79416. }
  79417. var defines = subMesh._materialDefines;
  79418. var scene = this.getScene();
  79419. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  79420. if (this._renderId === scene.getRenderId()) {
  79421. return true;
  79422. }
  79423. }
  79424. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  79425. defines.TRANSPARENT = !defines.TRANSPARENT;
  79426. defines.markAsUnprocessed();
  79427. }
  79428. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  79429. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  79430. defines.markAsUnprocessed();
  79431. }
  79432. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  79433. // Get correct effect
  79434. if (defines.isDirty) {
  79435. defines.markAsProcessed();
  79436. scene.resetCachedMaterial();
  79437. // Attributes
  79438. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79439. // Defines
  79440. var join = defines.toString();
  79441. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  79442. }
  79443. if (!subMesh.effect || !subMesh.effect.isReady()) {
  79444. return false;
  79445. }
  79446. this._renderId = scene.getRenderId();
  79447. this._wasPreviouslyReady = true;
  79448. return true;
  79449. };
  79450. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  79451. var scene = this.getScene();
  79452. var defines = subMesh._materialDefines;
  79453. if (!defines) {
  79454. return;
  79455. }
  79456. var effect = subMesh.effect;
  79457. if (!effect) {
  79458. return;
  79459. }
  79460. this._activeEffect = effect;
  79461. // Matrices
  79462. this.bindOnlyWorldMatrix(world);
  79463. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  79464. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  79465. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  79466. // Uniforms
  79467. if (this._mustRebind(scene, effect)) {
  79468. this._activeEffect.setColor3("mainColor", this.mainColor);
  79469. this._activeEffect.setColor3("lineColor", this.lineColor);
  79470. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  79471. this._gridControl.x = this.gridRatio;
  79472. this._gridControl.y = Math.round(this.majorUnitFrequency);
  79473. this._gridControl.z = this.minorUnitVisibility;
  79474. this._gridControl.w = this.opacity;
  79475. this._activeEffect.setVector4("gridControl", this._gridControl);
  79476. }
  79477. // Fog
  79478. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  79479. this._afterBind(mesh, this._activeEffect);
  79480. };
  79481. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  79482. _super.prototype.dispose.call(this, forceDisposeEffect);
  79483. };
  79484. GridMaterial.prototype.clone = function (name) {
  79485. var _this = this;
  79486. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  79487. };
  79488. GridMaterial.prototype.serialize = function () {
  79489. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79490. serializationObject.customType = "BABYLON.GridMaterial";
  79491. return serializationObject;
  79492. };
  79493. GridMaterial.prototype.getClassName = function () {
  79494. return "GridMaterial";
  79495. };
  79496. GridMaterial.Parse = function (source, scene, rootUrl) {
  79497. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  79498. };
  79499. __decorate([
  79500. BABYLON.serializeAsColor3()
  79501. ], GridMaterial.prototype, "mainColor", void 0);
  79502. __decorate([
  79503. BABYLON.serializeAsColor3()
  79504. ], GridMaterial.prototype, "lineColor", void 0);
  79505. __decorate([
  79506. BABYLON.serialize()
  79507. ], GridMaterial.prototype, "gridRatio", void 0);
  79508. __decorate([
  79509. BABYLON.serializeAsColor3()
  79510. ], GridMaterial.prototype, "gridOffset", void 0);
  79511. __decorate([
  79512. BABYLON.serialize()
  79513. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  79514. __decorate([
  79515. BABYLON.serialize()
  79516. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  79517. __decorate([
  79518. BABYLON.serialize()
  79519. ], GridMaterial.prototype, "opacity", void 0);
  79520. __decorate([
  79521. BABYLON.serialize()
  79522. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  79523. return GridMaterial;
  79524. }(BABYLON.PushMaterial));
  79525. BABYLON.GridMaterial = GridMaterial;
  79526. })(BABYLON || (BABYLON = {}));
  79527. //# sourceMappingURL=babylon.gridmaterial.js.map
  79528. 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}";
  79529. 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}";
  79530. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  79531. var BABYLON;
  79532. (function (BABYLON) {
  79533. var GLTFLoaderCoordinateSystemMode;
  79534. (function (GLTFLoaderCoordinateSystemMode) {
  79535. /**
  79536. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  79537. */
  79538. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  79539. /**
  79540. * Sets the useRightHandedSystem flag on the scene.
  79541. */
  79542. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  79543. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  79544. var GLTFLoaderAnimationStartMode;
  79545. (function (GLTFLoaderAnimationStartMode) {
  79546. /**
  79547. * No animation will start.
  79548. */
  79549. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  79550. /**
  79551. * The first animation will start.
  79552. */
  79553. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  79554. /**
  79555. * All animations will start.
  79556. */
  79557. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  79558. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  79559. var GLTFFileLoader = /** @class */ (function () {
  79560. function GLTFFileLoader() {
  79561. // #endregion
  79562. // #region V2 options
  79563. /**
  79564. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  79565. */
  79566. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  79567. /**
  79568. * The animation start mode (NONE, FIRST, ALL).
  79569. */
  79570. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  79571. /**
  79572. * Set to true to compile materials before raising the success callback.
  79573. */
  79574. this.compileMaterials = false;
  79575. /**
  79576. * Set to true to also compile materials with clip planes.
  79577. */
  79578. this.useClipPlane = false;
  79579. /**
  79580. * Set to true to compile shadow generators before raising the success callback.
  79581. */
  79582. this.compileShadowGenerators = false;
  79583. this.name = "gltf";
  79584. this.extensions = {
  79585. ".gltf": { isBinary: false },
  79586. ".glb": { isBinary: true }
  79587. };
  79588. }
  79589. /**
  79590. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  79591. */
  79592. GLTFFileLoader.prototype.dispose = function () {
  79593. if (this._loader) {
  79594. this._loader.dispose();
  79595. }
  79596. };
  79597. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  79598. try {
  79599. var loaderData = GLTFFileLoader._parse(data);
  79600. if (this.onParsed) {
  79601. this.onParsed(loaderData);
  79602. }
  79603. this._loader = this._getLoader(loaderData);
  79604. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  79605. }
  79606. catch (e) {
  79607. if (onError) {
  79608. onError(e.message, e);
  79609. }
  79610. else {
  79611. BABYLON.Tools.Error(e.message);
  79612. }
  79613. }
  79614. };
  79615. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  79616. try {
  79617. var loaderData = GLTFFileLoader._parse(data);
  79618. if (this.onParsed) {
  79619. this.onParsed(loaderData);
  79620. }
  79621. this._loader = this._getLoader(loaderData);
  79622. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  79623. }
  79624. catch (e) {
  79625. if (onError) {
  79626. onError(e.message, e);
  79627. }
  79628. else {
  79629. BABYLON.Tools.Error(e.message);
  79630. }
  79631. }
  79632. };
  79633. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  79634. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  79635. };
  79636. GLTFFileLoader.prototype.createPlugin = function () {
  79637. return new GLTFFileLoader();
  79638. };
  79639. GLTFFileLoader._parse = function (data) {
  79640. if (data instanceof ArrayBuffer) {
  79641. return GLTFFileLoader._parseBinary(data);
  79642. }
  79643. return {
  79644. json: JSON.parse(data),
  79645. bin: null
  79646. };
  79647. };
  79648. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  79649. var loaderVersion = { major: 2, minor: 0 };
  79650. var asset = loaderData.json.asset || {};
  79651. var version = GLTFFileLoader._parseVersion(asset.version);
  79652. if (!version) {
  79653. throw new Error("Invalid version: " + asset.version);
  79654. }
  79655. if (asset.minVersion !== undefined) {
  79656. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  79657. if (!minVersion) {
  79658. throw new Error("Invalid minimum version: " + asset.minVersion);
  79659. }
  79660. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  79661. throw new Error("Incompatible minimum version: " + asset.minVersion);
  79662. }
  79663. }
  79664. var createLoaders = {
  79665. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  79666. 2: GLTFFileLoader.CreateGLTFLoaderV2
  79667. };
  79668. var createLoader = createLoaders[version.major];
  79669. if (!createLoader) {
  79670. throw new Error("Unsupported version: " + asset.version);
  79671. }
  79672. return createLoader(this);
  79673. };
  79674. GLTFFileLoader._parseBinary = function (data) {
  79675. var Binary = {
  79676. Magic: 0x46546C67
  79677. };
  79678. var binaryReader = new BinaryReader(data);
  79679. var magic = binaryReader.readUint32();
  79680. if (magic !== Binary.Magic) {
  79681. throw new Error("Unexpected magic: " + magic);
  79682. }
  79683. var version = binaryReader.readUint32();
  79684. switch (version) {
  79685. case 1: return GLTFFileLoader._parseV1(binaryReader);
  79686. case 2: return GLTFFileLoader._parseV2(binaryReader);
  79687. }
  79688. throw new Error("Unsupported version: " + version);
  79689. };
  79690. GLTFFileLoader._parseV1 = function (binaryReader) {
  79691. var ContentFormat = {
  79692. JSON: 0
  79693. };
  79694. var length = binaryReader.readUint32();
  79695. if (length != binaryReader.getLength()) {
  79696. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  79697. }
  79698. var contentLength = binaryReader.readUint32();
  79699. var contentFormat = binaryReader.readUint32();
  79700. var content;
  79701. switch (contentFormat) {
  79702. case ContentFormat.JSON: {
  79703. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  79704. break;
  79705. }
  79706. default: {
  79707. throw new Error("Unexpected content format: " + contentFormat);
  79708. }
  79709. }
  79710. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  79711. var body = binaryReader.readUint8Array(bytesRemaining);
  79712. return {
  79713. json: content,
  79714. bin: body
  79715. };
  79716. };
  79717. GLTFFileLoader._parseV2 = function (binaryReader) {
  79718. var ChunkFormat = {
  79719. JSON: 0x4E4F534A,
  79720. BIN: 0x004E4942
  79721. };
  79722. var length = binaryReader.readUint32();
  79723. if (length !== binaryReader.getLength()) {
  79724. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  79725. }
  79726. // JSON chunk
  79727. var chunkLength = binaryReader.readUint32();
  79728. var chunkFormat = binaryReader.readUint32();
  79729. if (chunkFormat !== ChunkFormat.JSON) {
  79730. throw new Error("First chunk format is not JSON");
  79731. }
  79732. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  79733. // Look for BIN chunk
  79734. var bin = null;
  79735. while (binaryReader.getPosition() < binaryReader.getLength()) {
  79736. var chunkLength_1 = binaryReader.readUint32();
  79737. var chunkFormat_1 = binaryReader.readUint32();
  79738. switch (chunkFormat_1) {
  79739. case ChunkFormat.JSON: {
  79740. throw new Error("Unexpected JSON chunk");
  79741. }
  79742. case ChunkFormat.BIN: {
  79743. bin = binaryReader.readUint8Array(chunkLength_1);
  79744. break;
  79745. }
  79746. default: {
  79747. // ignore unrecognized chunkFormat
  79748. binaryReader.skipBytes(chunkLength_1);
  79749. break;
  79750. }
  79751. }
  79752. }
  79753. return {
  79754. json: json,
  79755. bin: bin
  79756. };
  79757. };
  79758. GLTFFileLoader._parseVersion = function (version) {
  79759. if (version === "1.0" || version === "1.0.1") {
  79760. return {
  79761. major: 1,
  79762. minor: 0
  79763. };
  79764. }
  79765. var match = (version + "").match(/^(\d+)\.(\d+)/);
  79766. if (!match) {
  79767. return null;
  79768. }
  79769. return {
  79770. major: parseInt(match[1]),
  79771. minor: parseInt(match[2])
  79772. };
  79773. };
  79774. GLTFFileLoader._compareVersion = function (a, b) {
  79775. if (a.major > b.major)
  79776. return 1;
  79777. if (a.major < b.major)
  79778. return -1;
  79779. if (a.minor > b.minor)
  79780. return 1;
  79781. if (a.minor < b.minor)
  79782. return -1;
  79783. return 0;
  79784. };
  79785. GLTFFileLoader._decodeBufferToText = function (buffer) {
  79786. var result = "";
  79787. var length = buffer.byteLength;
  79788. for (var i = 0; i < length; i++) {
  79789. result += String.fromCharCode(buffer[i]);
  79790. }
  79791. return result;
  79792. };
  79793. // #endregion
  79794. // #region V1 options
  79795. GLTFFileLoader.IncrementalLoading = true;
  79796. GLTFFileLoader.HomogeneousCoordinates = false;
  79797. return GLTFFileLoader;
  79798. }());
  79799. BABYLON.GLTFFileLoader = GLTFFileLoader;
  79800. var BinaryReader = /** @class */ (function () {
  79801. function BinaryReader(arrayBuffer) {
  79802. this._arrayBuffer = arrayBuffer;
  79803. this._dataView = new DataView(arrayBuffer);
  79804. this._byteOffset = 0;
  79805. }
  79806. BinaryReader.prototype.getPosition = function () {
  79807. return this._byteOffset;
  79808. };
  79809. BinaryReader.prototype.getLength = function () {
  79810. return this._arrayBuffer.byteLength;
  79811. };
  79812. BinaryReader.prototype.readUint32 = function () {
  79813. var value = this._dataView.getUint32(this._byteOffset, true);
  79814. this._byteOffset += 4;
  79815. return value;
  79816. };
  79817. BinaryReader.prototype.readUint8Array = function (length) {
  79818. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  79819. this._byteOffset += length;
  79820. return value;
  79821. };
  79822. BinaryReader.prototype.skipBytes = function (length) {
  79823. this._byteOffset += length;
  79824. };
  79825. return BinaryReader;
  79826. }());
  79827. if (BABYLON.SceneLoader) {
  79828. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  79829. }
  79830. })(BABYLON || (BABYLON = {}));
  79831. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  79832. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79833. var BABYLON;
  79834. (function (BABYLON) {
  79835. var GLTF1;
  79836. (function (GLTF1) {
  79837. /**
  79838. * Enums
  79839. */
  79840. var EComponentType;
  79841. (function (EComponentType) {
  79842. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  79843. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  79844. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  79845. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  79846. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  79847. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  79848. var EShaderType;
  79849. (function (EShaderType) {
  79850. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  79851. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  79852. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  79853. var EParameterType;
  79854. (function (EParameterType) {
  79855. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  79856. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  79857. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  79858. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  79859. EParameterType[EParameterType["INT"] = 5124] = "INT";
  79860. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  79861. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  79862. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  79863. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  79864. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  79865. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  79866. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  79867. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  79868. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  79869. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  79870. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  79871. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  79872. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  79873. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  79874. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  79875. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  79876. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  79877. var ETextureWrapMode;
  79878. (function (ETextureWrapMode) {
  79879. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  79880. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  79881. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  79882. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  79883. var ETextureFilterType;
  79884. (function (ETextureFilterType) {
  79885. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  79886. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  79887. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  79888. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  79889. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  79890. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  79891. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  79892. var ETextureFormat;
  79893. (function (ETextureFormat) {
  79894. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  79895. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  79896. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  79897. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  79898. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  79899. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  79900. var ECullingType;
  79901. (function (ECullingType) {
  79902. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  79903. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  79904. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  79905. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  79906. var EBlendingFunction;
  79907. (function (EBlendingFunction) {
  79908. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  79909. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  79910. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  79911. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  79912. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  79913. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  79914. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  79915. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  79916. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  79917. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  79918. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  79919. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  79920. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  79921. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  79922. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  79923. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  79924. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  79925. })(BABYLON || (BABYLON = {}));
  79926. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  79927. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  79928. var BABYLON;
  79929. (function (BABYLON) {
  79930. var GLTF1;
  79931. (function (GLTF1) {
  79932. /**
  79933. * Tokenizer. Used for shaders compatibility
  79934. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  79935. */
  79936. var ETokenType;
  79937. (function (ETokenType) {
  79938. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  79939. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  79940. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  79941. })(ETokenType || (ETokenType = {}));
  79942. var Tokenizer = /** @class */ (function () {
  79943. function Tokenizer(toParse) {
  79944. this._pos = 0;
  79945. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  79946. this._toParse = toParse;
  79947. this._maxPos = toParse.length;
  79948. }
  79949. Tokenizer.prototype.getNextToken = function () {
  79950. if (this.isEnd())
  79951. return ETokenType.END_OF_INPUT;
  79952. this.currentString = this.read();
  79953. this.currentToken = ETokenType.UNKNOWN;
  79954. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  79955. this.currentToken = ETokenType.IDENTIFIER;
  79956. this.currentIdentifier = this.currentString;
  79957. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  79958. this.currentIdentifier += this.currentString;
  79959. this.forward();
  79960. }
  79961. }
  79962. return this.currentToken;
  79963. };
  79964. Tokenizer.prototype.peek = function () {
  79965. return this._toParse[this._pos];
  79966. };
  79967. Tokenizer.prototype.read = function () {
  79968. return this._toParse[this._pos++];
  79969. };
  79970. Tokenizer.prototype.forward = function () {
  79971. this._pos++;
  79972. };
  79973. Tokenizer.prototype.isEnd = function () {
  79974. return this._pos >= this._maxPos;
  79975. };
  79976. return Tokenizer;
  79977. }());
  79978. /**
  79979. * Values
  79980. */
  79981. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  79982. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  79983. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  79984. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  79985. /**
  79986. * Parse
  79987. */
  79988. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  79989. for (var buf in parsedBuffers) {
  79990. var parsedBuffer = parsedBuffers[buf];
  79991. gltfRuntime.buffers[buf] = parsedBuffer;
  79992. gltfRuntime.buffersCount++;
  79993. }
  79994. };
  79995. var parseShaders = function (parsedShaders, gltfRuntime) {
  79996. for (var sha in parsedShaders) {
  79997. var parsedShader = parsedShaders[sha];
  79998. gltfRuntime.shaders[sha] = parsedShader;
  79999. gltfRuntime.shaderscount++;
  80000. }
  80001. };
  80002. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  80003. for (var object in parsedObjects) {
  80004. var parsedObject = parsedObjects[object];
  80005. gltfRuntime[runtimeProperty][object] = parsedObject;
  80006. }
  80007. };
  80008. /**
  80009. * Utils
  80010. */
  80011. var normalizeUVs = function (buffer) {
  80012. if (!buffer) {
  80013. return;
  80014. }
  80015. for (var i = 0; i < buffer.length / 2; i++) {
  80016. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  80017. }
  80018. };
  80019. var getAttribute = function (attributeParameter) {
  80020. if (attributeParameter.semantic === "NORMAL") {
  80021. return "normal";
  80022. }
  80023. else if (attributeParameter.semantic === "POSITION") {
  80024. return "position";
  80025. }
  80026. else if (attributeParameter.semantic === "JOINT") {
  80027. return "matricesIndices";
  80028. }
  80029. else if (attributeParameter.semantic === "WEIGHT") {
  80030. return "matricesWeights";
  80031. }
  80032. else if (attributeParameter.semantic === "COLOR") {
  80033. return "color";
  80034. }
  80035. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  80036. var channel = Number(attributeParameter.semantic.split("_")[1]);
  80037. return "uv" + (channel === 0 ? "" : channel + 1);
  80038. }
  80039. return null;
  80040. };
  80041. /**
  80042. * Loads and creates animations
  80043. */
  80044. var loadAnimations = function (gltfRuntime) {
  80045. for (var anim in gltfRuntime.animations) {
  80046. var animation = gltfRuntime.animations[anim];
  80047. if (!animation.channels || !animation.samplers) {
  80048. continue;
  80049. }
  80050. var lastAnimation = null;
  80051. for (var i = 0; i < animation.channels.length; i++) {
  80052. // Get parameters and load buffers
  80053. var channel = animation.channels[i];
  80054. var sampler = animation.samplers[channel.sampler];
  80055. if (!sampler) {
  80056. continue;
  80057. }
  80058. var inputData = null;
  80059. var outputData = null;
  80060. if (animation.parameters) {
  80061. inputData = animation.parameters[sampler.input];
  80062. outputData = animation.parameters[sampler.output];
  80063. }
  80064. else {
  80065. inputData = sampler.input;
  80066. outputData = sampler.output;
  80067. }
  80068. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  80069. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  80070. var targetID = channel.target.id;
  80071. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  80072. if (targetNode === null) {
  80073. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  80074. }
  80075. if (targetNode === null) {
  80076. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  80077. continue;
  80078. }
  80079. var isBone = targetNode instanceof BABYLON.Bone;
  80080. // Get target path (position, rotation or scaling)
  80081. var targetPath = channel.target.path;
  80082. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  80083. if (targetPathIndex !== -1) {
  80084. targetPath = babylonAnimationPaths[targetPathIndex];
  80085. }
  80086. // Determine animation type
  80087. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  80088. if (!isBone) {
  80089. if (targetPath === "rotationQuaternion") {
  80090. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  80091. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  80092. }
  80093. else {
  80094. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  80095. }
  80096. }
  80097. // Create animation and key frames
  80098. var babylonAnimation = null;
  80099. var keys = [];
  80100. var arrayOffset = 0;
  80101. var modifyKey = false;
  80102. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  80103. babylonAnimation = lastAnimation;
  80104. modifyKey = true;
  80105. }
  80106. if (!modifyKey) {
  80107. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80108. }
  80109. // For each frame
  80110. for (var j = 0; j < bufferInput.length; j++) {
  80111. var value = null;
  80112. if (targetPath === "rotationQuaternion") {
  80113. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  80114. arrayOffset += 4;
  80115. }
  80116. else {
  80117. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  80118. arrayOffset += 3;
  80119. }
  80120. if (isBone) {
  80121. var bone = targetNode;
  80122. var translation = BABYLON.Vector3.Zero();
  80123. var rotationQuaternion = new BABYLON.Quaternion();
  80124. var scaling = BABYLON.Vector3.Zero();
  80125. // Warning on decompose
  80126. var mat = bone.getBaseMatrix();
  80127. if (modifyKey && lastAnimation) {
  80128. mat = lastAnimation.getKeys()[j].value;
  80129. }
  80130. mat.decompose(scaling, rotationQuaternion, translation);
  80131. if (targetPath === "position") {
  80132. translation = value;
  80133. }
  80134. else if (targetPath === "rotationQuaternion") {
  80135. rotationQuaternion = value;
  80136. }
  80137. else {
  80138. scaling = value;
  80139. }
  80140. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  80141. }
  80142. if (!modifyKey) {
  80143. keys.push({
  80144. frame: bufferInput[j],
  80145. value: value
  80146. });
  80147. }
  80148. else if (lastAnimation) {
  80149. lastAnimation.getKeys()[j].value = value;
  80150. }
  80151. }
  80152. // Finish
  80153. if (!modifyKey && babylonAnimation) {
  80154. babylonAnimation.setKeys(keys);
  80155. targetNode.animations.push(babylonAnimation);
  80156. }
  80157. lastAnimation = babylonAnimation;
  80158. gltfRuntime.scene.stopAnimation(targetNode);
  80159. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  80160. }
  80161. }
  80162. };
  80163. /**
  80164. * Returns the bones transformation matrix
  80165. */
  80166. var configureBoneTransformation = function (node) {
  80167. var mat = null;
  80168. if (node.translation || node.rotation || node.scale) {
  80169. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  80170. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  80171. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  80172. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  80173. }
  80174. else {
  80175. mat = BABYLON.Matrix.FromArray(node.matrix);
  80176. }
  80177. return mat;
  80178. };
  80179. /**
  80180. * Returns the parent bone
  80181. */
  80182. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  80183. // Try to find
  80184. for (var i = 0; i < newSkeleton.bones.length; i++) {
  80185. if (newSkeleton.bones[i].name === jointName) {
  80186. return newSkeleton.bones[i];
  80187. }
  80188. }
  80189. // Not found, search in gltf nodes
  80190. var nodes = gltfRuntime.nodes;
  80191. for (var nde in nodes) {
  80192. var node = nodes[nde];
  80193. if (!node.jointName) {
  80194. continue;
  80195. }
  80196. var children = node.children;
  80197. for (var i = 0; i < children.length; i++) {
  80198. var child = gltfRuntime.nodes[children[i]];
  80199. if (!child.jointName) {
  80200. continue;
  80201. }
  80202. if (child.jointName === jointName) {
  80203. var mat = configureBoneTransformation(node);
  80204. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  80205. bone.id = nde;
  80206. return bone;
  80207. }
  80208. }
  80209. }
  80210. return null;
  80211. };
  80212. /**
  80213. * Returns the appropriate root node
  80214. */
  80215. var getNodeToRoot = function (nodesToRoot, id) {
  80216. for (var i = 0; i < nodesToRoot.length; i++) {
  80217. var nodeToRoot = nodesToRoot[i];
  80218. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  80219. var child = nodeToRoot.node.children[j];
  80220. if (child === id) {
  80221. return nodeToRoot.bone;
  80222. }
  80223. }
  80224. }
  80225. return null;
  80226. };
  80227. /**
  80228. * Returns the node with the joint name
  80229. */
  80230. var getJointNode = function (gltfRuntime, jointName) {
  80231. var nodes = gltfRuntime.nodes;
  80232. var node = nodes[jointName];
  80233. if (node) {
  80234. return {
  80235. node: node,
  80236. id: jointName
  80237. };
  80238. }
  80239. for (var nde in nodes) {
  80240. node = nodes[nde];
  80241. if (node.jointName === jointName) {
  80242. return {
  80243. node: node,
  80244. id: nde
  80245. };
  80246. }
  80247. }
  80248. return null;
  80249. };
  80250. /**
  80251. * Checks if a nodes is in joints
  80252. */
  80253. var nodeIsInJoints = function (skins, id) {
  80254. for (var i = 0; i < skins.jointNames.length; i++) {
  80255. if (skins.jointNames[i] === id) {
  80256. return true;
  80257. }
  80258. }
  80259. return false;
  80260. };
  80261. /**
  80262. * Fills the nodes to root for bones and builds hierarchy
  80263. */
  80264. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  80265. // Creates nodes for root
  80266. for (var nde in gltfRuntime.nodes) {
  80267. var node = gltfRuntime.nodes[nde];
  80268. var id = nde;
  80269. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  80270. continue;
  80271. }
  80272. // Create node to root bone
  80273. var mat = configureBoneTransformation(node);
  80274. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  80275. bone.id = id;
  80276. nodesToRoot.push({ bone: bone, node: node, id: id });
  80277. }
  80278. // Parenting
  80279. for (var i = 0; i < nodesToRoot.length; i++) {
  80280. var nodeToRoot = nodesToRoot[i];
  80281. var children = nodeToRoot.node.children;
  80282. for (var j = 0; j < children.length; j++) {
  80283. var child = null;
  80284. for (var k = 0; k < nodesToRoot.length; k++) {
  80285. if (nodesToRoot[k].id === children[j]) {
  80286. child = nodesToRoot[k];
  80287. break;
  80288. }
  80289. }
  80290. if (child) {
  80291. child.bone._parent = nodeToRoot.bone;
  80292. nodeToRoot.bone.children.push(child.bone);
  80293. }
  80294. }
  80295. }
  80296. };
  80297. /**
  80298. * Imports a skeleton
  80299. */
  80300. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  80301. if (!newSkeleton) {
  80302. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  80303. }
  80304. if (!skins.babylonSkeleton) {
  80305. return newSkeleton;
  80306. }
  80307. // Find the root bones
  80308. var nodesToRoot = [];
  80309. var nodesToRootToAdd = [];
  80310. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  80311. newSkeleton.bones = [];
  80312. // Joints
  80313. for (var i = 0; i < skins.jointNames.length; i++) {
  80314. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  80315. if (!jointNode) {
  80316. continue;
  80317. }
  80318. var node = jointNode.node;
  80319. if (!node) {
  80320. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  80321. continue;
  80322. }
  80323. var id = jointNode.id;
  80324. // Optimize, if the bone already exists...
  80325. var existingBone = gltfRuntime.scene.getBoneByID(id);
  80326. if (existingBone) {
  80327. newSkeleton.bones.push(existingBone);
  80328. continue;
  80329. }
  80330. // Search for parent bone
  80331. var foundBone = false;
  80332. var parentBone = null;
  80333. for (var j = 0; j < i; j++) {
  80334. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  80335. if (!jointNode_1) {
  80336. continue;
  80337. }
  80338. var joint = jointNode_1.node;
  80339. if (!joint) {
  80340. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  80341. continue;
  80342. }
  80343. var children = joint.children;
  80344. if (!children) {
  80345. continue;
  80346. }
  80347. foundBone = false;
  80348. for (var k = 0; k < children.length; k++) {
  80349. if (children[k] === id) {
  80350. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  80351. foundBone = true;
  80352. break;
  80353. }
  80354. }
  80355. if (foundBone) {
  80356. break;
  80357. }
  80358. }
  80359. // Create bone
  80360. var mat = configureBoneTransformation(node);
  80361. if (!parentBone && nodesToRoot.length > 0) {
  80362. parentBone = getNodeToRoot(nodesToRoot, id);
  80363. if (parentBone) {
  80364. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  80365. nodesToRootToAdd.push(parentBone);
  80366. }
  80367. }
  80368. }
  80369. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  80370. bone.id = id;
  80371. }
  80372. // Polish
  80373. var bones = newSkeleton.bones;
  80374. newSkeleton.bones = [];
  80375. for (var i = 0; i < skins.jointNames.length; i++) {
  80376. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  80377. if (!jointNode) {
  80378. continue;
  80379. }
  80380. for (var j = 0; j < bones.length; j++) {
  80381. if (bones[j].id === jointNode.id) {
  80382. newSkeleton.bones.push(bones[j]);
  80383. break;
  80384. }
  80385. }
  80386. }
  80387. newSkeleton.prepare();
  80388. // Finish
  80389. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  80390. newSkeleton.bones.push(nodesToRootToAdd[i]);
  80391. }
  80392. return newSkeleton;
  80393. };
  80394. /**
  80395. * Imports a mesh and its geometries
  80396. */
  80397. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  80398. if (!newMesh) {
  80399. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  80400. newMesh.id = id;
  80401. }
  80402. if (!node.babylonNode) {
  80403. return newMesh;
  80404. }
  80405. var subMaterials = [];
  80406. var vertexData = new BABYLON.VertexData();
  80407. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  80408. var verticesStarts = new Array();
  80409. var verticesCounts = new Array();
  80410. var indexStarts = new Array();
  80411. var indexCounts = new Array();
  80412. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  80413. var meshID = meshes[meshIndex];
  80414. var mesh = gltfRuntime.meshes[meshID];
  80415. if (!mesh) {
  80416. continue;
  80417. }
  80418. // Positions, normals and UVs
  80419. for (var i = 0; i < mesh.primitives.length; i++) {
  80420. // Temporary vertex data
  80421. var tempVertexData = new BABYLON.VertexData();
  80422. var primitive = mesh.primitives[i];
  80423. if (primitive.mode !== 4) {
  80424. // continue;
  80425. }
  80426. var attributes = primitive.attributes;
  80427. var accessor = null;
  80428. var buffer = null;
  80429. // Set positions, normal and uvs
  80430. for (var semantic in attributes) {
  80431. // Link accessor and buffer view
  80432. accessor = gltfRuntime.accessors[attributes[semantic]];
  80433. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  80434. if (semantic === "NORMAL") {
  80435. tempVertexData.normals = new Float32Array(buffer.length);
  80436. tempVertexData.normals.set(buffer);
  80437. }
  80438. else if (semantic === "POSITION") {
  80439. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  80440. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  80441. for (var j = 0; j < buffer.length; j += 4) {
  80442. tempVertexData.positions[j] = buffer[j];
  80443. tempVertexData.positions[j + 1] = buffer[j + 1];
  80444. tempVertexData.positions[j + 2] = buffer[j + 2];
  80445. }
  80446. }
  80447. else {
  80448. tempVertexData.positions = new Float32Array(buffer.length);
  80449. tempVertexData.positions.set(buffer);
  80450. }
  80451. verticesCounts.push(tempVertexData.positions.length);
  80452. }
  80453. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  80454. var channel = Number(semantic.split("_")[1]);
  80455. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  80456. var uvs = new Float32Array(buffer.length);
  80457. uvs.set(buffer);
  80458. normalizeUVs(uvs);
  80459. tempVertexData.set(uvs, uvKind);
  80460. }
  80461. else if (semantic === "JOINT") {
  80462. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  80463. tempVertexData.matricesIndices.set(buffer);
  80464. }
  80465. else if (semantic === "WEIGHT") {
  80466. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  80467. tempVertexData.matricesWeights.set(buffer);
  80468. }
  80469. else if (semantic === "COLOR") {
  80470. tempVertexData.colors = new Float32Array(buffer.length);
  80471. tempVertexData.colors.set(buffer);
  80472. }
  80473. }
  80474. // Indices
  80475. accessor = gltfRuntime.accessors[primitive.indices];
  80476. if (accessor) {
  80477. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  80478. tempVertexData.indices = new Int32Array(buffer.length);
  80479. tempVertexData.indices.set(buffer);
  80480. indexCounts.push(tempVertexData.indices.length);
  80481. }
  80482. else {
  80483. // Set indices on the fly
  80484. var indices = [];
  80485. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  80486. indices.push(j);
  80487. }
  80488. tempVertexData.indices = new Int32Array(indices);
  80489. indexCounts.push(tempVertexData.indices.length);
  80490. }
  80491. vertexData.merge(tempVertexData);
  80492. // Sub material
  80493. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  80494. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  80495. // Update vertices start and index start
  80496. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  80497. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  80498. }
  80499. }
  80500. var material;
  80501. if (subMaterials.length > 1) {
  80502. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  80503. material.subMaterials = subMaterials;
  80504. }
  80505. else {
  80506. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  80507. }
  80508. if (subMaterials.length === 1) {
  80509. material = subMaterials[0];
  80510. }
  80511. if (!newMesh.material) {
  80512. newMesh.material = material;
  80513. }
  80514. // Apply geometry
  80515. geometry.setAllVerticesData(vertexData, false);
  80516. newMesh.computeWorldMatrix(true);
  80517. // Apply submeshes
  80518. newMesh.subMeshes = [];
  80519. var index = 0;
  80520. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  80521. var meshID = meshes[meshIndex];
  80522. var mesh = gltfRuntime.meshes[meshID];
  80523. if (!mesh) {
  80524. continue;
  80525. }
  80526. for (var i = 0; i < mesh.primitives.length; i++) {
  80527. if (mesh.primitives[i].mode !== 4) {
  80528. //continue;
  80529. }
  80530. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  80531. index++;
  80532. }
  80533. }
  80534. // Finish
  80535. return newMesh;
  80536. };
  80537. /**
  80538. * Configure node transformation from position, rotation and scaling
  80539. */
  80540. var configureNode = function (newNode, position, rotation, scaling) {
  80541. if (newNode.position) {
  80542. newNode.position = position;
  80543. }
  80544. if (newNode.rotationQuaternion || newNode.rotation) {
  80545. newNode.rotationQuaternion = rotation;
  80546. }
  80547. if (newNode.scaling) {
  80548. newNode.scaling = scaling;
  80549. }
  80550. };
  80551. /**
  80552. * Configures node from transformation matrix
  80553. */
  80554. var configureNodeFromMatrix = function (newNode, node, parent) {
  80555. if (node.matrix) {
  80556. var position = new BABYLON.Vector3(0, 0, 0);
  80557. var rotation = new BABYLON.Quaternion();
  80558. var scaling = new BABYLON.Vector3(0, 0, 0);
  80559. var mat = BABYLON.Matrix.FromArray(node.matrix);
  80560. mat.decompose(scaling, rotation, position);
  80561. configureNode(newNode, position, rotation, scaling);
  80562. }
  80563. else if (node.translation && node.rotation && node.scale) {
  80564. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  80565. }
  80566. newNode.computeWorldMatrix(true);
  80567. };
  80568. /**
  80569. * Imports a node
  80570. */
  80571. var importNode = function (gltfRuntime, node, id, parent) {
  80572. var lastNode = null;
  80573. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  80574. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  80575. return null;
  80576. }
  80577. }
  80578. // Meshes
  80579. if (node.skin) {
  80580. if (node.meshes) {
  80581. var skin = gltfRuntime.skins[node.skin];
  80582. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  80583. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  80584. if (newMesh.skeleton === null) {
  80585. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  80586. if (!skin.babylonSkeleton) {
  80587. skin.babylonSkeleton = newMesh.skeleton;
  80588. }
  80589. }
  80590. lastNode = newMesh;
  80591. }
  80592. }
  80593. else if (node.meshes) {
  80594. /**
  80595. * Improve meshes property
  80596. */
  80597. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  80598. lastNode = newMesh;
  80599. }
  80600. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  80601. var light = gltfRuntime.lights[node.light];
  80602. if (light) {
  80603. if (light.type === "ambient") {
  80604. var ambienLight = light[light.type];
  80605. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80606. hemiLight.name = node.name || "";
  80607. if (ambienLight.color) {
  80608. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  80609. }
  80610. lastNode = hemiLight;
  80611. }
  80612. else if (light.type === "directional") {
  80613. var directionalLight = light[light.type];
  80614. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80615. dirLight.name = node.name || "";
  80616. if (directionalLight.color) {
  80617. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  80618. }
  80619. lastNode = dirLight;
  80620. }
  80621. else if (light.type === "point") {
  80622. var pointLight = light[light.type];
  80623. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80624. ptLight.name = node.name || "";
  80625. if (pointLight.color) {
  80626. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  80627. }
  80628. lastNode = ptLight;
  80629. }
  80630. else if (light.type === "spot") {
  80631. var spotLight = light[light.type];
  80632. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  80633. spLight.name = node.name || "";
  80634. if (spotLight.color) {
  80635. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  80636. }
  80637. if (spotLight.fallOfAngle) {
  80638. spLight.angle = spotLight.fallOfAngle;
  80639. }
  80640. if (spotLight.fallOffExponent) {
  80641. spLight.exponent = spotLight.fallOffExponent;
  80642. }
  80643. lastNode = spLight;
  80644. }
  80645. }
  80646. }
  80647. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  80648. var camera = gltfRuntime.cameras[node.camera];
  80649. if (camera) {
  80650. if (camera.type === "orthographic") {
  80651. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80652. orthoCamera.name = node.name || "";
  80653. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  80654. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  80655. lastNode = orthoCamera;
  80656. }
  80657. else if (camera.type === "perspective") {
  80658. var perspectiveCamera = camera[camera.type];
  80659. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  80660. persCamera.name = node.name || "";
  80661. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  80662. if (!perspectiveCamera.aspectRatio) {
  80663. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  80664. }
  80665. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  80666. persCamera.maxZ = perspectiveCamera.zfar;
  80667. persCamera.minZ = perspectiveCamera.znear;
  80668. }
  80669. lastNode = persCamera;
  80670. }
  80671. }
  80672. }
  80673. // Empty node
  80674. if (!node.jointName) {
  80675. if (node.babylonNode) {
  80676. return node.babylonNode;
  80677. }
  80678. else if (lastNode === null) {
  80679. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  80680. node.babylonNode = dummy;
  80681. lastNode = dummy;
  80682. }
  80683. }
  80684. if (lastNode !== null) {
  80685. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  80686. configureNodeFromMatrix(lastNode, node, parent);
  80687. }
  80688. else {
  80689. var translation = node.translation || [0, 0, 0];
  80690. var rotation = node.rotation || [0, 0, 0, 1];
  80691. var scale = node.scale || [1, 1, 1];
  80692. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  80693. }
  80694. lastNode.updateCache(true);
  80695. node.babylonNode = lastNode;
  80696. }
  80697. return lastNode;
  80698. };
  80699. /**
  80700. * Traverses nodes and creates them
  80701. */
  80702. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  80703. if (meshIncluded === void 0) { meshIncluded = false; }
  80704. var node = gltfRuntime.nodes[id];
  80705. var newNode = null;
  80706. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  80707. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  80708. meshIncluded = true;
  80709. }
  80710. else {
  80711. meshIncluded = false;
  80712. }
  80713. }
  80714. else {
  80715. meshIncluded = true;
  80716. }
  80717. if (!node.jointName && meshIncluded) {
  80718. newNode = importNode(gltfRuntime, node, id, parent);
  80719. if (newNode !== null) {
  80720. newNode.id = id;
  80721. newNode.parent = parent;
  80722. }
  80723. }
  80724. if (node.children) {
  80725. for (var i = 0; i < node.children.length; i++) {
  80726. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  80727. }
  80728. }
  80729. };
  80730. /**
  80731. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  80732. */
  80733. var postLoad = function (gltfRuntime) {
  80734. // Nodes
  80735. var currentScene = gltfRuntime.currentScene;
  80736. if (currentScene) {
  80737. for (var i = 0; i < currentScene.nodes.length; i++) {
  80738. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80739. }
  80740. }
  80741. else {
  80742. for (var thing in gltfRuntime.scenes) {
  80743. currentScene = gltfRuntime.scenes[thing];
  80744. for (var i = 0; i < currentScene.nodes.length; i++) {
  80745. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  80746. }
  80747. }
  80748. }
  80749. // Set animations
  80750. loadAnimations(gltfRuntime);
  80751. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  80752. var skeleton = gltfRuntime.scene.skeletons[i];
  80753. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  80754. }
  80755. };
  80756. /**
  80757. * onBind shaderrs callback to set uniforms and matrices
  80758. */
  80759. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  80760. var materialValues = material.values || technique.parameters;
  80761. for (var unif in unTreatedUniforms) {
  80762. var uniform = unTreatedUniforms[unif];
  80763. var type = uniform.type;
  80764. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  80765. if (uniform.semantic && !uniform.source && !uniform.node) {
  80766. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  80767. }
  80768. else if (uniform.semantic && (uniform.source || uniform.node)) {
  80769. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  80770. if (source === null) {
  80771. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  80772. }
  80773. if (source === null) {
  80774. continue;
  80775. }
  80776. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  80777. }
  80778. }
  80779. else {
  80780. var value = materialValues[technique.uniforms[unif]];
  80781. if (!value) {
  80782. continue;
  80783. }
  80784. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  80785. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  80786. if (texture === null || texture === undefined) {
  80787. continue;
  80788. }
  80789. shaderMaterial.getEffect().setTexture(unif, texture);
  80790. }
  80791. else {
  80792. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  80793. }
  80794. }
  80795. }
  80796. onSuccess(shaderMaterial);
  80797. };
  80798. /**
  80799. * Prepare uniforms to send the only one time
  80800. * Loads the appropriate textures
  80801. */
  80802. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  80803. var materialValues = material.values || technique.parameters;
  80804. var techniqueUniforms = technique.uniforms;
  80805. /**
  80806. * Prepare values here (not matrices)
  80807. */
  80808. for (var unif in unTreatedUniforms) {
  80809. var uniform = unTreatedUniforms[unif];
  80810. var type = uniform.type;
  80811. var value = materialValues[techniqueUniforms[unif]];
  80812. if (value === undefined) {
  80813. // In case the value is the same for all materials
  80814. value = uniform.value;
  80815. }
  80816. if (!value) {
  80817. continue;
  80818. }
  80819. var onLoadTexture = function (uniformName) {
  80820. return function (texture) {
  80821. if (uniform.value && uniformName) {
  80822. // Static uniform
  80823. shaderMaterial.setTexture(uniformName, texture);
  80824. delete unTreatedUniforms[uniformName];
  80825. }
  80826. };
  80827. };
  80828. // Texture (sampler2D)
  80829. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  80830. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  80831. }
  80832. else {
  80833. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  80834. // Static uniform
  80835. delete unTreatedUniforms[unif];
  80836. }
  80837. }
  80838. }
  80839. };
  80840. /**
  80841. * Shader compilation failed
  80842. */
  80843. var onShaderCompileError = function (program, shaderMaterial, onError) {
  80844. return function (effect, error) {
  80845. shaderMaterial.dispose(true);
  80846. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  80847. };
  80848. };
  80849. /**
  80850. * Shader compilation success
  80851. */
  80852. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  80853. return function (_) {
  80854. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  80855. shaderMaterial.onBind = function (mesh) {
  80856. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  80857. };
  80858. };
  80859. };
  80860. /**
  80861. * Returns the appropriate uniform if already handled by babylon
  80862. */
  80863. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  80864. for (var unif in technique.uniforms) {
  80865. var uniform = technique.uniforms[unif];
  80866. var uniformParameter = technique.parameters[uniform];
  80867. if (tokenizer.currentIdentifier === unif) {
  80868. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  80869. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  80870. if (transformIndex !== -1) {
  80871. delete unTreatedUniforms[unif];
  80872. return babylonTransforms[transformIndex];
  80873. }
  80874. }
  80875. }
  80876. }
  80877. return tokenizer.currentIdentifier;
  80878. };
  80879. /**
  80880. * All shaders loaded. Create materials one by one
  80881. */
  80882. var importMaterials = function (gltfRuntime) {
  80883. // Create materials
  80884. for (var mat in gltfRuntime.materials) {
  80885. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  80886. }
  80887. };
  80888. /**
  80889. * Implementation of the base glTF spec
  80890. */
  80891. var GLTFLoaderBase = /** @class */ (function () {
  80892. function GLTFLoaderBase() {
  80893. }
  80894. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  80895. var gltfRuntime = {
  80896. extensions: {},
  80897. accessors: {},
  80898. buffers: {},
  80899. bufferViews: {},
  80900. meshes: {},
  80901. lights: {},
  80902. cameras: {},
  80903. nodes: {},
  80904. images: {},
  80905. textures: {},
  80906. shaders: {},
  80907. programs: {},
  80908. samplers: {},
  80909. techniques: {},
  80910. materials: {},
  80911. animations: {},
  80912. skins: {},
  80913. extensionsUsed: [],
  80914. scenes: {},
  80915. buffersCount: 0,
  80916. shaderscount: 0,
  80917. scene: scene,
  80918. rootUrl: rootUrl,
  80919. loadedBufferCount: 0,
  80920. loadedBufferViews: {},
  80921. loadedShaderCount: 0,
  80922. importOnlyMeshes: false,
  80923. dummyNodes: []
  80924. };
  80925. // Parse
  80926. if (parsedData.extensions) {
  80927. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  80928. }
  80929. if (parsedData.extensionsUsed) {
  80930. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  80931. }
  80932. if (parsedData.buffers) {
  80933. parseBuffers(parsedData.buffers, gltfRuntime);
  80934. }
  80935. if (parsedData.bufferViews) {
  80936. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  80937. }
  80938. if (parsedData.accessors) {
  80939. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  80940. }
  80941. if (parsedData.meshes) {
  80942. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  80943. }
  80944. if (parsedData.lights) {
  80945. parseObject(parsedData.lights, "lights", gltfRuntime);
  80946. }
  80947. if (parsedData.cameras) {
  80948. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  80949. }
  80950. if (parsedData.nodes) {
  80951. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  80952. }
  80953. if (parsedData.images) {
  80954. parseObject(parsedData.images, "images", gltfRuntime);
  80955. }
  80956. if (parsedData.textures) {
  80957. parseObject(parsedData.textures, "textures", gltfRuntime);
  80958. }
  80959. if (parsedData.shaders) {
  80960. parseShaders(parsedData.shaders, gltfRuntime);
  80961. }
  80962. if (parsedData.programs) {
  80963. parseObject(parsedData.programs, "programs", gltfRuntime);
  80964. }
  80965. if (parsedData.samplers) {
  80966. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  80967. }
  80968. if (parsedData.techniques) {
  80969. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  80970. }
  80971. if (parsedData.materials) {
  80972. parseObject(parsedData.materials, "materials", gltfRuntime);
  80973. }
  80974. if (parsedData.animations) {
  80975. parseObject(parsedData.animations, "animations", gltfRuntime);
  80976. }
  80977. if (parsedData.skins) {
  80978. parseObject(parsedData.skins, "skins", gltfRuntime);
  80979. }
  80980. if (parsedData.scenes) {
  80981. gltfRuntime.scenes = parsedData.scenes;
  80982. }
  80983. if (parsedData.scene && parsedData.scenes) {
  80984. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  80985. }
  80986. return gltfRuntime;
  80987. };
  80988. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  80989. var buffer = gltfRuntime.buffers[id];
  80990. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  80991. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  80992. }
  80993. else {
  80994. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  80995. if (request) {
  80996. onError(request.status + " " + request.statusText);
  80997. }
  80998. });
  80999. }
  81000. };
  81001. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81002. var texture = gltfRuntime.textures[id];
  81003. if (!texture || !texture.source) {
  81004. onError("");
  81005. return;
  81006. }
  81007. if (texture.babylonTexture) {
  81008. onSuccess(null);
  81009. return;
  81010. }
  81011. var source = gltfRuntime.images[texture.source];
  81012. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  81013. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  81014. }
  81015. else {
  81016. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  81017. if (request) {
  81018. onError(request.status + " " + request.statusText);
  81019. }
  81020. });
  81021. }
  81022. };
  81023. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81024. var texture = gltfRuntime.textures[id];
  81025. if (texture.babylonTexture) {
  81026. onSuccess(texture.babylonTexture);
  81027. return;
  81028. }
  81029. var sampler = gltfRuntime.samplers[texture.sampler];
  81030. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  81031. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  81032. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  81033. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  81034. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  81035. var blob = new Blob([buffer]);
  81036. var blobURL = URL.createObjectURL(blob);
  81037. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  81038. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  81039. if (sampler.wrapS !== undefined) {
  81040. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  81041. }
  81042. if (sampler.wrapT !== undefined) {
  81043. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  81044. }
  81045. newTexture.name = id;
  81046. texture.babylonTexture = newTexture;
  81047. onSuccess(newTexture);
  81048. };
  81049. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81050. var shader = gltfRuntime.shaders[id];
  81051. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  81052. var shaderString = atob(shader.uri.split(",")[1]);
  81053. onSuccess(shaderString);
  81054. }
  81055. else {
  81056. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  81057. if (request) {
  81058. onError(request.status + " " + request.statusText);
  81059. }
  81060. });
  81061. }
  81062. };
  81063. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81064. var material = gltfRuntime.materials[id];
  81065. if (!material.technique) {
  81066. if (onError) {
  81067. onError("No technique found.");
  81068. }
  81069. return;
  81070. }
  81071. var technique = gltfRuntime.techniques[material.technique];
  81072. if (!technique) {
  81073. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  81074. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  81075. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81076. onSuccess(defaultMaterial);
  81077. return;
  81078. }
  81079. var program = gltfRuntime.programs[technique.program];
  81080. var states = technique.states;
  81081. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  81082. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  81083. var newVertexShader = "";
  81084. var newPixelShader = "";
  81085. var vertexTokenizer = new Tokenizer(vertexShader);
  81086. var pixelTokenizer = new Tokenizer(pixelShader);
  81087. var unTreatedUniforms = {};
  81088. var uniforms = [];
  81089. var attributes = [];
  81090. var samplers = [];
  81091. // Fill uniform, sampler2D and attributes
  81092. for (var unif in technique.uniforms) {
  81093. var uniform = technique.uniforms[unif];
  81094. var uniformParameter = technique.parameters[uniform];
  81095. unTreatedUniforms[unif] = uniformParameter;
  81096. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  81097. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  81098. if (transformIndex !== -1) {
  81099. uniforms.push(babylonTransforms[transformIndex]);
  81100. delete unTreatedUniforms[unif];
  81101. }
  81102. else {
  81103. uniforms.push(unif);
  81104. }
  81105. }
  81106. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  81107. samplers.push(unif);
  81108. }
  81109. else {
  81110. uniforms.push(unif);
  81111. }
  81112. }
  81113. for (var attr in technique.attributes) {
  81114. var attribute = technique.attributes[attr];
  81115. var attributeParameter = technique.parameters[attribute];
  81116. if (attributeParameter.semantic) {
  81117. attributes.push(getAttribute(attributeParameter));
  81118. }
  81119. }
  81120. // Configure vertex shader
  81121. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  81122. var tokenType = vertexTokenizer.currentToken;
  81123. if (tokenType !== ETokenType.IDENTIFIER) {
  81124. newVertexShader += vertexTokenizer.currentString;
  81125. continue;
  81126. }
  81127. var foundAttribute = false;
  81128. for (var attr in technique.attributes) {
  81129. var attribute = technique.attributes[attr];
  81130. var attributeParameter = technique.parameters[attribute];
  81131. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  81132. newVertexShader += getAttribute(attributeParameter);
  81133. foundAttribute = true;
  81134. break;
  81135. }
  81136. }
  81137. if (foundAttribute) {
  81138. continue;
  81139. }
  81140. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  81141. }
  81142. // Configure pixel shader
  81143. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  81144. var tokenType = pixelTokenizer.currentToken;
  81145. if (tokenType !== ETokenType.IDENTIFIER) {
  81146. newPixelShader += pixelTokenizer.currentString;
  81147. continue;
  81148. }
  81149. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  81150. }
  81151. // Create shader material
  81152. var shaderPath = {
  81153. vertex: program.vertexShader + id,
  81154. fragment: program.fragmentShader + id
  81155. };
  81156. var options = {
  81157. attributes: attributes,
  81158. uniforms: uniforms,
  81159. samplers: samplers,
  81160. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  81161. };
  81162. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  81163. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  81164. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  81165. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  81166. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  81167. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81168. if (states && states.functions) {
  81169. var functions = states.functions;
  81170. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  81171. shaderMaterial.backFaceCulling = false;
  81172. }
  81173. var blendFunc = functions.blendFuncSeparate;
  81174. if (blendFunc) {
  81175. 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) {
  81176. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  81177. }
  81178. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81179. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81180. }
  81181. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81182. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  81183. }
  81184. 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) {
  81185. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  81186. }
  81187. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  81188. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  81189. }
  81190. 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) {
  81191. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  81192. }
  81193. }
  81194. }
  81195. };
  81196. return GLTFLoaderBase;
  81197. }());
  81198. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  81199. /**
  81200. * glTF V1 Loader
  81201. */
  81202. var GLTFLoader = /** @class */ (function () {
  81203. function GLTFLoader() {
  81204. }
  81205. GLTFLoader.RegisterExtension = function (extension) {
  81206. if (GLTFLoader.Extensions[extension.name]) {
  81207. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  81208. return;
  81209. }
  81210. GLTFLoader.Extensions[extension.name] = extension;
  81211. };
  81212. GLTFLoader.prototype.dispose = function () {
  81213. // do nothing
  81214. };
  81215. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  81216. var _this = this;
  81217. scene.useRightHandedSystem = true;
  81218. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  81219. gltfRuntime.importOnlyMeshes = true;
  81220. if (meshesNames === "") {
  81221. gltfRuntime.importMeshesNames = [];
  81222. }
  81223. else if (typeof meshesNames === "string") {
  81224. gltfRuntime.importMeshesNames = [meshesNames];
  81225. }
  81226. else if (meshesNames && !(meshesNames instanceof Array)) {
  81227. gltfRuntime.importMeshesNames = [meshesNames];
  81228. }
  81229. else {
  81230. gltfRuntime.importMeshesNames = [];
  81231. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  81232. }
  81233. // Create nodes
  81234. _this._createNodes(gltfRuntime);
  81235. var meshes = new Array();
  81236. var skeletons = new Array();
  81237. // Fill arrays of meshes and skeletons
  81238. for (var nde in gltfRuntime.nodes) {
  81239. var node = gltfRuntime.nodes[nde];
  81240. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  81241. meshes.push(node.babylonNode);
  81242. }
  81243. }
  81244. for (var skl in gltfRuntime.skins) {
  81245. var skin = gltfRuntime.skins[skl];
  81246. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  81247. skeletons.push(skin.babylonSkeleton);
  81248. }
  81249. }
  81250. // Load buffers, shaders, materials, etc.
  81251. _this._loadBuffersAsync(gltfRuntime, function () {
  81252. _this._loadShadersAsync(gltfRuntime, function () {
  81253. importMaterials(gltfRuntime);
  81254. postLoad(gltfRuntime);
  81255. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  81256. onSuccess(meshes, [], skeletons);
  81257. }
  81258. });
  81259. }, onProgress);
  81260. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  81261. onSuccess(meshes, [], skeletons);
  81262. }
  81263. }, onError);
  81264. return true;
  81265. };
  81266. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  81267. var _this = this;
  81268. scene.useRightHandedSystem = true;
  81269. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  81270. // Load runtime extensios
  81271. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  81272. // Create nodes
  81273. _this._createNodes(gltfRuntime);
  81274. // Load buffers, shaders, materials, etc.
  81275. _this._loadBuffersAsync(gltfRuntime, function () {
  81276. _this._loadShadersAsync(gltfRuntime, function () {
  81277. importMaterials(gltfRuntime);
  81278. postLoad(gltfRuntime);
  81279. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  81280. onSuccess();
  81281. }
  81282. });
  81283. });
  81284. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  81285. onSuccess();
  81286. }
  81287. }, onError);
  81288. }, onError);
  81289. };
  81290. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  81291. var hasShaders = false;
  81292. var processShader = function (sha, shader) {
  81293. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  81294. gltfRuntime.loadedShaderCount++;
  81295. if (shaderString) {
  81296. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  81297. }
  81298. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  81299. onload();
  81300. }
  81301. }, function () {
  81302. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  81303. });
  81304. };
  81305. for (var sha in gltfRuntime.shaders) {
  81306. hasShaders = true;
  81307. var shader = gltfRuntime.shaders[sha];
  81308. if (shader) {
  81309. processShader.bind(this, sha, shader)();
  81310. }
  81311. else {
  81312. BABYLON.Tools.Error("No shader named: " + sha);
  81313. }
  81314. }
  81315. if (!hasShaders) {
  81316. onload();
  81317. }
  81318. };
  81319. ;
  81320. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  81321. var hasBuffers = false;
  81322. var processBuffer = function (buf, buffer) {
  81323. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  81324. gltfRuntime.loadedBufferCount++;
  81325. if (bufferView) {
  81326. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  81327. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  81328. }
  81329. gltfRuntime.loadedBufferViews[buf] = bufferView;
  81330. }
  81331. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  81332. onLoad();
  81333. }
  81334. }, function () {
  81335. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  81336. });
  81337. };
  81338. for (var buf in gltfRuntime.buffers) {
  81339. hasBuffers = true;
  81340. var buffer = gltfRuntime.buffers[buf];
  81341. if (buffer) {
  81342. processBuffer.bind(this, buf, buffer)();
  81343. }
  81344. else {
  81345. BABYLON.Tools.Error("No buffer named: " + buf);
  81346. }
  81347. }
  81348. if (!hasBuffers) {
  81349. onLoad();
  81350. }
  81351. };
  81352. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  81353. var currentScene = gltfRuntime.currentScene;
  81354. if (currentScene) {
  81355. // Only one scene even if multiple scenes are defined
  81356. for (var i = 0; i < currentScene.nodes.length; i++) {
  81357. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81358. }
  81359. }
  81360. else {
  81361. // Load all scenes
  81362. for (var thing in gltfRuntime.scenes) {
  81363. currentScene = gltfRuntime.scenes[thing];
  81364. for (var i = 0; i < currentScene.nodes.length; i++) {
  81365. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  81366. }
  81367. }
  81368. }
  81369. };
  81370. GLTFLoader.Extensions = {};
  81371. return GLTFLoader;
  81372. }());
  81373. GLTF1.GLTFLoader = GLTFLoader;
  81374. ;
  81375. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  81376. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81377. })(BABYLON || (BABYLON = {}));
  81378. //# sourceMappingURL=babylon.glTFLoader.js.map
  81379. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81380. var BABYLON;
  81381. (function (BABYLON) {
  81382. var GLTF1;
  81383. (function (GLTF1) {
  81384. /**
  81385. * Utils functions for GLTF
  81386. */
  81387. var GLTFUtils = /** @class */ (function () {
  81388. function GLTFUtils() {
  81389. }
  81390. /**
  81391. * Sets the given "parameter" matrix
  81392. * @param scene: the {BABYLON.Scene} object
  81393. * @param source: the source node where to pick the matrix
  81394. * @param parameter: the GLTF technique parameter
  81395. * @param uniformName: the name of the shader's uniform
  81396. * @param shaderMaterial: the shader material
  81397. */
  81398. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  81399. var mat = null;
  81400. if (parameter.semantic === "MODEL") {
  81401. mat = source.getWorldMatrix();
  81402. }
  81403. else if (parameter.semantic === "PROJECTION") {
  81404. mat = scene.getProjectionMatrix();
  81405. }
  81406. else if (parameter.semantic === "VIEW") {
  81407. mat = scene.getViewMatrix();
  81408. }
  81409. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  81410. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  81411. }
  81412. else if (parameter.semantic === "MODELVIEW") {
  81413. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  81414. }
  81415. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  81416. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  81417. }
  81418. else if (parameter.semantic === "MODELINVERSE") {
  81419. mat = source.getWorldMatrix().invert();
  81420. }
  81421. else if (parameter.semantic === "VIEWINVERSE") {
  81422. mat = scene.getViewMatrix().invert();
  81423. }
  81424. else if (parameter.semantic === "PROJECTIONINVERSE") {
  81425. mat = scene.getProjectionMatrix().invert();
  81426. }
  81427. else if (parameter.semantic === "MODELVIEWINVERSE") {
  81428. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  81429. }
  81430. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  81431. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  81432. }
  81433. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  81434. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  81435. }
  81436. else {
  81437. debugger;
  81438. }
  81439. if (mat) {
  81440. switch (parameter.type) {
  81441. case GLTF1.EParameterType.FLOAT_MAT2:
  81442. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  81443. break;
  81444. case GLTF1.EParameterType.FLOAT_MAT3:
  81445. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  81446. break;
  81447. case GLTF1.EParameterType.FLOAT_MAT4:
  81448. shaderMaterial.setMatrix(uniformName, mat);
  81449. break;
  81450. default: break;
  81451. }
  81452. }
  81453. };
  81454. /**
  81455. * Sets the given "parameter" matrix
  81456. * @param shaderMaterial: the shader material
  81457. * @param uniform: the name of the shader's uniform
  81458. * @param value: the value of the uniform
  81459. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  81460. */
  81461. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  81462. switch (type) {
  81463. case GLTF1.EParameterType.FLOAT:
  81464. shaderMaterial.setFloat(uniform, value);
  81465. return true;
  81466. case GLTF1.EParameterType.FLOAT_VEC2:
  81467. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  81468. return true;
  81469. case GLTF1.EParameterType.FLOAT_VEC3:
  81470. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  81471. return true;
  81472. case GLTF1.EParameterType.FLOAT_VEC4:
  81473. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  81474. return true;
  81475. default: return false;
  81476. }
  81477. };
  81478. /**
  81479. * If the uri is a base64 string
  81480. * @param uri: the uri to test
  81481. */
  81482. GLTFUtils.IsBase64 = function (uri) {
  81483. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  81484. };
  81485. /**
  81486. * Decode the base64 uri
  81487. * @param uri: the uri to decode
  81488. */
  81489. GLTFUtils.DecodeBase64 = function (uri) {
  81490. var decodedString = atob(uri.split(",")[1]);
  81491. var bufferLength = decodedString.length;
  81492. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  81493. for (var i = 0; i < bufferLength; i++) {
  81494. bufferView[i] = decodedString.charCodeAt(i);
  81495. }
  81496. return bufferView.buffer;
  81497. };
  81498. /**
  81499. * Returns the wrap mode of the texture
  81500. * @param mode: the mode value
  81501. */
  81502. GLTFUtils.GetWrapMode = function (mode) {
  81503. switch (mode) {
  81504. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  81505. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  81506. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  81507. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  81508. }
  81509. };
  81510. /**
  81511. * Returns the byte stride giving an accessor
  81512. * @param accessor: the GLTF accessor objet
  81513. */
  81514. GLTFUtils.GetByteStrideFromType = function (accessor) {
  81515. // Needs this function since "byteStride" isn't requiered in glTF format
  81516. var type = accessor.type;
  81517. switch (type) {
  81518. case "VEC2": return 2;
  81519. case "VEC3": return 3;
  81520. case "VEC4": return 4;
  81521. case "MAT2": return 4;
  81522. case "MAT3": return 9;
  81523. case "MAT4": return 16;
  81524. default: return 1;
  81525. }
  81526. };
  81527. /**
  81528. * Returns the texture filter mode giving a mode value
  81529. * @param mode: the filter mode value
  81530. */
  81531. GLTFUtils.GetTextureFilterMode = function (mode) {
  81532. switch (mode) {
  81533. case GLTF1.ETextureFilterType.LINEAR:
  81534. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  81535. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81536. case GLTF1.ETextureFilterType.NEAREST:
  81537. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  81538. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  81539. }
  81540. };
  81541. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  81542. var byteOffset = bufferView.byteOffset + byteOffset;
  81543. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  81544. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  81545. throw new Error("Buffer access is out of range");
  81546. }
  81547. var buffer = loadedBufferView.buffer;
  81548. byteOffset += loadedBufferView.byteOffset;
  81549. switch (componentType) {
  81550. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  81551. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  81552. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  81553. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  81554. default: return new Float32Array(buffer, byteOffset, byteLength);
  81555. }
  81556. };
  81557. /**
  81558. * Returns a buffer from its accessor
  81559. * @param gltfRuntime: the GLTF runtime
  81560. * @param accessor: the GLTF accessor
  81561. */
  81562. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  81563. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  81564. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  81565. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  81566. };
  81567. /**
  81568. * Decodes a buffer view into a string
  81569. * @param view: the buffer view
  81570. */
  81571. GLTFUtils.DecodeBufferToText = function (view) {
  81572. var result = "";
  81573. var length = view.byteLength;
  81574. for (var i = 0; i < length; ++i) {
  81575. result += String.fromCharCode(view[i]);
  81576. }
  81577. return result;
  81578. };
  81579. /**
  81580. * Returns the default material of gltf. Related to
  81581. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  81582. * @param scene: the Babylon.js scene
  81583. */
  81584. GLTFUtils.GetDefaultMaterial = function (scene) {
  81585. if (!GLTFUtils._DefaultMaterial) {
  81586. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  81587. "precision highp float;",
  81588. "",
  81589. "uniform mat4 worldView;",
  81590. "uniform mat4 projection;",
  81591. "",
  81592. "attribute vec3 position;",
  81593. "",
  81594. "void main(void)",
  81595. "{",
  81596. " gl_Position = projection * worldView * vec4(position, 1.0);",
  81597. "}"
  81598. ].join("\n");
  81599. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  81600. "precision highp float;",
  81601. "",
  81602. "uniform vec4 u_emission;",
  81603. "",
  81604. "void main(void)",
  81605. "{",
  81606. " gl_FragColor = u_emission;",
  81607. "}"
  81608. ].join("\n");
  81609. var shaderPath = {
  81610. vertex: "GLTFDefaultMaterial",
  81611. fragment: "GLTFDefaultMaterial"
  81612. };
  81613. var options = {
  81614. attributes: ["position"],
  81615. uniforms: ["worldView", "projection", "u_emission"],
  81616. samplers: new Array(),
  81617. needAlphaBlending: false
  81618. };
  81619. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  81620. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  81621. }
  81622. return GLTFUtils._DefaultMaterial;
  81623. };
  81624. // The GLTF default material
  81625. GLTFUtils._DefaultMaterial = null;
  81626. return GLTFUtils;
  81627. }());
  81628. GLTF1.GLTFUtils = GLTFUtils;
  81629. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81630. })(BABYLON || (BABYLON = {}));
  81631. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  81632. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81633. var BABYLON;
  81634. (function (BABYLON) {
  81635. var GLTF1;
  81636. (function (GLTF1) {
  81637. var GLTFLoaderExtension = /** @class */ (function () {
  81638. function GLTFLoaderExtension(name) {
  81639. this._name = name;
  81640. }
  81641. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  81642. get: function () {
  81643. return this._name;
  81644. },
  81645. enumerable: true,
  81646. configurable: true
  81647. });
  81648. /**
  81649. * Defines an override for loading the runtime
  81650. * Return true to stop further extensions from loading the runtime
  81651. */
  81652. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  81653. return false;
  81654. };
  81655. /**
  81656. * Defines an onverride for creating gltf runtime
  81657. * Return true to stop further extensions from creating the runtime
  81658. */
  81659. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  81660. return false;
  81661. };
  81662. /**
  81663. * Defines an override for loading buffers
  81664. * Return true to stop further extensions from loading this buffer
  81665. */
  81666. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  81667. return false;
  81668. };
  81669. /**
  81670. * Defines an override for loading texture buffers
  81671. * Return true to stop further extensions from loading this texture data
  81672. */
  81673. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81674. return false;
  81675. };
  81676. /**
  81677. * Defines an override for creating textures
  81678. * Return true to stop further extensions from loading this texture
  81679. */
  81680. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81681. return false;
  81682. };
  81683. /**
  81684. * Defines an override for loading shader strings
  81685. * Return true to stop further extensions from loading this shader data
  81686. */
  81687. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81688. return false;
  81689. };
  81690. /**
  81691. * Defines an override for loading materials
  81692. * Return true to stop further extensions from loading this material
  81693. */
  81694. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81695. return false;
  81696. };
  81697. // ---------
  81698. // Utilities
  81699. // ---------
  81700. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  81701. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81702. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  81703. }, function () {
  81704. setTimeout(function () {
  81705. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  81706. });
  81707. });
  81708. };
  81709. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  81710. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81711. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  81712. }, function () {
  81713. setTimeout(function () {
  81714. onSuccess();
  81715. });
  81716. });
  81717. };
  81718. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  81719. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81720. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  81721. }, function () {
  81722. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  81723. });
  81724. };
  81725. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  81726. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  81727. };
  81728. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81729. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81730. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  81731. }, function () {
  81732. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  81733. });
  81734. };
  81735. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81736. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81737. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  81738. }, function () {
  81739. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  81740. });
  81741. };
  81742. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81743. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81744. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  81745. }, function () {
  81746. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  81747. });
  81748. };
  81749. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  81750. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  81751. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  81752. }, function () {
  81753. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  81754. });
  81755. };
  81756. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  81757. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  81758. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  81759. if (func(loaderExtension)) {
  81760. return;
  81761. }
  81762. }
  81763. defaultFunc();
  81764. };
  81765. return GLTFLoaderExtension;
  81766. }());
  81767. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  81768. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81769. })(BABYLON || (BABYLON = {}));
  81770. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  81771. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81772. var BABYLON;
  81773. (function (BABYLON) {
  81774. var GLTF1;
  81775. (function (GLTF1) {
  81776. var BinaryExtensionBufferName = "binary_glTF";
  81777. ;
  81778. ;
  81779. var GLTFBinaryExtension = /** @class */ (function (_super) {
  81780. __extends(GLTFBinaryExtension, _super);
  81781. function GLTFBinaryExtension() {
  81782. return _super.call(this, "KHR_binary_glTF") || this;
  81783. }
  81784. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  81785. var extensionsUsed = data.json.extensionsUsed;
  81786. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  81787. return false;
  81788. }
  81789. this._bin = data.bin;
  81790. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  81791. return true;
  81792. };
  81793. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81794. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  81795. return false;
  81796. }
  81797. if (id !== BinaryExtensionBufferName) {
  81798. return false;
  81799. }
  81800. onSuccess(this._bin);
  81801. return true;
  81802. };
  81803. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  81804. var texture = gltfRuntime.textures[id];
  81805. var source = gltfRuntime.images[texture.source];
  81806. if (!source.extensions || !(this.name in source.extensions)) {
  81807. return false;
  81808. }
  81809. var sourceExt = source.extensions[this.name];
  81810. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  81811. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  81812. onSuccess(buffer);
  81813. return true;
  81814. };
  81815. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  81816. var shader = gltfRuntime.shaders[id];
  81817. if (!shader.extensions || !(this.name in shader.extensions)) {
  81818. return false;
  81819. }
  81820. var binaryExtensionShader = shader.extensions[this.name];
  81821. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  81822. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  81823. setTimeout(function () {
  81824. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  81825. onSuccess(shaderString);
  81826. });
  81827. return true;
  81828. };
  81829. return GLTFBinaryExtension;
  81830. }(GLTF1.GLTFLoaderExtension));
  81831. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  81832. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  81833. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81834. })(BABYLON || (BABYLON = {}));
  81835. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  81836. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81837. var BABYLON;
  81838. (function (BABYLON) {
  81839. var GLTF1;
  81840. (function (GLTF1) {
  81841. ;
  81842. ;
  81843. ;
  81844. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  81845. __extends(GLTFMaterialsCommonExtension, _super);
  81846. function GLTFMaterialsCommonExtension() {
  81847. return _super.call(this, "KHR_materials_common") || this;
  81848. }
  81849. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  81850. if (!gltfRuntime.extensions)
  81851. return false;
  81852. var extension = gltfRuntime.extensions[this.name];
  81853. if (!extension)
  81854. return false;
  81855. // Create lights
  81856. var lights = extension.lights;
  81857. if (lights) {
  81858. for (var thing in lights) {
  81859. var light = lights[thing];
  81860. switch (light.type) {
  81861. case "ambient":
  81862. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  81863. var ambient = light.ambient;
  81864. if (ambient) {
  81865. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  81866. }
  81867. break;
  81868. case "point":
  81869. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  81870. var point = light.point;
  81871. if (point) {
  81872. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  81873. }
  81874. break;
  81875. case "directional":
  81876. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  81877. var directional = light.directional;
  81878. if (directional) {
  81879. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  81880. }
  81881. break;
  81882. case "spot":
  81883. var spot = light.spot;
  81884. if (spot) {
  81885. 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);
  81886. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  81887. }
  81888. break;
  81889. default:
  81890. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  81891. break;
  81892. }
  81893. }
  81894. }
  81895. return false;
  81896. };
  81897. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  81898. var material = gltfRuntime.materials[id];
  81899. if (!material || !material.extensions)
  81900. return false;
  81901. var extension = material.extensions[this.name];
  81902. if (!extension)
  81903. return false;
  81904. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  81905. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  81906. if (extension.technique === "CONSTANT") {
  81907. standardMaterial.disableLighting = true;
  81908. }
  81909. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  81910. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  81911. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  81912. // Ambient
  81913. if (typeof extension.values.ambient === "string") {
  81914. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  81915. }
  81916. else {
  81917. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  81918. }
  81919. // Diffuse
  81920. if (typeof extension.values.diffuse === "string") {
  81921. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  81922. }
  81923. else {
  81924. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  81925. }
  81926. // Emission
  81927. if (typeof extension.values.emission === "string") {
  81928. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  81929. }
  81930. else {
  81931. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  81932. }
  81933. // Specular
  81934. if (typeof extension.values.specular === "string") {
  81935. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  81936. }
  81937. else {
  81938. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  81939. }
  81940. return true;
  81941. };
  81942. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  81943. // Create buffer from texture url
  81944. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  81945. // Create texture from buffer
  81946. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  81947. }, onError);
  81948. };
  81949. return GLTFMaterialsCommonExtension;
  81950. }(GLTF1.GLTFLoaderExtension));
  81951. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  81952. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  81953. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  81954. })(BABYLON || (BABYLON = {}));
  81955. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  81956. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  81957. var BABYLON;
  81958. (function (BABYLON) {
  81959. var GLTF2;
  81960. (function (GLTF2) {
  81961. /**
  81962. * Enums
  81963. */
  81964. var EComponentType;
  81965. (function (EComponentType) {
  81966. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  81967. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  81968. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  81969. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  81970. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  81971. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  81972. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  81973. var EMeshPrimitiveMode;
  81974. (function (EMeshPrimitiveMode) {
  81975. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  81976. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  81977. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  81978. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  81979. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  81980. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  81981. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  81982. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  81983. var ETextureMagFilter;
  81984. (function (ETextureMagFilter) {
  81985. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  81986. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  81987. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  81988. var ETextureMinFilter;
  81989. (function (ETextureMinFilter) {
  81990. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  81991. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  81992. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  81993. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  81994. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  81995. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  81996. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  81997. var ETextureWrapMode;
  81998. (function (ETextureWrapMode) {
  81999. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82000. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82001. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82002. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  82003. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  82004. })(BABYLON || (BABYLON = {}));
  82005. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82006. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82007. var BABYLON;
  82008. (function (BABYLON) {
  82009. var GLTF2;
  82010. (function (GLTF2) {
  82011. var GLTFLoaderTracker = /** @class */ (function () {
  82012. function GLTFLoaderTracker(onComplete) {
  82013. this._pendingCount = 0;
  82014. this._callback = onComplete;
  82015. }
  82016. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  82017. this._pendingCount++;
  82018. };
  82019. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  82020. if (--this._pendingCount === 0) {
  82021. this._callback();
  82022. }
  82023. };
  82024. return GLTFLoaderTracker;
  82025. }());
  82026. var GLTFLoader = /** @class */ (function () {
  82027. function GLTFLoader(parent) {
  82028. this._disposed = false;
  82029. this._defaultSampler = {};
  82030. this._renderReady = false;
  82031. this._requests = new Array();
  82032. this._renderReadyObservable = new BABYLON.Observable();
  82033. // Count of pending work that needs to complete before the asset is rendered.
  82034. this._renderPendingCount = 0;
  82035. // Count of pending work that needs to complete before the loader is disposed.
  82036. this._loaderPendingCount = 0;
  82037. this._loaderTrackers = new Array();
  82038. this._parent = parent;
  82039. }
  82040. GLTFLoader.RegisterExtension = function (extension) {
  82041. if (GLTFLoader.Extensions[extension.name]) {
  82042. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  82043. return;
  82044. }
  82045. GLTFLoader.Extensions[extension.name] = extension;
  82046. // Keep the order of registration so that extensions registered first are called first.
  82047. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  82048. };
  82049. GLTFLoader.prototype.dispose = function () {
  82050. if (this._disposed) {
  82051. return;
  82052. }
  82053. this._disposed = true;
  82054. // Abort requests that are not complete
  82055. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  82056. var request = _a[_i];
  82057. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  82058. request.abort();
  82059. }
  82060. }
  82061. // Revoke object urls created during load
  82062. if (this._gltf.textures) {
  82063. for (var _b = 0, _c = this._gltf.textures; _b < _c.length; _b++) {
  82064. var texture = _c[_b];
  82065. if (texture.url) {
  82066. URL.revokeObjectURL(texture.url);
  82067. }
  82068. }
  82069. }
  82070. };
  82071. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82072. var _this = this;
  82073. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  82074. if (onSuccess) {
  82075. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  82076. }
  82077. }, onProgress, onError);
  82078. };
  82079. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82080. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  82081. };
  82082. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82083. var _this = this;
  82084. this._babylonScene = scene;
  82085. this._rootUrl = rootUrl;
  82086. this._successCallback = onSuccess;
  82087. this._progressCallback = onProgress;
  82088. this._errorCallback = onError;
  82089. this._tryCatchOnError(function () {
  82090. _this._loadData(data);
  82091. _this._addPendingData(_this);
  82092. _this._loadDefaultScene(nodeNames);
  82093. _this._loadAnimations();
  82094. _this._removePendingData(_this);
  82095. });
  82096. };
  82097. GLTFLoader.prototype._onProgress = function () {
  82098. if (!this._progressCallback) {
  82099. return;
  82100. }
  82101. var lengthComputable = true;
  82102. var loaded = 0;
  82103. var total = 0;
  82104. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  82105. var request = _a[_i];
  82106. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  82107. return;
  82108. }
  82109. lengthComputable = lengthComputable && request._lengthComputable;
  82110. loaded += request._loaded;
  82111. total += request._total;
  82112. }
  82113. this._progressCallback(GLTFLoader._createProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  82114. };
  82115. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  82116. if (this._renderReady) {
  82117. func();
  82118. }
  82119. else {
  82120. this._renderReadyObservable.add(func);
  82121. }
  82122. };
  82123. GLTFLoader.prototype._onRenderReady = function () {
  82124. this._rootNode.babylonMesh.setEnabled(true);
  82125. this._startAnimations();
  82126. if (this._successCallback) {
  82127. this._successCallback();
  82128. }
  82129. this._renderReadyObservable.notifyObservers(this);
  82130. };
  82131. GLTFLoader.prototype._onComplete = function () {
  82132. if (this._parent.onComplete) {
  82133. this._parent.onComplete();
  82134. }
  82135. this.dispose();
  82136. };
  82137. GLTFLoader.prototype._loadData = function (data) {
  82138. this._gltf = data.json;
  82139. // Assign the index of each object for convinience.
  82140. GLTFLoader._AssignIndices(this._gltf.accessors);
  82141. GLTFLoader._AssignIndices(this._gltf.animations);
  82142. GLTFLoader._AssignIndices(this._gltf.buffers);
  82143. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  82144. GLTFLoader._AssignIndices(this._gltf.images);
  82145. GLTFLoader._AssignIndices(this._gltf.materials);
  82146. GLTFLoader._AssignIndices(this._gltf.meshes);
  82147. GLTFLoader._AssignIndices(this._gltf.nodes);
  82148. GLTFLoader._AssignIndices(this._gltf.samplers);
  82149. GLTFLoader._AssignIndices(this._gltf.scenes);
  82150. GLTFLoader._AssignIndices(this._gltf.skins);
  82151. GLTFLoader._AssignIndices(this._gltf.textures);
  82152. if (data.bin) {
  82153. var buffers = this._gltf.buffers;
  82154. if (buffers && buffers[0] && !buffers[0].uri) {
  82155. var binaryBuffer = buffers[0];
  82156. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  82157. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  82158. }
  82159. binaryBuffer.loadedData = data.bin;
  82160. }
  82161. else {
  82162. BABYLON.Tools.Warn("Unexpected BIN chunk");
  82163. }
  82164. }
  82165. };
  82166. GLTFLoader.prototype._getMeshes = function () {
  82167. var meshes = new Array();
  82168. // Root mesh is always first.
  82169. meshes.push(this._rootNode.babylonMesh);
  82170. var nodes = this._gltf.nodes;
  82171. if (nodes) {
  82172. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  82173. var node = nodes_1[_i];
  82174. if (node.babylonMesh) {
  82175. meshes.push(node.babylonMesh);
  82176. }
  82177. }
  82178. }
  82179. return meshes;
  82180. };
  82181. GLTFLoader.prototype._getSkeletons = function () {
  82182. var skeletons = new Array();
  82183. var skins = this._gltf.skins;
  82184. if (skins) {
  82185. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  82186. var skin = skins_1[_i];
  82187. if (skin.babylonSkeleton) {
  82188. skeletons.push(skin.babylonSkeleton);
  82189. }
  82190. }
  82191. }
  82192. return skeletons;
  82193. };
  82194. GLTFLoader.prototype._startAnimations = function () {
  82195. var animations = this._gltf.animations;
  82196. if (!animations) {
  82197. return;
  82198. }
  82199. switch (this._parent.animationStartMode) {
  82200. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  82201. // do nothing
  82202. break;
  82203. }
  82204. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  82205. var animation = animations[0];
  82206. for (var _i = 0, _a = animation.targets; _i < _a.length; _i++) {
  82207. var target = _a[_i];
  82208. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  82209. }
  82210. break;
  82211. }
  82212. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  82213. for (var _b = 0, animations_1 = animations; _b < animations_1.length; _b++) {
  82214. var animation = animations_1[_b];
  82215. for (var _c = 0, _d = animation.targets; _c < _d.length; _c++) {
  82216. var target = _d[_c];
  82217. this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true);
  82218. }
  82219. }
  82220. break;
  82221. }
  82222. default: {
  82223. BABYLON.Tools.Error("Invalid animation start mode " + this._parent.animationStartMode);
  82224. return;
  82225. }
  82226. }
  82227. };
  82228. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  82229. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  82230. if (!scene) {
  82231. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  82232. }
  82233. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  82234. };
  82235. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  82236. var _this = this;
  82237. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  82238. switch (this._parent.coordinateSystemMode) {
  82239. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  82240. if (!this._babylonScene.useRightHandedSystem) {
  82241. this._rootNode.rotation = [0, 1, 0, 0];
  82242. this._rootNode.scale = [1, 1, -1];
  82243. this._loadTransform(this._rootNode);
  82244. }
  82245. break;
  82246. }
  82247. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  82248. this._babylonScene.useRightHandedSystem = true;
  82249. break;
  82250. }
  82251. default: {
  82252. BABYLON.Tools.Error("Invalid coordinate system mode " + this._parent.coordinateSystemMode);
  82253. return;
  82254. }
  82255. }
  82256. if (this._parent.onMeshLoaded) {
  82257. this._parent.onMeshLoaded(this._rootNode.babylonMesh);
  82258. }
  82259. var nodeIndices = scene.nodes;
  82260. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  82261. node.parent = parentNode;
  82262. return true;
  82263. }, this._rootNode);
  82264. if (nodeNames) {
  82265. if (!(nodeNames instanceof Array)) {
  82266. nodeNames = [nodeNames];
  82267. }
  82268. var filteredNodeIndices_1 = new Array();
  82269. this._traverseNodes(context, nodeIndices, function (node) {
  82270. if (nodeNames.indexOf(node.name) !== -1) {
  82271. filteredNodeIndices_1.push(node.index);
  82272. node.parent = _this._rootNode;
  82273. return false;
  82274. }
  82275. return true;
  82276. }, this._rootNode);
  82277. nodeIndices = filteredNodeIndices_1;
  82278. }
  82279. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  82280. var index = nodeIndices_1[_i];
  82281. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82282. if (!node) {
  82283. throw new Error(context + ": Failed to find node " + index);
  82284. }
  82285. this._loadNode("#/nodes/" + index, node);
  82286. }
  82287. // Disable the root mesh until the asset is ready to render.
  82288. this._rootNode.babylonMesh.setEnabled(false);
  82289. };
  82290. GLTFLoader.prototype._loadNode = function (context, node) {
  82291. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  82292. return;
  82293. }
  82294. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  82295. node.babylonMesh.hasVertexAlpha = true;
  82296. this._loadTransform(node);
  82297. if (node.mesh != null) {
  82298. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  82299. if (!mesh) {
  82300. throw new Error(context + ": Failed to find mesh " + node.mesh);
  82301. }
  82302. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  82303. }
  82304. node.babylonMesh.parent = node.parent.babylonMesh;
  82305. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  82306. node.babylonAnimationTargets.push(node.babylonMesh);
  82307. if (node.skin != null) {
  82308. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  82309. if (!skin_1) {
  82310. throw new Error(context + ": Failed to find skin " + node.skin);
  82311. }
  82312. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  82313. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  82314. node.babylonMesh._refreshBoundingInfo(true);
  82315. });
  82316. node.babylonMesh.parent = this._rootNode.babylonMesh;
  82317. node.babylonMesh.position = BABYLON.Vector3.Zero();
  82318. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  82319. node.babylonMesh.scaling = BABYLON.Vector3.One();
  82320. }
  82321. if (node.camera != null) {
  82322. // TODO: handle cameras
  82323. }
  82324. if (node.children) {
  82325. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  82326. var index = _a[_i];
  82327. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82328. if (!childNode) {
  82329. throw new Error(context + ": Failed to find child node " + index);
  82330. }
  82331. this._loadNode("#/nodes/" + index, childNode);
  82332. }
  82333. }
  82334. if (this._parent.onMeshLoaded) {
  82335. this._parent.onMeshLoaded(node.babylonMesh);
  82336. }
  82337. };
  82338. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  82339. var _this = this;
  82340. var primitives = mesh.primitives;
  82341. if (!primitives || primitives.length === 0) {
  82342. throw new Error(context + ": Primitives are missing");
  82343. }
  82344. this._createMorphTargets(context, node, mesh);
  82345. this._loadAllVertexDataAsync(context, mesh, function () {
  82346. _this._loadMorphTargets(context, node, mesh);
  82347. var vertexData = new BABYLON.VertexData();
  82348. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  82349. var primitive = primitives_1[_i];
  82350. vertexData.merge(primitive.vertexData);
  82351. }
  82352. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  82353. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  82354. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  82355. node.babylonMesh.subMeshes = [];
  82356. var verticesStart = 0;
  82357. var indicesStart = 0;
  82358. for (var index = 0; index < primitives.length; index++) {
  82359. var vertexData_1 = primitives[index].vertexData;
  82360. var verticesCount = vertexData_1.positions.length;
  82361. var indicesCount = vertexData_1.indices.length;
  82362. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  82363. verticesStart += verticesCount;
  82364. indicesStart += indicesCount;
  82365. }
  82366. ;
  82367. });
  82368. if (primitives.length === 1) {
  82369. var primitive = primitives[0];
  82370. if (primitive.material == null) {
  82371. node.babylonMesh.material = this._getDefaultMaterial();
  82372. }
  82373. else {
  82374. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  82375. if (!material) {
  82376. throw new Error(context + ": Failed to find material " + primitive.material);
  82377. }
  82378. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  82379. if (isNew && _this._parent.onMaterialLoaded) {
  82380. _this._parent.onMaterialLoaded(babylonMaterial);
  82381. }
  82382. node.babylonMesh.material = babylonMaterial;
  82383. });
  82384. }
  82385. }
  82386. else {
  82387. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  82388. node.babylonMesh.material = multiMaterial;
  82389. var subMaterials_1 = multiMaterial.subMaterials;
  82390. var _loop_1 = function (index) {
  82391. var primitive = primitives[index];
  82392. if (primitive.material == null) {
  82393. subMaterials_1[index] = this_1._getDefaultMaterial();
  82394. }
  82395. else {
  82396. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  82397. if (!material) {
  82398. throw new Error(context + ": Failed to find material " + primitive.material);
  82399. }
  82400. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  82401. if (isNew && _this._parent.onMaterialLoaded) {
  82402. _this._parent.onMaterialLoaded(babylonMaterial);
  82403. }
  82404. subMaterials_1[index] = babylonMaterial;
  82405. });
  82406. }
  82407. };
  82408. var this_1 = this;
  82409. for (var index = 0; index < primitives.length; index++) {
  82410. _loop_1(index);
  82411. }
  82412. ;
  82413. }
  82414. };
  82415. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  82416. var primitives = mesh.primitives;
  82417. var numRemainingPrimitives = primitives.length;
  82418. var _loop_2 = function (index) {
  82419. var primitive = primitives[index];
  82420. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  82421. primitive.vertexData = vertexData;
  82422. if (--numRemainingPrimitives === 0) {
  82423. onSuccess();
  82424. }
  82425. });
  82426. };
  82427. var this_2 = this;
  82428. for (var index = 0; index < primitives.length; index++) {
  82429. _loop_2(index);
  82430. }
  82431. };
  82432. /**
  82433. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  82434. * @param {ArrayBufferView} data
  82435. * @param {IGLTFAccessor} accessor
  82436. */
  82437. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  82438. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  82439. return data;
  82440. }
  82441. var buffer = data;
  82442. var factor = 1;
  82443. switch (accessor.componentType) {
  82444. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  82445. factor = 1 / 255;
  82446. break;
  82447. }
  82448. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  82449. factor = 1 / 65535;
  82450. break;
  82451. }
  82452. default: {
  82453. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  82454. }
  82455. }
  82456. var result = new Float32Array(accessor.count * 2);
  82457. for (var i = 0; i < result.length; ++i) {
  82458. result[i] = buffer[i] * factor;
  82459. }
  82460. return result;
  82461. };
  82462. /**
  82463. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  82464. * @param {ArrayBufferView} data
  82465. * @param {IGLTFAccessor} accessor
  82466. */
  82467. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  82468. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  82469. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  82470. return data;
  82471. }
  82472. var buffer = data;
  82473. var factor = 1;
  82474. switch (accessor.componentType) {
  82475. case GLTF2.EComponentType.FLOAT: {
  82476. factor = 1;
  82477. break;
  82478. }
  82479. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  82480. factor = 1 / 255;
  82481. break;
  82482. }
  82483. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  82484. factor = 1 / 65535;
  82485. break;
  82486. }
  82487. default: {
  82488. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  82489. }
  82490. }
  82491. var result = new Float32Array(accessor.count * 4);
  82492. if (colorComponentCount === 4) {
  82493. for (var i = 0; i < result.length; ++i) {
  82494. result[i] = buffer[i] * factor;
  82495. }
  82496. }
  82497. else {
  82498. var offset = 0;
  82499. for (var i = 0; i < result.length; ++i) {
  82500. if ((i + 1) % 4 === 0) {
  82501. result[i] = 1;
  82502. }
  82503. else {
  82504. result[i] = buffer[offset++] * factor;
  82505. }
  82506. }
  82507. }
  82508. return result;
  82509. };
  82510. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  82511. var _this = this;
  82512. var attributes = primitive.attributes;
  82513. if (!attributes) {
  82514. throw new Error(context + ": Attributes are missing");
  82515. }
  82516. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  82517. // TODO: handle other primitive modes
  82518. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  82519. }
  82520. var vertexData = new BABYLON.VertexData();
  82521. var numRemainingAttributes = Object.keys(attributes).length;
  82522. var _loop_3 = function (attribute) {
  82523. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  82524. if (!accessor) {
  82525. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  82526. }
  82527. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  82528. switch (attribute) {
  82529. case "POSITION": {
  82530. vertexData.positions = data;
  82531. break;
  82532. }
  82533. case "NORMAL": {
  82534. vertexData.normals = data;
  82535. break;
  82536. }
  82537. case "TANGENT": {
  82538. vertexData.tangents = data;
  82539. break;
  82540. }
  82541. case "TEXCOORD_0": {
  82542. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  82543. break;
  82544. }
  82545. case "TEXCOORD_1": {
  82546. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  82547. break;
  82548. }
  82549. case "JOINTS_0": {
  82550. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  82551. break;
  82552. }
  82553. case "WEIGHTS_0": {
  82554. //TODO: need to add support for normalized weights.
  82555. vertexData.matricesWeights = data;
  82556. break;
  82557. }
  82558. case "COLOR_0": {
  82559. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  82560. break;
  82561. }
  82562. default: {
  82563. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  82564. break;
  82565. }
  82566. }
  82567. if (--numRemainingAttributes === 0) {
  82568. if (primitive.indices == null) {
  82569. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  82570. for (var i = 0; i < vertexData.indices.length; i++) {
  82571. vertexData.indices[i] = i;
  82572. }
  82573. onSuccess(vertexData);
  82574. }
  82575. else {
  82576. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  82577. if (!indicesAccessor) {
  82578. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  82579. }
  82580. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  82581. vertexData.indices = data;
  82582. onSuccess(vertexData);
  82583. });
  82584. }
  82585. }
  82586. });
  82587. };
  82588. var this_3 = this;
  82589. for (var attribute in attributes) {
  82590. _loop_3(attribute);
  82591. }
  82592. };
  82593. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  82594. var primitives = mesh.primitives;
  82595. var targets = primitives[0].targets;
  82596. if (!targets) {
  82597. return;
  82598. }
  82599. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  82600. var primitive = primitives_2[_i];
  82601. if (!primitive.targets || primitive.targets.length != targets.length) {
  82602. throw new Error(context + ": All primitives are required to list the same number of targets");
  82603. }
  82604. }
  82605. var morphTargetManager = new BABYLON.MorphTargetManager();
  82606. node.babylonMesh.morphTargetManager = morphTargetManager;
  82607. for (var index = 0; index < targets.length; index++) {
  82608. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  82609. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  82610. }
  82611. };
  82612. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  82613. var morphTargetManager = node.babylonMesh.morphTargetManager;
  82614. if (!morphTargetManager) {
  82615. return;
  82616. }
  82617. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  82618. var numTargets = morphTargetManager.numTargets;
  82619. for (var index = 0; index < numTargets; index++) {
  82620. var vertexData = new BABYLON.VertexData();
  82621. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  82622. var primitive = _a[_i];
  82623. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  82624. }
  82625. if (!vertexData.positions) {
  82626. throw new Error(context + ": Positions are missing");
  82627. }
  82628. var target = morphTargetManager.getTarget(index);
  82629. target.setPositions(vertexData.positions);
  82630. target.setNormals(vertexData.normals);
  82631. target.setTangents(vertexData.tangents);
  82632. }
  82633. });
  82634. };
  82635. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  82636. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  82637. var _loop_4 = function (primitive) {
  82638. var targets = primitive.targets;
  82639. primitive.targetsVertexData = new Array(targets.length);
  82640. var _loop_5 = function (index) {
  82641. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  82642. primitive.targetsVertexData[index] = vertexData;
  82643. if (--numRemainingTargets === 0) {
  82644. onSuccess();
  82645. }
  82646. });
  82647. };
  82648. for (var index = 0; index < targets.length; index++) {
  82649. _loop_5(index);
  82650. }
  82651. };
  82652. var this_4 = this;
  82653. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  82654. var primitive = _a[_i];
  82655. _loop_4(primitive);
  82656. }
  82657. };
  82658. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  82659. var targetVertexData = new BABYLON.VertexData();
  82660. var numRemainingAttributes = Object.keys(attributes).length;
  82661. var _loop_6 = function (attribute) {
  82662. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  82663. if (!accessor) {
  82664. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  82665. }
  82666. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  82667. // glTF stores morph target information as deltas while babylon.js expects the final data.
  82668. // As a result we have to add the original data to the delta to calculate the final data.
  82669. var values = data;
  82670. switch (attribute) {
  82671. case "POSITION": {
  82672. for (var i = 0; i < values.length; i++) {
  82673. values[i] += vertexData.positions[i];
  82674. }
  82675. targetVertexData.positions = values;
  82676. break;
  82677. }
  82678. case "NORMAL": {
  82679. for (var i = 0; i < values.length; i++) {
  82680. values[i] += vertexData.normals[i];
  82681. }
  82682. targetVertexData.normals = values;
  82683. break;
  82684. }
  82685. case "TANGENT": {
  82686. // Tangent data for morph targets is stored as xyz delta.
  82687. // The vertexData.tangent is stored as xyzw.
  82688. // So we need to skip every fourth vertexData.tangent.
  82689. for (var i = 0, j = 0; i < values.length; i++, j++) {
  82690. values[i] += vertexData.tangents[j];
  82691. if ((i + 1) % 3 == 0) {
  82692. j++;
  82693. }
  82694. }
  82695. targetVertexData.tangents = values;
  82696. break;
  82697. }
  82698. default: {
  82699. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  82700. break;
  82701. }
  82702. }
  82703. if (--numRemainingAttributes === 0) {
  82704. onSuccess(targetVertexData);
  82705. }
  82706. });
  82707. };
  82708. var this_5 = this;
  82709. for (var attribute in attributes) {
  82710. _loop_6(attribute);
  82711. }
  82712. };
  82713. GLTFLoader.prototype._loadTransform = function (node) {
  82714. var position = BABYLON.Vector3.Zero();
  82715. var rotation = BABYLON.Quaternion.Identity();
  82716. var scaling = BABYLON.Vector3.One();
  82717. if (node.matrix) {
  82718. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  82719. matrix.decompose(scaling, rotation, position);
  82720. }
  82721. else {
  82722. if (node.translation)
  82723. position = BABYLON.Vector3.FromArray(node.translation);
  82724. if (node.rotation)
  82725. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  82726. if (node.scale)
  82727. scaling = BABYLON.Vector3.FromArray(node.scale);
  82728. }
  82729. node.babylonMesh.position = position;
  82730. node.babylonMesh.rotationQuaternion = rotation;
  82731. node.babylonMesh.scaling = scaling;
  82732. };
  82733. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  82734. var _this = this;
  82735. if (skin.babylonSkeleton) {
  82736. onSuccess();
  82737. return;
  82738. }
  82739. var skeletonId = "skeleton" + skin.index;
  82740. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  82741. if (skin.inverseBindMatrices == null) {
  82742. this._loadBones(context, skin, null);
  82743. onSuccess();
  82744. }
  82745. else {
  82746. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  82747. if (!accessor) {
  82748. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  82749. }
  82750. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  82751. _this._loadBones(context, skin, data);
  82752. onSuccess();
  82753. });
  82754. }
  82755. };
  82756. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  82757. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  82758. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  82759. node.babylonAnimationTargets.push(babylonBone);
  82760. return babylonBone;
  82761. };
  82762. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  82763. var babylonBones = {};
  82764. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  82765. var index = _a[_i];
  82766. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82767. if (!node) {
  82768. throw new Error(context + ": Failed to find joint " + index);
  82769. }
  82770. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  82771. }
  82772. };
  82773. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  82774. var babylonBone = babylonBones[node.index];
  82775. if (babylonBone) {
  82776. return babylonBone;
  82777. }
  82778. var boneIndex = skin.joints.indexOf(node.index);
  82779. var baseMatrix = BABYLON.Matrix.Identity();
  82780. if (inverseBindMatrixData && boneIndex !== -1) {
  82781. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  82782. baseMatrix.invertToRef(baseMatrix);
  82783. }
  82784. var babylonParentBone = null;
  82785. if (node.parent !== this._rootNode) {
  82786. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  82787. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  82788. }
  82789. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  82790. babylonBones[node.index] = babylonBone;
  82791. return babylonBone;
  82792. };
  82793. GLTFLoader.prototype._getNodeMatrix = function (node) {
  82794. return node.matrix ?
  82795. BABYLON.Matrix.FromArray(node.matrix) :
  82796. 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());
  82797. };
  82798. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  82799. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  82800. var index = indices_1[_i];
  82801. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  82802. if (!node) {
  82803. throw new Error(context + ": Failed to find node " + index);
  82804. }
  82805. this._traverseNode(context, node, action, parentNode);
  82806. }
  82807. };
  82808. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  82809. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  82810. return;
  82811. }
  82812. if (!action(node, parentNode)) {
  82813. return;
  82814. }
  82815. if (node.children) {
  82816. this._traverseNodes(context, node.children, action, node);
  82817. }
  82818. };
  82819. GLTFLoader.prototype._loadAnimations = function () {
  82820. var animations = this._gltf.animations;
  82821. if (!animations) {
  82822. return;
  82823. }
  82824. for (var index = 0; index < animations.length; index++) {
  82825. var animation = animations[index];
  82826. this._loadAnimation("#/animations/" + index, animation);
  82827. }
  82828. };
  82829. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  82830. animation.targets = [];
  82831. for (var index = 0; index < animation.channels.length; index++) {
  82832. var channel = GLTFLoader._GetProperty(animation.channels, index);
  82833. if (!channel) {
  82834. throw new Error(context + ": Failed to find channel " + index);
  82835. }
  82836. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  82837. if (!sampler) {
  82838. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  82839. }
  82840. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  82841. }
  82842. };
  82843. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  82844. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  82845. if (!targetNode) {
  82846. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  82847. }
  82848. var targetPath;
  82849. var animationType;
  82850. switch (channel.target.path) {
  82851. case "translation": {
  82852. targetPath = "position";
  82853. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82854. break;
  82855. }
  82856. case "rotation": {
  82857. targetPath = "rotationQuaternion";
  82858. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82859. break;
  82860. }
  82861. case "scale": {
  82862. targetPath = "scaling";
  82863. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82864. break;
  82865. }
  82866. case "weights": {
  82867. targetPath = "influence";
  82868. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  82869. break;
  82870. }
  82871. default: {
  82872. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  82873. }
  82874. }
  82875. var inputData;
  82876. var outputData;
  82877. var checkSuccess = function () {
  82878. if (!inputData || !outputData) {
  82879. return;
  82880. }
  82881. var outputBufferOffset = 0;
  82882. var getNextOutputValue;
  82883. switch (targetPath) {
  82884. case "position": {
  82885. getNextOutputValue = function () {
  82886. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  82887. outputBufferOffset += 3;
  82888. return value;
  82889. };
  82890. break;
  82891. }
  82892. case "rotationQuaternion": {
  82893. getNextOutputValue = function () {
  82894. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  82895. outputBufferOffset += 4;
  82896. return value;
  82897. };
  82898. break;
  82899. }
  82900. case "scaling": {
  82901. getNextOutputValue = function () {
  82902. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  82903. outputBufferOffset += 3;
  82904. return value;
  82905. };
  82906. break;
  82907. }
  82908. case "influence": {
  82909. getNextOutputValue = function () {
  82910. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  82911. var value = new Array(numTargets);
  82912. for (var i = 0; i < numTargets; i++) {
  82913. value[i] = outputData[outputBufferOffset++];
  82914. }
  82915. return value;
  82916. };
  82917. break;
  82918. }
  82919. }
  82920. var getNextKey;
  82921. switch (sampler.interpolation) {
  82922. case "LINEAR": {
  82923. getNextKey = function (frameIndex) { return ({
  82924. frame: inputData[frameIndex],
  82925. value: getNextOutputValue()
  82926. }); };
  82927. break;
  82928. }
  82929. case "CUBICSPLINE": {
  82930. getNextKey = function (frameIndex) { return ({
  82931. frame: inputData[frameIndex],
  82932. inTangent: getNextOutputValue(),
  82933. value: getNextOutputValue(),
  82934. outTangent: getNextOutputValue()
  82935. }); };
  82936. break;
  82937. }
  82938. default: {
  82939. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  82940. }
  82941. }
  82942. ;
  82943. var keys;
  82944. if (inputData.length === 1) {
  82945. var key = getNextKey(0);
  82946. keys = [
  82947. { frame: key.frame, value: key.value },
  82948. { frame: key.frame + 1, value: key.value }
  82949. ];
  82950. }
  82951. else {
  82952. keys = new Array(inputData.length);
  82953. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  82954. keys[frameIndex] = getNextKey(frameIndex);
  82955. }
  82956. }
  82957. if (targetPath === "influence") {
  82958. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  82959. var _loop_7 = function (targetIndex) {
  82960. var morphTarget = morphTargetManager.getTarget(targetIndex);
  82961. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  82962. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  82963. babylonAnimation.setKeys(keys.map(function (key) { return ({
  82964. frame: key.frame,
  82965. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  82966. value: key.value[targetIndex],
  82967. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  82968. }); }));
  82969. morphTarget.animations.push(babylonAnimation);
  82970. animation.targets.push(morphTarget);
  82971. };
  82972. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  82973. _loop_7(targetIndex);
  82974. }
  82975. }
  82976. else {
  82977. var animationName = animation.name || "anim" + animation.index;
  82978. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  82979. babylonAnimation.setKeys(keys);
  82980. if (targetNode.babylonAnimationTargets) {
  82981. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  82982. var target = _a[_i];
  82983. target.animations.push(babylonAnimation.clone());
  82984. animation.targets.push(target);
  82985. }
  82986. }
  82987. }
  82988. };
  82989. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  82990. if (!inputAccessor) {
  82991. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  82992. }
  82993. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  82994. inputData = data;
  82995. checkSuccess();
  82996. });
  82997. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  82998. if (!outputAccessor) {
  82999. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  83000. }
  83001. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  83002. outputData = data;
  83003. checkSuccess();
  83004. });
  83005. };
  83006. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  83007. var _this = this;
  83008. this._addPendingData(buffer);
  83009. if (buffer.loadedData) {
  83010. onSuccess(buffer.loadedData);
  83011. this._removePendingData(buffer);
  83012. }
  83013. else if (buffer.loadedObservable) {
  83014. buffer.loadedObservable.add(function (buffer) {
  83015. onSuccess(buffer.loadedData);
  83016. _this._removePendingData(buffer);
  83017. });
  83018. }
  83019. else {
  83020. if (!buffer.uri) {
  83021. throw new Error(context + ": Uri is missing");
  83022. }
  83023. buffer.loadedObservable = new BABYLON.Observable();
  83024. buffer.loadedObservable.add(function (buffer) {
  83025. onSuccess(buffer.loadedData);
  83026. _this._removePendingData(buffer);
  83027. });
  83028. this._loadUriAsync(context, buffer.uri, function (data) {
  83029. buffer.loadedData = data;
  83030. buffer.loadedObservable.notifyObservers(buffer);
  83031. buffer.loadedObservable = undefined;
  83032. });
  83033. }
  83034. };
  83035. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  83036. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  83037. if (!buffer) {
  83038. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  83039. }
  83040. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  83041. var data;
  83042. try {
  83043. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  83044. }
  83045. catch (e) {
  83046. throw new Error(context + ": " + e.message);
  83047. }
  83048. onSuccess(data);
  83049. });
  83050. };
  83051. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  83052. var _this = this;
  83053. if (accessor.sparse) {
  83054. throw new Error(context + ": Sparse accessors are not currently supported");
  83055. }
  83056. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  83057. if (!bufferView) {
  83058. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  83059. }
  83060. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  83061. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  83062. var data;
  83063. var byteOffset = accessor.byteOffset || 0;
  83064. var byteStride = bufferView.byteStride;
  83065. if (byteStride === 0) {
  83066. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  83067. }
  83068. try {
  83069. switch (accessor.componentType) {
  83070. case GLTF2.EComponentType.BYTE: {
  83071. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83072. break;
  83073. }
  83074. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  83075. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83076. break;
  83077. }
  83078. case GLTF2.EComponentType.SHORT: {
  83079. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83080. break;
  83081. }
  83082. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  83083. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83084. break;
  83085. }
  83086. case GLTF2.EComponentType.UNSIGNED_INT: {
  83087. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83088. break;
  83089. }
  83090. case GLTF2.EComponentType.FLOAT: {
  83091. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  83092. break;
  83093. }
  83094. default: {
  83095. throw new Error(context + ": Invalid component type " + accessor.componentType);
  83096. }
  83097. }
  83098. }
  83099. catch (e) {
  83100. throw new Error(context + ": " + e);
  83101. }
  83102. onSuccess(data);
  83103. });
  83104. };
  83105. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  83106. byteOffset += data.byteOffset;
  83107. var targetLength = count * numComponents;
  83108. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  83109. return new typedArray(data.buffer, byteOffset, targetLength);
  83110. }
  83111. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  83112. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  83113. var targetBuffer = new typedArray(targetLength);
  83114. var sourceIndex = 0;
  83115. var targetIndex = 0;
  83116. while (targetIndex < targetLength) {
  83117. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  83118. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  83119. targetIndex++;
  83120. }
  83121. sourceIndex += elementStride;
  83122. }
  83123. return targetBuffer;
  83124. };
  83125. GLTFLoader.prototype._addPendingData = function (data) {
  83126. if (!this._renderReady) {
  83127. this._renderPendingCount++;
  83128. }
  83129. this._addLoaderPendingData(data);
  83130. };
  83131. GLTFLoader.prototype._removePendingData = function (data) {
  83132. var _this = this;
  83133. if (!this._renderReady) {
  83134. if (--this._renderPendingCount === 0) {
  83135. this._addLoaderPendingData(this);
  83136. this._compileMaterialsAsync(function () {
  83137. _this._compileShadowGeneratorsAsync(function () {
  83138. _this._removeLoaderPendingData(_this);
  83139. _this._renderReady = true;
  83140. _this._onRenderReady();
  83141. });
  83142. });
  83143. }
  83144. }
  83145. this._removeLoaderPendingData(data);
  83146. };
  83147. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  83148. this._loaderPendingCount++;
  83149. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  83150. var tracker = _a[_i];
  83151. tracker._addPendingData(data);
  83152. }
  83153. };
  83154. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  83155. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  83156. var tracker = _a[_i];
  83157. tracker._removePendingData(data);
  83158. }
  83159. if (--this._loaderPendingCount === 0) {
  83160. this._onComplete();
  83161. }
  83162. };
  83163. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  83164. var _this = this;
  83165. var tracker = new GLTFLoaderTracker(function () {
  83166. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  83167. onComplete();
  83168. });
  83169. this._loaderTrackers.push(tracker);
  83170. this._addLoaderPendingData(tracker);
  83171. action();
  83172. this._removeLoaderPendingData(tracker);
  83173. };
  83174. GLTFLoader.prototype._getDefaultMaterial = function () {
  83175. if (!this._defaultMaterial) {
  83176. var id = "__gltf_default";
  83177. var material = this._babylonScene.getMaterialByName(id);
  83178. if (!material) {
  83179. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  83180. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83181. material.metallic = 1;
  83182. material.roughness = 1;
  83183. }
  83184. this._defaultMaterial = material;
  83185. }
  83186. return this._defaultMaterial;
  83187. };
  83188. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  83189. var babylonMaterial = material.babylonMaterial;
  83190. // Ensure metallic workflow
  83191. babylonMaterial.metallic = 1;
  83192. babylonMaterial.roughness = 1;
  83193. var properties = material.pbrMetallicRoughness;
  83194. if (!properties) {
  83195. return;
  83196. }
  83197. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  83198. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  83199. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  83200. if (properties.baseColorTexture) {
  83201. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  83202. if (!texture) {
  83203. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  83204. }
  83205. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  83206. }
  83207. if (properties.metallicRoughnessTexture) {
  83208. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  83209. if (!texture) {
  83210. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  83211. }
  83212. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  83213. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  83214. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  83215. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  83216. }
  83217. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  83218. };
  83219. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  83220. if (material.babylonMaterial) {
  83221. assign(material.babylonMaterial, false);
  83222. return;
  83223. }
  83224. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  83225. return;
  83226. }
  83227. this._createPbrMaterial(material);
  83228. this._loadMaterialBaseProperties(context, material);
  83229. this._loadMaterialMetallicRoughnessProperties(context, material);
  83230. assign(material.babylonMaterial, true);
  83231. };
  83232. GLTFLoader.prototype._createPbrMaterial = function (material) {
  83233. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  83234. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83235. material.babylonMaterial = babylonMaterial;
  83236. };
  83237. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  83238. var babylonMaterial = material.babylonMaterial;
  83239. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  83240. if (material.doubleSided) {
  83241. babylonMaterial.backFaceCulling = false;
  83242. babylonMaterial.twoSidedLighting = true;
  83243. }
  83244. if (material.normalTexture) {
  83245. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  83246. if (!texture) {
  83247. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  83248. }
  83249. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  83250. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  83251. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  83252. if (material.normalTexture.scale != null) {
  83253. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  83254. }
  83255. }
  83256. if (material.occlusionTexture) {
  83257. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  83258. if (!texture) {
  83259. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  83260. }
  83261. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  83262. babylonMaterial.useAmbientInGrayScale = true;
  83263. if (material.occlusionTexture.strength != null) {
  83264. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  83265. }
  83266. }
  83267. if (material.emissiveTexture) {
  83268. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  83269. if (!texture) {
  83270. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  83271. }
  83272. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  83273. }
  83274. };
  83275. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  83276. var babylonMaterial = material.babylonMaterial;
  83277. var alphaMode = material.alphaMode || "OPAQUE";
  83278. switch (alphaMode) {
  83279. case "OPAQUE": {
  83280. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  83281. break;
  83282. }
  83283. case "MASK": {
  83284. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  83285. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  83286. if (colorFactor) {
  83287. if (colorFactor[3] == 0) {
  83288. babylonMaterial.alphaCutOff = 1;
  83289. }
  83290. else {
  83291. babylonMaterial.alphaCutOff /= colorFactor[3];
  83292. }
  83293. }
  83294. if (babylonMaterial.albedoTexture) {
  83295. babylonMaterial.albedoTexture.hasAlpha = true;
  83296. }
  83297. break;
  83298. }
  83299. case "BLEND": {
  83300. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  83301. if (colorFactor) {
  83302. babylonMaterial.alpha = colorFactor[3];
  83303. }
  83304. if (babylonMaterial.albedoTexture) {
  83305. babylonMaterial.albedoTexture.hasAlpha = true;
  83306. babylonMaterial.useAlphaFromAlbedoTexture = true;
  83307. }
  83308. break;
  83309. }
  83310. default: {
  83311. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  83312. }
  83313. }
  83314. };
  83315. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  83316. var _this = this;
  83317. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  83318. if (!sampler) {
  83319. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  83320. }
  83321. this._loadSampler("#/samplers/" + sampler.index, sampler);
  83322. this._addPendingData(texture);
  83323. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  83324. _this._tryCatchOnError(function () {
  83325. _this._removePendingData(texture);
  83326. });
  83327. }, function (message) {
  83328. _this._tryCatchOnError(function () {
  83329. throw new Error(context + ": " + message);
  83330. });
  83331. });
  83332. if (texture.url) {
  83333. babylonTexture.updateURL(texture.url);
  83334. }
  83335. else if (texture.dataReadyObservable) {
  83336. texture.dataReadyObservable.add(function (texture) {
  83337. babylonTexture.updateURL(texture.url);
  83338. });
  83339. }
  83340. else {
  83341. texture.dataReadyObservable = new BABYLON.Observable();
  83342. texture.dataReadyObservable.add(function (texture) {
  83343. babylonTexture.updateURL(texture.url);
  83344. });
  83345. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  83346. if (!image_1) {
  83347. throw new Error(context + ": Failed to find source " + texture.source);
  83348. }
  83349. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  83350. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  83351. texture.dataReadyObservable.notifyObservers(texture);
  83352. texture.dataReadyObservable = undefined;
  83353. });
  83354. }
  83355. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  83356. babylonTexture.wrapU = sampler.wrapU;
  83357. babylonTexture.wrapV = sampler.wrapV;
  83358. babylonTexture.name = texture.name || "texture" + texture.index;
  83359. if (this._parent.onTextureLoaded) {
  83360. this._parent.onTextureLoaded(babylonTexture);
  83361. }
  83362. return babylonTexture;
  83363. };
  83364. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  83365. if (sampler.noMipMaps != undefined) {
  83366. return;
  83367. }
  83368. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  83369. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  83370. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  83371. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  83372. };
  83373. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  83374. if (image.uri) {
  83375. this._loadUriAsync(context, image.uri, onSuccess);
  83376. }
  83377. else {
  83378. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  83379. if (!bufferView) {
  83380. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  83381. }
  83382. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  83383. }
  83384. };
  83385. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  83386. var _this = this;
  83387. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  83388. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  83389. return;
  83390. }
  83391. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  83392. throw new Error(context + ": Uri '" + uri + "' is invalid");
  83393. }
  83394. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  83395. _this._tryCatchOnError(function () {
  83396. onSuccess(new Uint8Array(data));
  83397. });
  83398. }, function (event) {
  83399. _this._tryCatchOnError(function () {
  83400. if (request && !_this._renderReady) {
  83401. request._lengthComputable = event.lengthComputable;
  83402. request._loaded = event.loaded;
  83403. request._total = event.total;
  83404. _this._onProgress();
  83405. }
  83406. });
  83407. }, this._babylonScene.database, true, function (request, exception) {
  83408. _this._tryCatchOnError(function () {
  83409. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  83410. });
  83411. }, function (oldRequest, newRequest) {
  83412. _this._requests.splice(_this._requests.indexOf(oldRequest), 1, newRequest);
  83413. });
  83414. if (request) {
  83415. this._requests.push(request);
  83416. }
  83417. };
  83418. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  83419. if (this._disposed) {
  83420. return;
  83421. }
  83422. try {
  83423. handler();
  83424. }
  83425. catch (e) {
  83426. BABYLON.Tools.Error("glTF Loader: " + e.message);
  83427. if (this._errorCallback) {
  83428. this._errorCallback(e.message, e);
  83429. }
  83430. this.dispose();
  83431. }
  83432. };
  83433. GLTFLoader._AssignIndices = function (array) {
  83434. if (array) {
  83435. for (var index = 0; index < array.length; index++) {
  83436. array[index].index = index;
  83437. }
  83438. }
  83439. };
  83440. GLTFLoader._GetProperty = function (array, index) {
  83441. if (!array || index == undefined || !array[index]) {
  83442. return null;
  83443. }
  83444. return array[index];
  83445. };
  83446. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  83447. // Set defaults if undefined
  83448. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  83449. switch (mode) {
  83450. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83451. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83452. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83453. default:
  83454. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  83455. return BABYLON.Texture.WRAP_ADDRESSMODE;
  83456. }
  83457. };
  83458. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  83459. // Set defaults if undefined
  83460. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  83461. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  83462. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  83463. switch (minFilter) {
  83464. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  83465. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  83466. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  83467. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  83468. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  83469. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  83470. default:
  83471. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  83472. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  83473. }
  83474. }
  83475. else {
  83476. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  83477. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  83478. }
  83479. switch (minFilter) {
  83480. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  83481. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  83482. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  83483. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  83484. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  83485. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  83486. default:
  83487. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  83488. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  83489. }
  83490. }
  83491. };
  83492. GLTFLoader._GetNumComponents = function (context, type) {
  83493. switch (type) {
  83494. case "SCALAR": return 1;
  83495. case "VEC2": return 2;
  83496. case "VEC3": return 3;
  83497. case "VEC4": return 4;
  83498. case "MAT2": return 4;
  83499. case "MAT3": return 9;
  83500. case "MAT4": return 16;
  83501. }
  83502. throw new Error(context + ": Invalid type " + type);
  83503. };
  83504. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  83505. var _this = this;
  83506. if (this._parent.useClipPlane) {
  83507. babylonMaterial.forceCompilation(babylonMesh, function () {
  83508. babylonMaterial.forceCompilation(babylonMesh, function () {
  83509. _this._tryCatchOnError(onSuccess);
  83510. }, { clipPlane: true });
  83511. });
  83512. }
  83513. else {
  83514. babylonMaterial.forceCompilation(babylonMesh, function () {
  83515. _this._tryCatchOnError(onSuccess);
  83516. });
  83517. }
  83518. };
  83519. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  83520. if (!this._parent.compileMaterials || !this._gltf.materials) {
  83521. onSuccess();
  83522. return;
  83523. }
  83524. var meshes = this._getMeshes();
  83525. var remaining = 0;
  83526. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  83527. var mesh = meshes_1[_i];
  83528. if (mesh.material instanceof BABYLON.MultiMaterial) {
  83529. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  83530. var subMaterial = _b[_a];
  83531. if (subMaterial) {
  83532. remaining++;
  83533. }
  83534. }
  83535. }
  83536. else if (mesh.material) {
  83537. remaining++;
  83538. }
  83539. }
  83540. if (remaining === 0) {
  83541. onSuccess();
  83542. return;
  83543. }
  83544. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  83545. var mesh = meshes_2[_c];
  83546. if (mesh.material instanceof BABYLON.MultiMaterial) {
  83547. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  83548. var subMaterial = _e[_d];
  83549. if (subMaterial) {
  83550. this._compileMaterialAsync(subMaterial, mesh, function () {
  83551. if (--remaining === 0) {
  83552. onSuccess();
  83553. }
  83554. });
  83555. }
  83556. }
  83557. }
  83558. else if (mesh.material) {
  83559. this._compileMaterialAsync(mesh.material, mesh, function () {
  83560. if (--remaining === 0) {
  83561. onSuccess();
  83562. }
  83563. });
  83564. }
  83565. }
  83566. };
  83567. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  83568. var _this = this;
  83569. if (!this._parent.compileShadowGenerators) {
  83570. onSuccess();
  83571. return;
  83572. }
  83573. var lights = this._babylonScene.lights;
  83574. var remaining = 0;
  83575. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  83576. var light = lights_1[_i];
  83577. var generator = light.getShadowGenerator();
  83578. if (generator) {
  83579. remaining++;
  83580. }
  83581. }
  83582. if (remaining === 0) {
  83583. onSuccess();
  83584. return;
  83585. }
  83586. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  83587. var light = lights_2[_a];
  83588. var generator = light.getShadowGenerator();
  83589. if (generator) {
  83590. generator.forceCompilation(function () {
  83591. if (--remaining === 0) {
  83592. _this._tryCatchOnError(onSuccess);
  83593. }
  83594. });
  83595. }
  83596. }
  83597. };
  83598. GLTFLoader.Extensions = {};
  83599. // IE 11 Compatibility.
  83600. GLTFLoader._createProgressEvent = (typeof window["ProgressEvent"] === "function")
  83601. ? function (lengthComputable, loaded, total) {
  83602. return new ProgressEvent("GLTFLoaderProgress", {
  83603. lengthComputable: lengthComputable,
  83604. loaded: loaded,
  83605. total: total
  83606. });
  83607. }
  83608. : function (lengthComputable, loaded, total) {
  83609. var event = document.createEvent("ProgressEvent");
  83610. event.initProgressEvent("GLTFLoaderProgress", false, false, lengthComputable, loaded, total);
  83611. return event;
  83612. };
  83613. return GLTFLoader;
  83614. }());
  83615. GLTF2.GLTFLoader = GLTFLoader;
  83616. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  83617. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83618. })(BABYLON || (BABYLON = {}));
  83619. //# sourceMappingURL=babylon.glTFLoader.js.map
  83620. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83621. var BABYLON;
  83622. (function (BABYLON) {
  83623. var GLTF2;
  83624. (function (GLTF2) {
  83625. /**
  83626. * Utils functions for GLTF
  83627. */
  83628. var GLTFUtils = /** @class */ (function () {
  83629. function GLTFUtils() {
  83630. }
  83631. /**
  83632. * If the uri is a base64 string
  83633. * @param uri: the uri to test
  83634. */
  83635. GLTFUtils.IsBase64 = function (uri) {
  83636. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  83637. };
  83638. /**
  83639. * Decode the base64 uri
  83640. * @param uri: the uri to decode
  83641. */
  83642. GLTFUtils.DecodeBase64 = function (uri) {
  83643. var decodedString = atob(uri.split(",")[1]);
  83644. var bufferLength = decodedString.length;
  83645. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  83646. for (var i = 0; i < bufferLength; i++) {
  83647. bufferView[i] = decodedString.charCodeAt(i);
  83648. }
  83649. return bufferView.buffer;
  83650. };
  83651. GLTFUtils.ValidateUri = function (uri) {
  83652. return (uri.indexOf("..") === -1);
  83653. };
  83654. return GLTFUtils;
  83655. }());
  83656. GLTF2.GLTFUtils = GLTFUtils;
  83657. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83658. })(BABYLON || (BABYLON = {}));
  83659. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  83660. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83661. var BABYLON;
  83662. (function (BABYLON) {
  83663. var GLTF2;
  83664. (function (GLTF2) {
  83665. var GLTFLoaderExtension = /** @class */ (function () {
  83666. function GLTFLoaderExtension() {
  83667. this.enabled = true;
  83668. }
  83669. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  83670. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  83671. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  83672. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  83673. var _this = this;
  83674. if (!property.extensions) {
  83675. return false;
  83676. }
  83677. var extension = property.extensions[this.name];
  83678. if (!extension) {
  83679. return false;
  83680. }
  83681. // Clear out the extension before executing the action to avoid recursing into the same property.
  83682. property.extensions[this.name] = undefined;
  83683. action(context + "extensions/" + this.name, extension, function () {
  83684. // Restore the extension after completing the action.
  83685. property.extensions[_this.name] = extension;
  83686. });
  83687. return true;
  83688. };
  83689. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  83690. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  83691. };
  83692. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  83693. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  83694. };
  83695. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  83696. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  83697. };
  83698. GLTFLoaderExtension._ApplyExtensions = function (action) {
  83699. var extensions = GLTFLoaderExtension._Extensions;
  83700. if (!extensions) {
  83701. return false;
  83702. }
  83703. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  83704. var extension = extensions_1[_i];
  83705. if (extension.enabled && action(extension)) {
  83706. return true;
  83707. }
  83708. }
  83709. return false;
  83710. };
  83711. //
  83712. // Utilities
  83713. //
  83714. GLTFLoaderExtension._Extensions = [];
  83715. return GLTFLoaderExtension;
  83716. }());
  83717. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  83718. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83719. })(BABYLON || (BABYLON = {}));
  83720. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  83721. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  83722. var BABYLON;
  83723. (function (BABYLON) {
  83724. var GLTF2;
  83725. (function (GLTF2) {
  83726. var Extensions;
  83727. (function (Extensions) {
  83728. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  83729. var MSFTLOD = /** @class */ (function (_super) {
  83730. __extends(MSFTLOD, _super);
  83731. function MSFTLOD() {
  83732. var _this = _super !== null && _super.apply(this, arguments) || this;
  83733. /**
  83734. * Specify the minimal delay between LODs in ms (default = 250)
  83735. */
  83736. _this.Delay = 250;
  83737. return _this;
  83738. }
  83739. Object.defineProperty(MSFTLOD.prototype, "name", {
  83740. get: function () {
  83741. return "MSFT_lod";
  83742. },
  83743. enumerable: true,
  83744. configurable: true
  83745. });
  83746. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  83747. return this._loadExtension(context, node, function (context, extension, onComplete) {
  83748. for (var i = extension.ids.length - 1; i >= 0; i--) {
  83749. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  83750. if (!lodNode) {
  83751. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  83752. }
  83753. loader._traverseNode(context, lodNode, action, parentNode);
  83754. }
  83755. loader._traverseNode(context, node, action, parentNode);
  83756. onComplete();
  83757. });
  83758. };
  83759. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  83760. var _this = this;
  83761. return this._loadExtension(context, node, function (context, extension, onComplete) {
  83762. var nodes = [node];
  83763. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  83764. var index = _a[_i];
  83765. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  83766. if (!lodNode) {
  83767. throw new Error(context + ": Failed to find node " + index);
  83768. }
  83769. nodes.push(lodNode);
  83770. }
  83771. loader._addLoaderPendingData(node);
  83772. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  83773. loader._removeLoaderPendingData(node);
  83774. onComplete();
  83775. });
  83776. });
  83777. };
  83778. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  83779. var _this = this;
  83780. loader._whenAction(function () {
  83781. loader._loadNode(context, nodes[index]);
  83782. }, function () {
  83783. if (index !== nodes.length - 1) {
  83784. var previousNode = nodes[index + 1];
  83785. previousNode.babylonMesh.setEnabled(false);
  83786. }
  83787. if (index === 0) {
  83788. onComplete();
  83789. return;
  83790. }
  83791. setTimeout(function () {
  83792. loader._tryCatchOnError(function () {
  83793. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  83794. });
  83795. }, _this.Delay);
  83796. });
  83797. };
  83798. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  83799. var _this = this;
  83800. return this._loadExtension(context, material, function (context, extension, onComplete) {
  83801. var materials = [material];
  83802. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  83803. var index = _a[_i];
  83804. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  83805. if (!lodMaterial) {
  83806. throw new Error(context + ": Failed to find material " + index);
  83807. }
  83808. materials.push(lodMaterial);
  83809. }
  83810. loader._addLoaderPendingData(material);
  83811. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  83812. loader._removeLoaderPendingData(material);
  83813. onComplete();
  83814. });
  83815. });
  83816. };
  83817. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  83818. var _this = this;
  83819. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  83820. if (index === materials.length - 1) {
  83821. assign(babylonMaterial, isNew);
  83822. // Load the next LOD when the loader is ready to render.
  83823. loader._executeWhenRenderReady(function () {
  83824. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  83825. });
  83826. }
  83827. else {
  83828. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  83829. assign(babylonMaterial, isNew);
  83830. if (index === 0) {
  83831. onComplete();
  83832. }
  83833. else {
  83834. setTimeout(function () {
  83835. loader._tryCatchOnError(function () {
  83836. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  83837. });
  83838. }, _this.Delay);
  83839. }
  83840. });
  83841. }
  83842. });
  83843. };
  83844. return MSFTLOD;
  83845. }(GLTF2.GLTFLoaderExtension));
  83846. Extensions.MSFTLOD = MSFTLOD;
  83847. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  83848. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  83849. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83850. })(BABYLON || (BABYLON = {}));
  83851. //# sourceMappingURL=MSFT_lod.js.map
  83852. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  83853. var BABYLON;
  83854. (function (BABYLON) {
  83855. var GLTF2;
  83856. (function (GLTF2) {
  83857. var Extensions;
  83858. (function (Extensions) {
  83859. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  83860. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  83861. function KHRMaterialsPbrSpecularGlossiness() {
  83862. return _super !== null && _super.apply(this, arguments) || this;
  83863. }
  83864. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  83865. get: function () {
  83866. return "KHR_materials_pbrSpecularGlossiness";
  83867. },
  83868. enumerable: true,
  83869. configurable: true
  83870. });
  83871. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  83872. var _this = this;
  83873. return this._loadExtension(context, material, function (context, extension, onComplete) {
  83874. loader._createPbrMaterial(material);
  83875. loader._loadMaterialBaseProperties(context, material);
  83876. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  83877. assign(material.babylonMaterial, true);
  83878. onComplete();
  83879. });
  83880. };
  83881. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  83882. var babylonMaterial = material.babylonMaterial;
  83883. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  83884. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  83885. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  83886. if (properties.diffuseTexture) {
  83887. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  83888. if (!texture) {
  83889. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  83890. }
  83891. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  83892. }
  83893. if (properties.specularGlossinessTexture) {
  83894. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  83895. if (!texture) {
  83896. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  83897. }
  83898. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  83899. babylonMaterial.reflectivityTexture.hasAlpha = true;
  83900. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  83901. }
  83902. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  83903. };
  83904. return KHRMaterialsPbrSpecularGlossiness;
  83905. }(GLTF2.GLTFLoaderExtension));
  83906. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  83907. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  83908. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  83909. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  83910. })(BABYLON || (BABYLON = {}));
  83911. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  83912. (function universalModuleDefinition(root, factory) {
  83913. var f = factory();
  83914. if (root && root["BABYLON"]) {
  83915. return;
  83916. }
  83917. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  83918. globalObject["BABYLON"] = f;
  83919. if(typeof exports === 'object' && typeof module === 'object')
  83920. module.exports = f;
  83921. else if(typeof define === 'function' && define.amd)
  83922. define(["BABYLON"], factory);
  83923. else if(typeof exports === 'object')
  83924. exports["BABYLON"] = f;
  83925. else {
  83926. root["BABYLON"] = f;
  83927. }
  83928. })(this, function() {
  83929. return BABYLON;
  83930. });