index.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361
  1. var __extends = (this && this.__extends) || (function () {
  2. var extendStatics = Object.setPrototypeOf ||
  3. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  5. return function (d, b) {
  6. extendStatics(d, b);
  7. function __() { this.constructor = d; }
  8. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9. };
  10. })();
  11. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14. 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;
  15. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16. };
  17. if(typeof require !== 'undefined'){
  18. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  19. var BABYLON = globalObject["BABYLON"] || {};
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var EffectFallbacks = /** @class */ (function () {
  23. function EffectFallbacks() {
  24. this._defines = {};
  25. this._currentRank = 32;
  26. this._maxRank = -1;
  27. }
  28. EffectFallbacks.prototype.unBindMesh = function () {
  29. this._mesh = null;
  30. };
  31. EffectFallbacks.prototype.addFallback = function (rank, define) {
  32. if (!this._defines[rank]) {
  33. if (rank < this._currentRank) {
  34. this._currentRank = rank;
  35. }
  36. if (rank > this._maxRank) {
  37. this._maxRank = rank;
  38. }
  39. this._defines[rank] = new Array();
  40. }
  41. this._defines[rank].push(define);
  42. };
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. get: function () {
  54. return this._currentRank <= this._maxRank;
  55. },
  56. enumerable: true,
  57. configurable: true
  58. });
  59. EffectFallbacks.prototype.reduce = function (currentDefines) {
  60. // First we try to switch to CPU skinning
  61. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  62. this._mesh.computeBonesUsingShaders = false;
  63. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  64. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  65. var scene = this._mesh.getScene();
  66. for (var index = 0; index < scene.meshes.length; index++) {
  67. var otherMesh = scene.meshes[index];
  68. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  69. otherMesh.computeBonesUsingShaders = false;
  70. }
  71. }
  72. }
  73. else {
  74. var currentFallbacks = this._defines[this._currentRank];
  75. if (currentFallbacks) {
  76. for (var index = 0; index < currentFallbacks.length; index++) {
  77. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  78. }
  79. }
  80. this._currentRank++;
  81. }
  82. return currentDefines;
  83. };
  84. return EffectFallbacks;
  85. }());
  86. BABYLON.EffectFallbacks = EffectFallbacks;
  87. var EffectCreationOptions = /** @class */ (function () {
  88. function EffectCreationOptions() {
  89. }
  90. return EffectCreationOptions;
  91. }());
  92. BABYLON.EffectCreationOptions = EffectCreationOptions;
  93. var Effect = /** @class */ (function () {
  94. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  95. if (samplers === void 0) { samplers = null; }
  96. if (defines === void 0) { defines = null; }
  97. if (fallbacks === void 0) { fallbacks = null; }
  98. if (onCompiled === void 0) { onCompiled = null; }
  99. if (onError === void 0) { onError = null; }
  100. var _this = this;
  101. this.uniqueId = 0;
  102. this.onCompileObservable = new BABYLON.Observable();
  103. this.onErrorObservable = new BABYLON.Observable();
  104. this.onBindObservable = new BABYLON.Observable();
  105. this._uniformBuffersNames = {};
  106. this._isReady = false;
  107. this._compilationError = "";
  108. this.name = baseName;
  109. if (attributesNamesOrOptions.attributes) {
  110. var options = attributesNamesOrOptions;
  111. this._engine = uniformsNamesOrEngine;
  112. this._attributesNames = options.attributes;
  113. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  114. this._samplers = options.samplers;
  115. this.defines = options.defines;
  116. this.onError = options.onError;
  117. this.onCompiled = options.onCompiled;
  118. this._fallbacks = options.fallbacks;
  119. this._indexParameters = options.indexParameters;
  120. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  121. if (options.uniformBuffersNames) {
  122. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  123. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  124. }
  125. }
  126. }
  127. else {
  128. this._engine = engine;
  129. this.defines = defines;
  130. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  131. this._samplers = samplers;
  132. this._attributesNames = attributesNamesOrOptions;
  133. this.onError = onError;
  134. this.onCompiled = onCompiled;
  135. this._indexParameters = indexParameters;
  136. this._fallbacks = fallbacks;
  137. }
  138. this.uniqueId = Effect._uniqueIdSeed++;
  139. var vertexSource;
  140. var fragmentSource;
  141. if (baseName.vertexElement) {
  142. vertexSource = document.getElementById(baseName.vertexElement);
  143. if (!vertexSource) {
  144. vertexSource = baseName.vertexElement;
  145. }
  146. }
  147. else {
  148. vertexSource = baseName.vertex || baseName;
  149. }
  150. if (baseName.fragmentElement) {
  151. fragmentSource = document.getElementById(baseName.fragmentElement);
  152. if (!fragmentSource) {
  153. fragmentSource = baseName.fragmentElement;
  154. }
  155. }
  156. else {
  157. fragmentSource = baseName.fragment || baseName;
  158. }
  159. this._loadVertexShader(vertexSource, function (vertexCode) {
  160. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  161. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  162. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  163. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  164. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  165. if (baseName) {
  166. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  167. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  168. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  169. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  170. }
  171. else {
  172. _this._vertexSourceCode = migratedVertexCode;
  173. _this._fragmentSourceCode = migratedFragmentCode;
  174. }
  175. _this._prepareEffect();
  176. });
  177. });
  178. });
  179. });
  180. });
  181. });
  182. }
  183. Object.defineProperty(Effect.prototype, "key", {
  184. get: function () {
  185. return this._key;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. // Properties
  191. Effect.prototype.isReady = function () {
  192. return this._isReady;
  193. };
  194. Effect.prototype.getEngine = function () {
  195. return this._engine;
  196. };
  197. Effect.prototype.getProgram = function () {
  198. return this._program;
  199. };
  200. Effect.prototype.getAttributesNames = function () {
  201. return this._attributesNames;
  202. };
  203. Effect.prototype.getAttributeLocation = function (index) {
  204. return this._attributes[index];
  205. };
  206. Effect.prototype.getAttributeLocationByName = function (name) {
  207. var index = this._attributesNames.indexOf(name);
  208. return this._attributes[index];
  209. };
  210. Effect.prototype.getAttributesCount = function () {
  211. return this._attributes.length;
  212. };
  213. Effect.prototype.getUniformIndex = function (uniformName) {
  214. return this._uniformsNames.indexOf(uniformName);
  215. };
  216. Effect.prototype.getUniform = function (uniformName) {
  217. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  218. };
  219. Effect.prototype.getSamplers = function () {
  220. return this._samplers;
  221. };
  222. Effect.prototype.getCompilationError = function () {
  223. return this._compilationError;
  224. };
  225. // Methods
  226. Effect.prototype.executeWhenCompiled = function (func) {
  227. if (this.isReady()) {
  228. func(this);
  229. return;
  230. }
  231. this.onCompileObservable.add(function (effect) {
  232. func(effect);
  233. });
  234. };
  235. Effect.prototype._loadVertexShader = function (vertex, callback) {
  236. if (BABYLON.Tools.IsWindowObjectExist()) {
  237. // DOM element ?
  238. if (vertex instanceof HTMLElement) {
  239. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  240. callback(vertexCode);
  241. return;
  242. }
  243. }
  244. // Base64 encoded ?
  245. if (vertex.substr(0, 7) === "base64:") {
  246. var vertexBinary = window.atob(vertex.substr(7));
  247. callback(vertexBinary);
  248. return;
  249. }
  250. // Is in local store ?
  251. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  252. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  253. return;
  254. }
  255. var vertexShaderUrl;
  256. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  257. vertexShaderUrl = vertex;
  258. }
  259. else {
  260. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  261. }
  262. // Vertex shader
  263. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  264. };
  265. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  266. if (BABYLON.Tools.IsWindowObjectExist()) {
  267. // DOM element ?
  268. if (fragment instanceof HTMLElement) {
  269. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  270. callback(fragmentCode);
  271. return;
  272. }
  273. }
  274. // Base64 encoded ?
  275. if (fragment.substr(0, 7) === "base64:") {
  276. var fragmentBinary = window.atob(fragment.substr(7));
  277. callback(fragmentBinary);
  278. return;
  279. }
  280. // Is in local store ?
  281. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  282. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  283. return;
  284. }
  285. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  286. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  287. return;
  288. }
  289. var fragmentShaderUrl;
  290. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  291. fragmentShaderUrl = fragment;
  292. }
  293. else {
  294. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  295. }
  296. // Fragment shader
  297. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  298. };
  299. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  300. // Rebuild shaders source code
  301. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  302. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  303. vertexCode = prefix + vertexCode;
  304. fragmentCode = prefix + fragmentCode;
  305. // Number lines of shaders source code
  306. var i = 2;
  307. var regex = /\n/gm;
  308. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  309. i = 2;
  310. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  311. // Dump shaders name and formatted source code
  312. if (this.name.vertexElement) {
  313. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  314. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  315. }
  316. else if (this.name.vertex) {
  317. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  318. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  319. }
  320. else {
  321. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  322. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  323. }
  324. };
  325. ;
  326. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  327. var preparedSourceCode = this._processPrecision(sourceCode);
  328. if (this._engine.webGLVersion == 1) {
  329. callback(preparedSourceCode);
  330. return;
  331. }
  332. // Already converted
  333. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  334. callback(preparedSourceCode.replace("#version 300 es", ""));
  335. return;
  336. }
  337. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  338. // Remove extensions
  339. // #extension GL_OES_standard_derivatives : enable
  340. // #extension GL_EXT_shader_texture_lod : enable
  341. // #extension GL_EXT_frag_depth : enable
  342. // #extension GL_EXT_draw_buffers : require
  343. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  344. var result = preparedSourceCode.replace(regex, "");
  345. // Migrate to GLSL v300
  346. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  347. result = result.replace(/attribute[ \t]/g, "in ");
  348. result = result.replace(/[ \t]attribute/g, " in");
  349. if (isFragment) {
  350. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  351. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  352. result = result.replace(/texture2D\s*\(/g, "texture(");
  353. result = result.replace(/textureCube\s*\(/g, "texture(");
  354. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  355. result = result.replace(/gl_FragColor/g, "glFragColor");
  356. result = result.replace(/gl_FragData/g, "glFragData");
  357. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  358. }
  359. callback(result);
  360. };
  361. Effect.prototype._processIncludes = function (sourceCode, callback) {
  362. var _this = this;
  363. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  364. var match = regex.exec(sourceCode);
  365. var returnValue = new String(sourceCode);
  366. while (match != null) {
  367. var includeFile = match[1];
  368. // Uniform declaration
  369. if (includeFile.indexOf("__decl__") !== -1) {
  370. includeFile = includeFile.replace(/__decl__/, "");
  371. if (this._engine.supportsUniformBuffers) {
  372. includeFile = includeFile.replace(/Vertex/, "Ubo");
  373. includeFile = includeFile.replace(/Fragment/, "Ubo");
  374. }
  375. includeFile = includeFile + "Declaration";
  376. }
  377. if (Effect.IncludesShadersStore[includeFile]) {
  378. // Substitution
  379. var includeContent = Effect.IncludesShadersStore[includeFile];
  380. if (match[2]) {
  381. var splits = match[3].split(",");
  382. for (var index = 0; index < splits.length; index += 2) {
  383. var source = new RegExp(splits[index], "g");
  384. var dest = splits[index + 1];
  385. includeContent = includeContent.replace(source, dest);
  386. }
  387. }
  388. if (match[4]) {
  389. var indexString = match[5];
  390. if (indexString.indexOf("..") !== -1) {
  391. var indexSplits = indexString.split("..");
  392. var minIndex = parseInt(indexSplits[0]);
  393. var maxIndex = parseInt(indexSplits[1]);
  394. var sourceIncludeContent = includeContent.slice(0);
  395. includeContent = "";
  396. if (isNaN(maxIndex)) {
  397. maxIndex = this._indexParameters[indexSplits[1]];
  398. }
  399. for (var i = minIndex; i < maxIndex; i++) {
  400. if (!this._engine.supportsUniformBuffers) {
  401. // Ubo replacement
  402. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  403. return p1 + "{X}";
  404. });
  405. }
  406. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  407. }
  408. }
  409. else {
  410. if (!this._engine.supportsUniformBuffers) {
  411. // Ubo replacement
  412. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  413. return p1 + "{X}";
  414. });
  415. }
  416. includeContent = includeContent.replace(/\{X\}/g, indexString);
  417. }
  418. }
  419. // Replace
  420. returnValue = returnValue.replace(match[0], includeContent);
  421. }
  422. else {
  423. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  424. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  425. Effect.IncludesShadersStore[includeFile] = fileContent;
  426. _this._processIncludes(returnValue, callback);
  427. });
  428. return;
  429. }
  430. match = regex.exec(sourceCode);
  431. }
  432. callback(returnValue);
  433. };
  434. Effect.prototype._processPrecision = function (source) {
  435. if (source.indexOf("precision highp float") === -1) {
  436. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  437. source = "precision mediump float;\n" + source;
  438. }
  439. else {
  440. source = "precision highp float;\n" + source;
  441. }
  442. }
  443. else {
  444. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  445. source = source.replace("precision highp float", "precision mediump float");
  446. }
  447. }
  448. return source;
  449. };
  450. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  451. var _this = this;
  452. this._isReady = false;
  453. this._vertexSourceCodeOverride = vertexSourceCode;
  454. this._fragmentSourceCodeOverride = fragmentSourceCode;
  455. this.onError = function (effect, error) {
  456. if (onError) {
  457. onError(error);
  458. }
  459. };
  460. this.onCompiled = function () {
  461. var scenes = _this.getEngine().scenes;
  462. for (var i = 0; i < scenes.length; i++) {
  463. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  464. }
  465. if (onCompiled) {
  466. onCompiled(_this._program);
  467. }
  468. };
  469. this._fallbacks = null;
  470. this._prepareEffect();
  471. };
  472. Effect.prototype.getSpecificUniformLocations = function (names) {
  473. var engine = this._engine;
  474. return engine.getUniforms(this._program, names);
  475. };
  476. Effect.prototype._prepareEffect = function () {
  477. var attributesNames = this._attributesNames;
  478. var defines = this.defines;
  479. var fallbacks = this._fallbacks;
  480. this._valueCache = {};
  481. var previousProgram = this._program;
  482. try {
  483. var engine = this._engine;
  484. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  485. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  486. }
  487. else {
  488. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  489. }
  490. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  491. if (engine.supportsUniformBuffers) {
  492. for (var name in this._uniformBuffersNames) {
  493. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  494. }
  495. }
  496. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  497. this._attributes = engine.getAttributes(this._program, attributesNames);
  498. var index;
  499. for (index = 0; index < this._samplers.length; index++) {
  500. var sampler = this.getUniform(this._samplers[index]);
  501. if (sampler == null) {
  502. this._samplers.splice(index, 1);
  503. index--;
  504. }
  505. }
  506. engine.bindSamplers(this);
  507. this._compilationError = "";
  508. this._isReady = true;
  509. if (this.onCompiled) {
  510. this.onCompiled(this);
  511. }
  512. this.onCompileObservable.notifyObservers(this);
  513. this.onCompileObservable.clear();
  514. // Unbind mesh reference in fallbacks
  515. if (this._fallbacks) {
  516. this._fallbacks.unBindMesh();
  517. }
  518. if (previousProgram) {
  519. this.getEngine()._deleteProgram(previousProgram);
  520. }
  521. }
  522. catch (e) {
  523. this._compilationError = e.message;
  524. // Let's go through fallbacks then
  525. BABYLON.Tools.Error("Unable to compile effect:");
  526. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  527. return " " + uniform;
  528. }));
  529. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  530. return " " + attribute;
  531. }));
  532. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  533. BABYLON.Tools.Error("Error: " + this._compilationError);
  534. if (previousProgram) {
  535. this._program = previousProgram;
  536. this._isReady = true;
  537. if (this.onError) {
  538. this.onError(this, this._compilationError);
  539. }
  540. this.onErrorObservable.notifyObservers(this);
  541. }
  542. if (fallbacks && fallbacks.isMoreFallbacks) {
  543. BABYLON.Tools.Error("Trying next fallback.");
  544. this.defines = fallbacks.reduce(this.defines);
  545. this._prepareEffect();
  546. }
  547. else {
  548. if (this.onError) {
  549. this.onError(this, this._compilationError);
  550. }
  551. this.onErrorObservable.notifyObservers(this);
  552. this.onErrorObservable.clear();
  553. // Unbind mesh reference in fallbacks
  554. if (this._fallbacks) {
  555. this._fallbacks.unBindMesh();
  556. }
  557. }
  558. }
  559. };
  560. Object.defineProperty(Effect.prototype, "isSupported", {
  561. get: function () {
  562. return this._compilationError === "";
  563. },
  564. enumerable: true,
  565. configurable: true
  566. });
  567. Effect.prototype._bindTexture = function (channel, texture) {
  568. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  569. };
  570. Effect.prototype.setTexture = function (channel, texture) {
  571. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  572. };
  573. Effect.prototype.setTextureArray = function (channel, textures) {
  574. if (this._samplers.indexOf(channel + "Ex") === -1) {
  575. var initialPos = this._samplers.indexOf(channel);
  576. for (var index = 1; index < textures.length; index++) {
  577. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  578. }
  579. }
  580. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  581. };
  582. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  583. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  584. };
  585. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  586. var cache = this._valueCache[uniformName];
  587. var flag = matrix.updateFlag;
  588. if (cache !== undefined && cache === flag) {
  589. return false;
  590. }
  591. this._valueCache[uniformName] = flag;
  592. return true;
  593. };
  594. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  595. var cache = this._valueCache[uniformName];
  596. if (!cache) {
  597. cache = [x, y];
  598. this._valueCache[uniformName] = cache;
  599. return true;
  600. }
  601. var changed = false;
  602. if (cache[0] !== x) {
  603. cache[0] = x;
  604. changed = true;
  605. }
  606. if (cache[1] !== y) {
  607. cache[1] = y;
  608. changed = true;
  609. }
  610. return changed;
  611. };
  612. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  613. var cache = this._valueCache[uniformName];
  614. if (!cache) {
  615. cache = [x, y, z];
  616. this._valueCache[uniformName] = cache;
  617. return true;
  618. }
  619. var changed = false;
  620. if (cache[0] !== x) {
  621. cache[0] = x;
  622. changed = true;
  623. }
  624. if (cache[1] !== y) {
  625. cache[1] = y;
  626. changed = true;
  627. }
  628. if (cache[2] !== z) {
  629. cache[2] = z;
  630. changed = true;
  631. }
  632. return changed;
  633. };
  634. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  635. var cache = this._valueCache[uniformName];
  636. if (!cache) {
  637. cache = [x, y, z, w];
  638. this._valueCache[uniformName] = cache;
  639. return true;
  640. }
  641. var changed = false;
  642. if (cache[0] !== x) {
  643. cache[0] = x;
  644. changed = true;
  645. }
  646. if (cache[1] !== y) {
  647. cache[1] = y;
  648. changed = true;
  649. }
  650. if (cache[2] !== z) {
  651. cache[2] = z;
  652. changed = true;
  653. }
  654. if (cache[3] !== w) {
  655. cache[3] = w;
  656. changed = true;
  657. }
  658. return changed;
  659. };
  660. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  661. var bufferName = this._uniformBuffersNames[name];
  662. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  663. return;
  664. }
  665. Effect._baseCache[bufferName] = buffer;
  666. this._engine.bindUniformBufferBase(buffer, bufferName);
  667. };
  668. Effect.prototype.bindUniformBlock = function (blockName, index) {
  669. this._engine.bindUniformBlock(this._program, blockName, index);
  670. };
  671. Effect.prototype.setInt = function (uniformName, value) {
  672. var cache = this._valueCache[uniformName];
  673. if (cache !== undefined && cache === value)
  674. return this;
  675. this._valueCache[uniformName] = value;
  676. this._engine.setInt(this.getUniform(uniformName), value);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setIntArray2 = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setIntArray2(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setIntArray3 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setIntArray3(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setIntArray4 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setIntArray4(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setArray2 = function (uniformName, array) {
  725. this._valueCache[uniformName] = null;
  726. this._engine.setArray2(this.getUniform(uniformName), array);
  727. return this;
  728. };
  729. Effect.prototype.setArray3 = function (uniformName, array) {
  730. this._valueCache[uniformName] = null;
  731. this._engine.setArray3(this.getUniform(uniformName), array);
  732. return this;
  733. };
  734. Effect.prototype.setArray4 = function (uniformName, array) {
  735. this._valueCache[uniformName] = null;
  736. this._engine.setArray4(this.getUniform(uniformName), array);
  737. return this;
  738. };
  739. Effect.prototype.setMatrices = function (uniformName, matrices) {
  740. if (!matrices) {
  741. return this;
  742. }
  743. this._valueCache[uniformName] = null;
  744. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  745. return this;
  746. };
  747. Effect.prototype.setMatrix = function (uniformName, matrix) {
  748. if (this._cacheMatrix(uniformName, matrix)) {
  749. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  750. }
  751. return this;
  752. };
  753. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  754. this._valueCache[uniformName] = null;
  755. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  756. return this;
  757. };
  758. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  759. this._valueCache[uniformName] = null;
  760. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  761. return this;
  762. };
  763. Effect.prototype.setFloat = function (uniformName, value) {
  764. var cache = this._valueCache[uniformName];
  765. if (cache !== undefined && cache === value)
  766. return this;
  767. this._valueCache[uniformName] = value;
  768. this._engine.setFloat(this.getUniform(uniformName), value);
  769. return this;
  770. };
  771. Effect.prototype.setBool = function (uniformName, bool) {
  772. var cache = this._valueCache[uniformName];
  773. if (cache !== undefined && cache === bool)
  774. return this;
  775. this._valueCache[uniformName] = bool;
  776. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  777. return this;
  778. };
  779. Effect.prototype.setVector2 = function (uniformName, vector2) {
  780. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  781. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  782. }
  783. return this;
  784. };
  785. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  786. if (this._cacheFloat2(uniformName, x, y)) {
  787. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  788. }
  789. return this;
  790. };
  791. Effect.prototype.setVector3 = function (uniformName, vector3) {
  792. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  793. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  794. }
  795. return this;
  796. };
  797. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  798. if (this._cacheFloat3(uniformName, x, y, z)) {
  799. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  800. }
  801. return this;
  802. };
  803. Effect.prototype.setVector4 = function (uniformName, vector4) {
  804. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  805. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  806. }
  807. return this;
  808. };
  809. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  810. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  811. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  812. }
  813. return this;
  814. };
  815. Effect.prototype.setColor3 = function (uniformName, color3) {
  816. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  817. this._engine.setColor3(this.getUniform(uniformName), color3);
  818. }
  819. return this;
  820. };
  821. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  822. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  823. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  824. }
  825. return this;
  826. };
  827. Effect.ResetCache = function () {
  828. Effect._baseCache = {};
  829. };
  830. Effect._uniqueIdSeed = 0;
  831. Effect._baseCache = {};
  832. // Statics
  833. Effect.ShadersStore = {};
  834. Effect.IncludesShadersStore = {};
  835. return Effect;
  836. }());
  837. BABYLON.Effect = Effect;
  838. })(BABYLON || (BABYLON = {}));
  839. //# sourceMappingURL=babylon.effect.js.map
  840. //# sourceMappingURL=babylon.types.js.map
  841. 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}";
  842. BABYLON.Effect.ShadersStore['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}";
  843. var BABYLON;
  844. (function (BABYLON) {
  845. var KeyboardEventTypes = /** @class */ (function () {
  846. function KeyboardEventTypes() {
  847. }
  848. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  849. get: function () {
  850. return KeyboardEventTypes._KEYDOWN;
  851. },
  852. enumerable: true,
  853. configurable: true
  854. });
  855. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  856. get: function () {
  857. return KeyboardEventTypes._KEYUP;
  858. },
  859. enumerable: true,
  860. configurable: true
  861. });
  862. KeyboardEventTypes._KEYDOWN = 0x01;
  863. KeyboardEventTypes._KEYUP = 0x02;
  864. return KeyboardEventTypes;
  865. }());
  866. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  867. var KeyboardInfo = /** @class */ (function () {
  868. function KeyboardInfo(type, event) {
  869. this.type = type;
  870. this.event = event;
  871. }
  872. return KeyboardInfo;
  873. }());
  874. BABYLON.KeyboardInfo = KeyboardInfo;
  875. /**
  876. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  877. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  878. */
  879. var KeyboardInfoPre = /** @class */ (function (_super) {
  880. __extends(KeyboardInfoPre, _super);
  881. function KeyboardInfoPre(type, event) {
  882. var _this = _super.call(this, type, event) || this;
  883. _this.skipOnPointerObservable = false;
  884. return _this;
  885. }
  886. return KeyboardInfoPre;
  887. }(KeyboardInfo));
  888. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  889. })(BABYLON || (BABYLON = {}));
  890. //# sourceMappingURL=babylon.keyboardEvents.js.map
  891. var BABYLON;
  892. (function (BABYLON) {
  893. var PointerEventTypes = /** @class */ (function () {
  894. function PointerEventTypes() {
  895. }
  896. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  897. get: function () {
  898. return PointerEventTypes._POINTERDOWN;
  899. },
  900. enumerable: true,
  901. configurable: true
  902. });
  903. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  904. get: function () {
  905. return PointerEventTypes._POINTERUP;
  906. },
  907. enumerable: true,
  908. configurable: true
  909. });
  910. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  911. get: function () {
  912. return PointerEventTypes._POINTERMOVE;
  913. },
  914. enumerable: true,
  915. configurable: true
  916. });
  917. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  918. get: function () {
  919. return PointerEventTypes._POINTERWHEEL;
  920. },
  921. enumerable: true,
  922. configurable: true
  923. });
  924. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  925. get: function () {
  926. return PointerEventTypes._POINTERPICK;
  927. },
  928. enumerable: true,
  929. configurable: true
  930. });
  931. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  932. get: function () {
  933. return PointerEventTypes._POINTERTAP;
  934. },
  935. enumerable: true,
  936. configurable: true
  937. });
  938. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  939. get: function () {
  940. return PointerEventTypes._POINTERDOUBLETAP;
  941. },
  942. enumerable: true,
  943. configurable: true
  944. });
  945. PointerEventTypes._POINTERDOWN = 0x01;
  946. PointerEventTypes._POINTERUP = 0x02;
  947. PointerEventTypes._POINTERMOVE = 0x04;
  948. PointerEventTypes._POINTERWHEEL = 0x08;
  949. PointerEventTypes._POINTERPICK = 0x10;
  950. PointerEventTypes._POINTERTAP = 0x20;
  951. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  952. return PointerEventTypes;
  953. }());
  954. BABYLON.PointerEventTypes = PointerEventTypes;
  955. var PointerInfoBase = /** @class */ (function () {
  956. function PointerInfoBase(type, event) {
  957. this.type = type;
  958. this.event = event;
  959. }
  960. return PointerInfoBase;
  961. }());
  962. BABYLON.PointerInfoBase = PointerInfoBase;
  963. /**
  964. * This class is used to store pointer related info for the onPrePointerObservable event.
  965. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  966. */
  967. var PointerInfoPre = /** @class */ (function (_super) {
  968. __extends(PointerInfoPre, _super);
  969. function PointerInfoPre(type, event, localX, localY) {
  970. var _this = _super.call(this, type, event) || this;
  971. _this.skipOnPointerObservable = false;
  972. _this.localPosition = new BABYLON.Vector2(localX, localY);
  973. return _this;
  974. }
  975. return PointerInfoPre;
  976. }(PointerInfoBase));
  977. BABYLON.PointerInfoPre = PointerInfoPre;
  978. /**
  979. * This type contains all the data related to a pointer event in Babylon.js.
  980. * 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.
  981. */
  982. var PointerInfo = /** @class */ (function (_super) {
  983. __extends(PointerInfo, _super);
  984. function PointerInfo(type, event, pickInfo) {
  985. var _this = _super.call(this, type, event) || this;
  986. _this.pickInfo = pickInfo;
  987. return _this;
  988. }
  989. return PointerInfo;
  990. }(PointerInfoBase));
  991. BABYLON.PointerInfo = PointerInfo;
  992. })(BABYLON || (BABYLON = {}));
  993. //# sourceMappingURL=babylon.pointerEvents.js.map
  994. var BABYLON;
  995. (function (BABYLON) {
  996. BABYLON.ToGammaSpace = 1 / 2.2;
  997. BABYLON.ToLinearSpace = 2.2;
  998. BABYLON.Epsilon = 0.001;
  999. var Color3 = /** @class */ (function () {
  1000. /**
  1001. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  1002. */
  1003. function Color3(r, g, b) {
  1004. if (r === void 0) { r = 0; }
  1005. if (g === void 0) { g = 0; }
  1006. if (b === void 0) { b = 0; }
  1007. this.r = r;
  1008. this.g = g;
  1009. this.b = b;
  1010. }
  1011. /**
  1012. * Returns a string with the Color3 current values.
  1013. */
  1014. Color3.prototype.toString = function () {
  1015. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1016. };
  1017. /**
  1018. * Returns the string "Color3".
  1019. */
  1020. Color3.prototype.getClassName = function () {
  1021. return "Color3";
  1022. };
  1023. /**
  1024. * Returns the Color3 hash code.
  1025. */
  1026. Color3.prototype.getHashCode = function () {
  1027. var hash = this.r || 0;
  1028. hash = (hash * 397) ^ (this.g || 0);
  1029. hash = (hash * 397) ^ (this.b || 0);
  1030. return hash;
  1031. };
  1032. // Operators
  1033. /**
  1034. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1035. * Returns the Color3.
  1036. */
  1037. Color3.prototype.toArray = function (array, index) {
  1038. if (index === undefined) {
  1039. index = 0;
  1040. }
  1041. array[index] = this.r;
  1042. array[index + 1] = this.g;
  1043. array[index + 2] = this.b;
  1044. return this;
  1045. };
  1046. /**
  1047. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1048. */
  1049. Color3.prototype.toColor4 = function (alpha) {
  1050. if (alpha === void 0) { alpha = 1; }
  1051. return new Color4(this.r, this.g, this.b, alpha);
  1052. };
  1053. /**
  1054. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1055. */
  1056. Color3.prototype.asArray = function () {
  1057. var result = new Array();
  1058. this.toArray(result, 0);
  1059. return result;
  1060. };
  1061. /**
  1062. * Returns the luminance value (float).
  1063. */
  1064. Color3.prototype.toLuminance = function () {
  1065. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1066. };
  1067. /**
  1068. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1069. * Returns this new object.
  1070. */
  1071. Color3.prototype.multiply = function (otherColor) {
  1072. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1073. };
  1074. /**
  1075. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1076. * Returns the current Color3.
  1077. */
  1078. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1079. result.r = this.r * otherColor.r;
  1080. result.g = this.g * otherColor.g;
  1081. result.b = this.b * otherColor.b;
  1082. return this;
  1083. };
  1084. /**
  1085. * Boolean : True if the rgb values are equal to the passed ones.
  1086. */
  1087. Color3.prototype.equals = function (otherColor) {
  1088. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1089. };
  1090. /**
  1091. * Boolean : True if the rgb values are equal to the passed ones.
  1092. */
  1093. Color3.prototype.equalsFloats = function (r, g, b) {
  1094. return this.r === r && this.g === g && this.b === b;
  1095. };
  1096. /**
  1097. * Multiplies in place each rgb value by scale.
  1098. * Returns the updated Color3.
  1099. */
  1100. Color3.prototype.scale = function (scale) {
  1101. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1102. };
  1103. /**
  1104. * Multiplies the rgb values by scale and stores the result into "result".
  1105. * Returns the unmodified current Color3.
  1106. */
  1107. Color3.prototype.scaleToRef = function (scale, result) {
  1108. result.r = this.r * scale;
  1109. result.g = this.g * scale;
  1110. result.b = this.b * scale;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1115. */
  1116. Color3.prototype.add = function (otherColor) {
  1117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1118. };
  1119. /**
  1120. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1121. * Returns the unmodified current Color3.
  1122. */
  1123. Color3.prototype.addToRef = function (otherColor, result) {
  1124. result.r = this.r + otherColor.r;
  1125. result.g = this.g + otherColor.g;
  1126. result.b = this.b + otherColor.b;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1131. */
  1132. Color3.prototype.subtract = function (otherColor) {
  1133. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1134. };
  1135. /**
  1136. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1137. * Returns the unmodified current Color3.
  1138. */
  1139. Color3.prototype.subtractToRef = function (otherColor, result) {
  1140. result.r = this.r - otherColor.r;
  1141. result.g = this.g - otherColor.g;
  1142. result.b = this.b - otherColor.b;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Color3 copied the current one.
  1147. */
  1148. Color3.prototype.clone = function () {
  1149. return new Color3(this.r, this.g, this.b);
  1150. };
  1151. /**
  1152. * Copies the rgb values from the source in the current Color3.
  1153. * Returns the updated Color3.
  1154. */
  1155. Color3.prototype.copyFrom = function (source) {
  1156. this.r = source.r;
  1157. this.g = source.g;
  1158. this.b = source.b;
  1159. return this;
  1160. };
  1161. /**
  1162. * Updates the Color3 rgb values from the passed floats.
  1163. * Returns the Color3.
  1164. */
  1165. Color3.prototype.copyFromFloats = function (r, g, b) {
  1166. this.r = r;
  1167. this.g = g;
  1168. this.b = b;
  1169. return this;
  1170. };
  1171. /**
  1172. * Updates the Color3 rgb values from the passed floats.
  1173. * Returns the Color3.
  1174. */
  1175. Color3.prototype.set = function (r, g, b) {
  1176. return this.copyFromFloats(r, g, b);
  1177. };
  1178. /**
  1179. * Returns the Color3 hexadecimal code as a string.
  1180. */
  1181. Color3.prototype.toHexString = function () {
  1182. var intR = (this.r * 255) | 0;
  1183. var intG = (this.g * 255) | 0;
  1184. var intB = (this.b * 255) | 0;
  1185. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1186. };
  1187. /**
  1188. * Returns a new Color3 converted to linear space.
  1189. */
  1190. Color3.prototype.toLinearSpace = function () {
  1191. var convertedColor = new Color3();
  1192. this.toLinearSpaceToRef(convertedColor);
  1193. return convertedColor;
  1194. };
  1195. /**
  1196. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1197. * Returns the unmodified Color3.
  1198. */
  1199. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1200. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1201. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1202. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1203. return this;
  1204. };
  1205. /**
  1206. * Returns a new Color3 converted to gamma space.
  1207. */
  1208. Color3.prototype.toGammaSpace = function () {
  1209. var convertedColor = new Color3();
  1210. this.toGammaSpaceToRef(convertedColor);
  1211. return convertedColor;
  1212. };
  1213. /**
  1214. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1215. * Returns the unmodified Color3.
  1216. */
  1217. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1218. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1219. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1220. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1221. return this;
  1222. };
  1223. // Statics
  1224. /**
  1225. * Creates a new Color3 from the string containing valid hexadecimal values.
  1226. */
  1227. Color3.FromHexString = function (hex) {
  1228. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1229. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1230. return new Color3(0, 0, 0);
  1231. }
  1232. var r = parseInt(hex.substring(1, 3), 16);
  1233. var g = parseInt(hex.substring(3, 5), 16);
  1234. var b = parseInt(hex.substring(5, 7), 16);
  1235. return Color3.FromInts(r, g, b);
  1236. };
  1237. /**
  1238. * Creates a new Vector3 from the startind index of the passed array.
  1239. */
  1240. Color3.FromArray = function (array, offset) {
  1241. if (offset === void 0) { offset = 0; }
  1242. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1243. };
  1244. /**
  1245. * Creates a new Color3 from integer values ( < 256).
  1246. */
  1247. Color3.FromInts = function (r, g, b) {
  1248. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1249. };
  1250. /**
  1251. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1252. */
  1253. Color3.Lerp = function (start, end, amount) {
  1254. var r = start.r + ((end.r - start.r) * amount);
  1255. var g = start.g + ((end.g - start.g) * amount);
  1256. var b = start.b + ((end.b - start.b) * amount);
  1257. return new Color3(r, g, b);
  1258. };
  1259. Color3.Red = function () { return new Color3(1, 0, 0); };
  1260. Color3.Green = function () { return new Color3(0, 1, 0); };
  1261. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1262. Color3.Black = function () { return new Color3(0, 0, 0); };
  1263. Color3.White = function () { return new Color3(1, 1, 1); };
  1264. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1265. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1266. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1267. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1268. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1269. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1270. return Color3;
  1271. }());
  1272. BABYLON.Color3 = Color3;
  1273. var Color4 = /** @class */ (function () {
  1274. /**
  1275. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1276. */
  1277. function Color4(r, g, b, a) {
  1278. if (r === void 0) { r = 0; }
  1279. if (g === void 0) { g = 0; }
  1280. if (b === void 0) { b = 0; }
  1281. if (a === void 0) { a = 1; }
  1282. this.r = r;
  1283. this.g = g;
  1284. this.b = b;
  1285. this.a = a;
  1286. }
  1287. // Operators
  1288. /**
  1289. * Adds in place the passed Color4 values to the current Color4.
  1290. * Returns the updated Color4.
  1291. */
  1292. Color4.prototype.addInPlace = function (right) {
  1293. this.r += right.r;
  1294. this.g += right.g;
  1295. this.b += right.b;
  1296. this.a += right.a;
  1297. return this;
  1298. };
  1299. /**
  1300. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1301. */
  1302. Color4.prototype.asArray = function () {
  1303. var result = new Array();
  1304. this.toArray(result, 0);
  1305. return result;
  1306. };
  1307. /**
  1308. * Stores from the starting index in the passed array the Color4 successive values.
  1309. * Returns the Color4.
  1310. */
  1311. Color4.prototype.toArray = function (array, index) {
  1312. if (index === undefined) {
  1313. index = 0;
  1314. }
  1315. array[index] = this.r;
  1316. array[index + 1] = this.g;
  1317. array[index + 2] = this.b;
  1318. array[index + 3] = this.a;
  1319. return this;
  1320. };
  1321. /**
  1322. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1323. */
  1324. Color4.prototype.add = function (right) {
  1325. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1326. };
  1327. /**
  1328. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1329. */
  1330. Color4.prototype.subtract = function (right) {
  1331. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1332. };
  1333. /**
  1334. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1335. * Returns the Color4.
  1336. */
  1337. Color4.prototype.subtractToRef = function (right, result) {
  1338. result.r = this.r - right.r;
  1339. result.g = this.g - right.g;
  1340. result.b = this.b - right.b;
  1341. result.a = this.a - right.a;
  1342. return this;
  1343. };
  1344. /**
  1345. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1346. */
  1347. Color4.prototype.scale = function (scale) {
  1348. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1349. };
  1350. /**
  1351. * Multiplies the current Color4 values by scale and stores the result in "result".
  1352. * Returns the Color4.
  1353. */
  1354. Color4.prototype.scaleToRef = function (scale, result) {
  1355. result.r = this.r * scale;
  1356. result.g = this.g * scale;
  1357. result.b = this.b * scale;
  1358. result.a = this.a * scale;
  1359. return this;
  1360. };
  1361. /**
  1362. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1363. * @param color The Color4 (RGBA) value to multiply by
  1364. * @returns A new Color4.
  1365. */
  1366. Color4.prototype.multiply = function (color) {
  1367. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1368. };
  1369. /**
  1370. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1371. * @param color The Color4 (RGBA) value to multiply by
  1372. * @param result The Color4 (RGBA) to fill the result in
  1373. * @returns the result Color4.
  1374. */
  1375. Color4.prototype.multiplyToRef = function (color, result) {
  1376. result.r = this.r * color.r;
  1377. result.g = this.g * color.g;
  1378. result.b = this.b * color.b;
  1379. result.a = this.a * color.a;
  1380. return result;
  1381. };
  1382. /**
  1383. * Returns a string with the Color4 values.
  1384. */
  1385. Color4.prototype.toString = function () {
  1386. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1387. };
  1388. /**
  1389. * Returns the string "Color4"
  1390. */
  1391. Color4.prototype.getClassName = function () {
  1392. return "Color4";
  1393. };
  1394. /**
  1395. * Return the Color4 hash code as a number.
  1396. */
  1397. Color4.prototype.getHashCode = function () {
  1398. var hash = this.r || 0;
  1399. hash = (hash * 397) ^ (this.g || 0);
  1400. hash = (hash * 397) ^ (this.b || 0);
  1401. hash = (hash * 397) ^ (this.a || 0);
  1402. return hash;
  1403. };
  1404. /**
  1405. * Creates a new Color4 copied from the current one.
  1406. */
  1407. Color4.prototype.clone = function () {
  1408. return new Color4(this.r, this.g, this.b, this.a);
  1409. };
  1410. /**
  1411. * Copies the passed Color4 values into the current one.
  1412. * Returns the updated Color4.
  1413. */
  1414. Color4.prototype.copyFrom = function (source) {
  1415. this.r = source.r;
  1416. this.g = source.g;
  1417. this.b = source.b;
  1418. this.a = source.a;
  1419. return this;
  1420. };
  1421. /**
  1422. * Copies the passed float values into the current one.
  1423. * Returns the updated Color4.
  1424. */
  1425. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1426. this.r = r;
  1427. this.g = g;
  1428. this.b = b;
  1429. this.a = a;
  1430. return this;
  1431. };
  1432. /**
  1433. * Copies the passed float values into the current one.
  1434. * Returns the updated Color4.
  1435. */
  1436. Color4.prototype.set = function (r, g, b, a) {
  1437. return this.copyFromFloats(r, g, b, a);
  1438. };
  1439. /**
  1440. * Returns a string containing the hexadecimal Color4 code.
  1441. */
  1442. Color4.prototype.toHexString = function () {
  1443. var intR = (this.r * 255) | 0;
  1444. var intG = (this.g * 255) | 0;
  1445. var intB = (this.b * 255) | 0;
  1446. var intA = (this.a * 255) | 0;
  1447. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1448. };
  1449. /**
  1450. * Returns a new Color4 converted to linear space.
  1451. */
  1452. Color4.prototype.toLinearSpace = function () {
  1453. var convertedColor = new Color4();
  1454. this.toLinearSpaceToRef(convertedColor);
  1455. return convertedColor;
  1456. };
  1457. /**
  1458. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1459. * Returns the unmodified Color4.
  1460. */
  1461. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1462. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1463. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1464. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1465. convertedColor.a = this.a;
  1466. return this;
  1467. };
  1468. /**
  1469. * Returns a new Color4 converted to gamma space.
  1470. */
  1471. Color4.prototype.toGammaSpace = function () {
  1472. var convertedColor = new Color4();
  1473. this.toGammaSpaceToRef(convertedColor);
  1474. return convertedColor;
  1475. };
  1476. /**
  1477. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1478. * Returns the unmodified Color4.
  1479. */
  1480. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1481. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1482. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1483. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1484. convertedColor.a = this.a;
  1485. return this;
  1486. };
  1487. // Statics
  1488. /**
  1489. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1490. */
  1491. Color4.FromHexString = function (hex) {
  1492. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1493. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1494. return new Color4(0.0, 0.0, 0.0, 0.0);
  1495. }
  1496. var r = parseInt(hex.substring(1, 3), 16);
  1497. var g = parseInt(hex.substring(3, 5), 16);
  1498. var b = parseInt(hex.substring(5, 7), 16);
  1499. var a = parseInt(hex.substring(7, 9), 16);
  1500. return Color4.FromInts(r, g, b, a);
  1501. };
  1502. /**
  1503. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1504. */
  1505. Color4.Lerp = function (left, right, amount) {
  1506. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1507. Color4.LerpToRef(left, right, amount, result);
  1508. return result;
  1509. };
  1510. /**
  1511. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1512. */
  1513. Color4.LerpToRef = function (left, right, amount, result) {
  1514. result.r = left.r + (right.r - left.r) * amount;
  1515. result.g = left.g + (right.g - left.g) * amount;
  1516. result.b = left.b + (right.b - left.b) * amount;
  1517. result.a = left.a + (right.a - left.a) * amount;
  1518. };
  1519. /**
  1520. * Creates a new Color4 from the starting index element of the passed array.
  1521. */
  1522. Color4.FromArray = function (array, offset) {
  1523. if (offset === void 0) { offset = 0; }
  1524. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1525. };
  1526. /**
  1527. * Creates a new Color4 from the passed integers ( < 256 ).
  1528. */
  1529. Color4.FromInts = function (r, g, b, a) {
  1530. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1531. };
  1532. Color4.CheckColors4 = function (colors, count) {
  1533. // Check if color3 was used
  1534. if (colors.length === count * 3) {
  1535. var colors4 = [];
  1536. for (var index = 0; index < colors.length; index += 3) {
  1537. var newIndex = (index / 3) * 4;
  1538. colors4[newIndex] = colors[index];
  1539. colors4[newIndex + 1] = colors[index + 1];
  1540. colors4[newIndex + 2] = colors[index + 2];
  1541. colors4[newIndex + 3] = 1.0;
  1542. }
  1543. return colors4;
  1544. }
  1545. return colors;
  1546. };
  1547. return Color4;
  1548. }());
  1549. BABYLON.Color4 = Color4;
  1550. var Vector2 = /** @class */ (function () {
  1551. /**
  1552. * Creates a new Vector2 from the passed x and y coordinates.
  1553. */
  1554. function Vector2(x, y) {
  1555. this.x = x;
  1556. this.y = y;
  1557. }
  1558. /**
  1559. * Returns a string with the Vector2 coordinates.
  1560. */
  1561. Vector2.prototype.toString = function () {
  1562. return "{X: " + this.x + " Y:" + this.y + "}";
  1563. };
  1564. /**
  1565. * Returns the string "Vector2"
  1566. */
  1567. Vector2.prototype.getClassName = function () {
  1568. return "Vector2";
  1569. };
  1570. /**
  1571. * Returns the Vector2 hash code as a number.
  1572. */
  1573. Vector2.prototype.getHashCode = function () {
  1574. var hash = this.x || 0;
  1575. hash = (hash * 397) ^ (this.y || 0);
  1576. return hash;
  1577. };
  1578. // Operators
  1579. /**
  1580. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1581. * Returns the Vector2.
  1582. */
  1583. Vector2.prototype.toArray = function (array, index) {
  1584. if (index === void 0) { index = 0; }
  1585. array[index] = this.x;
  1586. array[index + 1] = this.y;
  1587. return this;
  1588. };
  1589. /**
  1590. * Returns a new array with 2 elements : the Vector2 coordinates.
  1591. */
  1592. Vector2.prototype.asArray = function () {
  1593. var result = new Array();
  1594. this.toArray(result, 0);
  1595. return result;
  1596. };
  1597. /**
  1598. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1599. * Returns the updated Vector2.
  1600. */
  1601. Vector2.prototype.copyFrom = function (source) {
  1602. this.x = source.x;
  1603. this.y = source.y;
  1604. return this;
  1605. };
  1606. /**
  1607. * Sets the Vector2 coordinates with the passed floats.
  1608. * Returns the updated Vector2.
  1609. */
  1610. Vector2.prototype.copyFromFloats = function (x, y) {
  1611. this.x = x;
  1612. this.y = y;
  1613. return this;
  1614. };
  1615. /**
  1616. * Sets the Vector2 coordinates with the passed floats.
  1617. * Returns the updated Vector2.
  1618. */
  1619. Vector2.prototype.set = function (x, y) {
  1620. return this.copyFromFloats(x, y);
  1621. };
  1622. /**
  1623. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1624. */
  1625. Vector2.prototype.add = function (otherVector) {
  1626. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1627. };
  1628. /**
  1629. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1630. * Returns the Vector2.
  1631. */
  1632. Vector2.prototype.addToRef = function (otherVector, result) {
  1633. result.x = this.x + otherVector.x;
  1634. result.y = this.y + otherVector.y;
  1635. return this;
  1636. };
  1637. /**
  1638. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1639. * Returns the updated Vector2.
  1640. */
  1641. Vector2.prototype.addInPlace = function (otherVector) {
  1642. this.x += otherVector.x;
  1643. this.y += otherVector.y;
  1644. return this;
  1645. };
  1646. /**
  1647. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1648. */
  1649. Vector2.prototype.addVector3 = function (otherVector) {
  1650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1651. };
  1652. /**
  1653. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1654. */
  1655. Vector2.prototype.subtract = function (otherVector) {
  1656. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1657. };
  1658. /**
  1659. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1660. * Returns the Vector2.
  1661. */
  1662. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1663. result.x = this.x - otherVector.x;
  1664. result.y = this.y - otherVector.y;
  1665. return this;
  1666. };
  1667. /**
  1668. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1669. * Returns the updated Vector2.
  1670. */
  1671. Vector2.prototype.subtractInPlace = function (otherVector) {
  1672. this.x -= otherVector.x;
  1673. this.y -= otherVector.y;
  1674. return this;
  1675. };
  1676. /**
  1677. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1678. * Returns the updated Vector2.
  1679. */
  1680. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1681. this.x *= otherVector.x;
  1682. this.y *= otherVector.y;
  1683. return this;
  1684. };
  1685. /**
  1686. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1687. */
  1688. Vector2.prototype.multiply = function (otherVector) {
  1689. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1690. };
  1691. /**
  1692. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1693. * Returns the Vector2.
  1694. */
  1695. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1696. result.x = this.x * otherVector.x;
  1697. result.y = this.y * otherVector.y;
  1698. return this;
  1699. };
  1700. /**
  1701. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1702. */
  1703. Vector2.prototype.multiplyByFloats = function (x, y) {
  1704. return new Vector2(this.x * x, this.y * y);
  1705. };
  1706. /**
  1707. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1708. */
  1709. Vector2.prototype.divide = function (otherVector) {
  1710. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1711. };
  1712. /**
  1713. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1714. * Returns the Vector2.
  1715. */
  1716. Vector2.prototype.divideToRef = function (otherVector, result) {
  1717. result.x = this.x / otherVector.x;
  1718. result.y = this.y / otherVector.y;
  1719. return this;
  1720. };
  1721. /**
  1722. * Divides the current Vector3 coordinates by the passed ones.
  1723. * Returns the updated Vector3.
  1724. */
  1725. Vector2.prototype.divideInPlace = function (otherVector) {
  1726. return this.divideToRef(otherVector, this);
  1727. };
  1728. /**
  1729. * Returns a new Vector2 with current Vector2 negated coordinates.
  1730. */
  1731. Vector2.prototype.negate = function () {
  1732. return new Vector2(-this.x, -this.y);
  1733. };
  1734. /**
  1735. * Multiply the Vector2 coordinates by scale.
  1736. * Returns the updated Vector2.
  1737. */
  1738. Vector2.prototype.scaleInPlace = function (scale) {
  1739. this.x *= scale;
  1740. this.y *= scale;
  1741. return this;
  1742. };
  1743. /**
  1744. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1745. */
  1746. Vector2.prototype.scale = function (scale) {
  1747. return new Vector2(this.x * scale, this.y * scale);
  1748. };
  1749. /**
  1750. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1751. */
  1752. Vector2.prototype.equals = function (otherVector) {
  1753. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1754. };
  1755. /**
  1756. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1757. */
  1758. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1759. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1760. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1761. };
  1762. // Properties
  1763. /**
  1764. * Returns the vector length (float).
  1765. */
  1766. Vector2.prototype.length = function () {
  1767. return Math.sqrt(this.x * this.x + this.y * this.y);
  1768. };
  1769. /**
  1770. * Returns the vector squared length (float);
  1771. */
  1772. Vector2.prototype.lengthSquared = function () {
  1773. return (this.x * this.x + this.y * this.y);
  1774. };
  1775. // Methods
  1776. /**
  1777. * Normalize the vector.
  1778. * Returns the updated Vector2.
  1779. */
  1780. Vector2.prototype.normalize = function () {
  1781. var len = this.length();
  1782. if (len === 0)
  1783. return this;
  1784. var num = 1.0 / len;
  1785. this.x *= num;
  1786. this.y *= num;
  1787. return this;
  1788. };
  1789. /**
  1790. * Returns a new Vector2 copied from the Vector2.
  1791. */
  1792. Vector2.prototype.clone = function () {
  1793. return new Vector2(this.x, this.y);
  1794. };
  1795. // Statics
  1796. /**
  1797. * Returns a new Vector2(0, 0)
  1798. */
  1799. Vector2.Zero = function () {
  1800. return new Vector2(0, 0);
  1801. };
  1802. /**
  1803. * Returns a new Vector2(1, 1)
  1804. */
  1805. Vector2.One = function () {
  1806. return new Vector2(1, 1);
  1807. };
  1808. /**
  1809. * Returns a new Vector2 set from the passed index element of the passed array.
  1810. */
  1811. Vector2.FromArray = function (array, offset) {
  1812. if (offset === void 0) { offset = 0; }
  1813. return new Vector2(array[offset], array[offset + 1]);
  1814. };
  1815. /**
  1816. * Sets "result" from the passed index element of the passed array.
  1817. */
  1818. Vector2.FromArrayToRef = function (array, offset, result) {
  1819. result.x = array[offset];
  1820. result.y = array[offset + 1];
  1821. };
  1822. /**
  1823. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1824. */
  1825. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1826. var squared = amount * amount;
  1827. var cubed = amount * squared;
  1828. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1829. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1830. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1831. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1832. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1833. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1834. return new Vector2(x, y);
  1835. };
  1836. /**
  1837. * 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".
  1838. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1839. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1840. */
  1841. Vector2.Clamp = function (value, min, max) {
  1842. var x = value.x;
  1843. x = (x > max.x) ? max.x : x;
  1844. x = (x < min.x) ? min.x : x;
  1845. var y = value.y;
  1846. y = (y > max.y) ? max.y : y;
  1847. y = (y < min.y) ? min.y : y;
  1848. return new Vector2(x, y);
  1849. };
  1850. /**
  1851. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1852. */
  1853. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1854. var squared = amount * amount;
  1855. var cubed = amount * squared;
  1856. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1857. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1858. var part3 = (cubed - (2.0 * squared)) + amount;
  1859. var part4 = cubed - squared;
  1860. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1861. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1862. return new Vector2(x, y);
  1863. };
  1864. /**
  1865. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1866. */
  1867. Vector2.Lerp = function (start, end, amount) {
  1868. var x = start.x + ((end.x - start.x) * amount);
  1869. var y = start.y + ((end.y - start.y) * amount);
  1870. return new Vector2(x, y);
  1871. };
  1872. /**
  1873. * Returns the dot product (float) of the vector "left" and the vector "right".
  1874. */
  1875. Vector2.Dot = function (left, right) {
  1876. return left.x * right.x + left.y * right.y;
  1877. };
  1878. /**
  1879. * Returns a new Vector2 equal to the normalized passed vector.
  1880. */
  1881. Vector2.Normalize = function (vector) {
  1882. var newVector = vector.clone();
  1883. newVector.normalize();
  1884. return newVector;
  1885. };
  1886. /**
  1887. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1888. */
  1889. Vector2.Minimize = function (left, right) {
  1890. var x = (left.x < right.x) ? left.x : right.x;
  1891. var y = (left.y < right.y) ? left.y : right.y;
  1892. return new Vector2(x, y);
  1893. };
  1894. /**
  1895. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1896. */
  1897. Vector2.Maximize = function (left, right) {
  1898. var x = (left.x > right.x) ? left.x : right.x;
  1899. var y = (left.y > right.y) ? left.y : right.y;
  1900. return new Vector2(x, y);
  1901. };
  1902. /**
  1903. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1904. */
  1905. Vector2.Transform = function (vector, transformation) {
  1906. var r = Vector2.Zero();
  1907. Vector2.TransformToRef(vector, transformation, r);
  1908. return r;
  1909. };
  1910. /**
  1911. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1912. */
  1913. Vector2.TransformToRef = function (vector, transformation, result) {
  1914. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1915. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1916. result.x = x;
  1917. result.y = y;
  1918. };
  1919. /**
  1920. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1921. */
  1922. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1923. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1924. var sign = a < 0 ? -1 : 1;
  1925. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1926. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1927. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1928. };
  1929. /**
  1930. * Returns the distance (float) between the vectors "value1" and "value2".
  1931. */
  1932. Vector2.Distance = function (value1, value2) {
  1933. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1934. };
  1935. /**
  1936. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1937. */
  1938. Vector2.DistanceSquared = function (value1, value2) {
  1939. var x = value1.x - value2.x;
  1940. var y = value1.y - value2.y;
  1941. return (x * x) + (y * y);
  1942. };
  1943. /**
  1944. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1945. */
  1946. Vector2.Center = function (value1, value2) {
  1947. var center = value1.add(value2);
  1948. center.scaleInPlace(0.5);
  1949. return center;
  1950. };
  1951. /**
  1952. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1953. */
  1954. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1955. var l2 = Vector2.DistanceSquared(segA, segB);
  1956. if (l2 === 0.0) {
  1957. return Vector2.Distance(p, segA);
  1958. }
  1959. var v = segB.subtract(segA);
  1960. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1961. var proj = segA.add(v.multiplyByFloats(t, t));
  1962. return Vector2.Distance(p, proj);
  1963. };
  1964. return Vector2;
  1965. }());
  1966. BABYLON.Vector2 = Vector2;
  1967. var Vector3 = /** @class */ (function () {
  1968. /**
  1969. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1970. * A Vector3 is the main object used in 3D geometry.
  1971. * It can represent etiher the coordinates of a point the space, either a direction.
  1972. */
  1973. function Vector3(x, y, z) {
  1974. this.x = x;
  1975. this.y = y;
  1976. this.z = z;
  1977. }
  1978. /**
  1979. * Returns a string with the Vector3 coordinates.
  1980. */
  1981. Vector3.prototype.toString = function () {
  1982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1983. };
  1984. /**
  1985. * Returns the string "Vector3"
  1986. */
  1987. Vector3.prototype.getClassName = function () {
  1988. return "Vector3";
  1989. };
  1990. /**
  1991. * Returns the Vector hash code.
  1992. */
  1993. Vector3.prototype.getHashCode = function () {
  1994. var hash = this.x || 0;
  1995. hash = (hash * 397) ^ (this.y || 0);
  1996. hash = (hash * 397) ^ (this.z || 0);
  1997. return hash;
  1998. };
  1999. // Operators
  2000. /**
  2001. * Returns a new array with three elements : the coordinates the Vector3.
  2002. */
  2003. Vector3.prototype.asArray = function () {
  2004. var result = [];
  2005. this.toArray(result, 0);
  2006. return result;
  2007. };
  2008. /**
  2009. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2010. * Returns the Vector3.
  2011. */
  2012. Vector3.prototype.toArray = function (array, index) {
  2013. if (index === void 0) { index = 0; }
  2014. array[index] = this.x;
  2015. array[index + 1] = this.y;
  2016. array[index + 2] = this.z;
  2017. return this;
  2018. };
  2019. /**
  2020. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2021. */
  2022. Vector3.prototype.toQuaternion = function () {
  2023. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2024. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2025. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2026. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2027. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2028. var cosy = Math.cos(this.y * 0.5);
  2029. var siny = Math.sin(this.y * 0.5);
  2030. result.x = coszMinusx * siny;
  2031. result.y = -sinzMinusx * siny;
  2032. result.z = sinxPlusz * cosy;
  2033. result.w = cosxPlusz * cosy;
  2034. return result;
  2035. };
  2036. /**
  2037. * Adds the passed vector to the current Vector3.
  2038. * Returns the updated Vector3.
  2039. */
  2040. Vector3.prototype.addInPlace = function (otherVector) {
  2041. this.x += otherVector.x;
  2042. this.y += otherVector.y;
  2043. this.z += otherVector.z;
  2044. return this;
  2045. };
  2046. /**
  2047. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2048. */
  2049. Vector3.prototype.add = function (otherVector) {
  2050. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2051. };
  2052. /**
  2053. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2054. * Returns the current Vector3.
  2055. */
  2056. Vector3.prototype.addToRef = function (otherVector, result) {
  2057. result.x = this.x + otherVector.x;
  2058. result.y = this.y + otherVector.y;
  2059. result.z = this.z + otherVector.z;
  2060. return this;
  2061. };
  2062. /**
  2063. * Subtract the passed vector from the current Vector3.
  2064. * Returns the updated Vector3.
  2065. */
  2066. Vector3.prototype.subtractInPlace = function (otherVector) {
  2067. this.x -= otherVector.x;
  2068. this.y -= otherVector.y;
  2069. this.z -= otherVector.z;
  2070. return this;
  2071. };
  2072. /**
  2073. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2074. */
  2075. Vector3.prototype.subtract = function (otherVector) {
  2076. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2077. };
  2078. /**
  2079. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2080. * Returns the current Vector3.
  2081. */
  2082. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2083. result.x = this.x - otherVector.x;
  2084. result.y = this.y - otherVector.y;
  2085. result.z = this.z - otherVector.z;
  2086. return this;
  2087. };
  2088. /**
  2089. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2090. */
  2091. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2092. return new Vector3(this.x - x, this.y - y, this.z - z);
  2093. };
  2094. /**
  2095. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2096. * Returns the current Vector3.
  2097. */
  2098. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2099. result.x = this.x - x;
  2100. result.y = this.y - y;
  2101. result.z = this.z - z;
  2102. return this;
  2103. };
  2104. /**
  2105. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2106. */
  2107. Vector3.prototype.negate = function () {
  2108. return new Vector3(-this.x, -this.y, -this.z);
  2109. };
  2110. /**
  2111. * Multiplies the Vector3 coordinates by the float "scale".
  2112. * Returns the updated Vector3.
  2113. */
  2114. Vector3.prototype.scaleInPlace = function (scale) {
  2115. this.x *= scale;
  2116. this.y *= scale;
  2117. this.z *= scale;
  2118. return this;
  2119. };
  2120. /**
  2121. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2122. */
  2123. Vector3.prototype.scale = function (scale) {
  2124. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2125. };
  2126. /**
  2127. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2128. * Returns the current Vector3.
  2129. */
  2130. Vector3.prototype.scaleToRef = function (scale, result) {
  2131. result.x = this.x * scale;
  2132. result.y = this.y * scale;
  2133. result.z = this.z * scale;
  2134. return this;
  2135. };
  2136. /**
  2137. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2138. */
  2139. Vector3.prototype.equals = function (otherVector) {
  2140. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2141. };
  2142. /**
  2143. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2144. */
  2145. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2146. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2147. 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);
  2148. };
  2149. /**
  2150. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2151. */
  2152. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2153. return this.x === x && this.y === y && this.z === z;
  2154. };
  2155. /**
  2156. * Muliplies the current Vector3 coordinates by the passed ones.
  2157. * Returns the updated Vector3.
  2158. */
  2159. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2160. this.x *= otherVector.x;
  2161. this.y *= otherVector.y;
  2162. this.z *= otherVector.z;
  2163. return this;
  2164. };
  2165. /**
  2166. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2167. */
  2168. Vector3.prototype.multiply = function (otherVector) {
  2169. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2170. };
  2171. /**
  2172. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2173. * Returns the current Vector3.
  2174. */
  2175. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2176. result.x = this.x * otherVector.x;
  2177. result.y = this.y * otherVector.y;
  2178. result.z = this.z * otherVector.z;
  2179. return this;
  2180. };
  2181. /**
  2182. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2183. */
  2184. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2185. return new Vector3(this.x * x, this.y * y, this.z * z);
  2186. };
  2187. /**
  2188. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2189. */
  2190. Vector3.prototype.divide = function (otherVector) {
  2191. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2192. };
  2193. /**
  2194. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2195. * Returns the current Vector3.
  2196. */
  2197. Vector3.prototype.divideToRef = function (otherVector, result) {
  2198. result.x = this.x / otherVector.x;
  2199. result.y = this.y / otherVector.y;
  2200. result.z = this.z / otherVector.z;
  2201. return this;
  2202. };
  2203. /**
  2204. * Divides the current Vector3 coordinates by the passed ones.
  2205. * Returns the updated Vector3.
  2206. */
  2207. Vector3.prototype.divideInPlace = function (otherVector) {
  2208. return this.divideToRef(otherVector, this);
  2209. };
  2210. /**
  2211. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2212. * Returns the updated Vector3.
  2213. */
  2214. Vector3.prototype.MinimizeInPlace = function (other) {
  2215. if (other.x < this.x)
  2216. this.x = other.x;
  2217. if (other.y < this.y)
  2218. this.y = other.y;
  2219. if (other.z < this.z)
  2220. this.z = other.z;
  2221. return this;
  2222. };
  2223. /**
  2224. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2225. * Returns the updated Vector3.
  2226. */
  2227. Vector3.prototype.MaximizeInPlace = function (other) {
  2228. if (other.x > this.x)
  2229. this.x = other.x;
  2230. if (other.y > this.y)
  2231. this.y = other.y;
  2232. if (other.z > this.z)
  2233. this.z = other.z;
  2234. return this;
  2235. };
  2236. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2237. /**
  2238. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2239. */
  2240. get: function () {
  2241. var absX = Math.abs(this.x);
  2242. var absY = Math.abs(this.y);
  2243. if (absX !== absY) {
  2244. return true;
  2245. }
  2246. var absZ = Math.abs(this.z);
  2247. if (absX !== absZ) {
  2248. return true;
  2249. }
  2250. if (absY !== absZ) {
  2251. return true;
  2252. }
  2253. return false;
  2254. },
  2255. enumerable: true,
  2256. configurable: true
  2257. });
  2258. // Properties
  2259. /**
  2260. * Returns the length of the Vector3 (float).
  2261. */
  2262. Vector3.prototype.length = function () {
  2263. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2264. };
  2265. /**
  2266. * Returns the squared length of the Vector3 (float).
  2267. */
  2268. Vector3.prototype.lengthSquared = function () {
  2269. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2270. };
  2271. /**
  2272. * Normalize the current Vector3.
  2273. * Returns the updated Vector3.
  2274. * /!\ In place operation.
  2275. */
  2276. Vector3.prototype.normalize = function () {
  2277. var len = this.length();
  2278. if (len === 0 || len === 1.0)
  2279. return this;
  2280. var num = 1.0 / len;
  2281. this.x *= num;
  2282. this.y *= num;
  2283. this.z *= num;
  2284. return this;
  2285. };
  2286. /**
  2287. * Normalize the current Vector3 to a new vector.
  2288. * @returns the new Vector3.
  2289. */
  2290. Vector3.prototype.normalizeToNew = function () {
  2291. var normalized = new Vector3(0, 0, 0);
  2292. this.normalizeToRef(normalized);
  2293. return normalized;
  2294. };
  2295. /**
  2296. * Normalize the current Vector3 to the reference.
  2297. * @param the reference to update.
  2298. * @returns the updated Vector3.
  2299. */
  2300. Vector3.prototype.normalizeToRef = function (reference) {
  2301. var len = this.length();
  2302. if (len === 0 || len === 1.0) {
  2303. reference.set(this.x, this.y, this.z);
  2304. return reference;
  2305. }
  2306. var scale = 1.0 / len;
  2307. this.scaleToRef(scale, reference);
  2308. return reference;
  2309. };
  2310. /**
  2311. * Returns a new Vector3 copied from the current Vector3.
  2312. */
  2313. Vector3.prototype.clone = function () {
  2314. return new Vector3(this.x, this.y, this.z);
  2315. };
  2316. /**
  2317. * Copies the passed vector coordinates to the current Vector3 ones.
  2318. * Returns the updated Vector3.
  2319. */
  2320. Vector3.prototype.copyFrom = function (source) {
  2321. this.x = source.x;
  2322. this.y = source.y;
  2323. this.z = source.z;
  2324. return this;
  2325. };
  2326. /**
  2327. * Copies the passed floats to the current Vector3 coordinates.
  2328. * Returns the updated Vector3.
  2329. */
  2330. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2331. this.x = x;
  2332. this.y = y;
  2333. this.z = z;
  2334. return this;
  2335. };
  2336. /**
  2337. * Copies the passed floats to the current Vector3 coordinates.
  2338. * Returns the updated Vector3.
  2339. */
  2340. Vector3.prototype.set = function (x, y, z) {
  2341. return this.copyFromFloats(x, y, z);
  2342. };
  2343. // Statics
  2344. /**
  2345. *
  2346. */
  2347. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2348. var d0 = Vector3.Dot(vector0, axis) - size;
  2349. var d1 = Vector3.Dot(vector1, axis) - size;
  2350. var s = d0 / (d0 - d1);
  2351. return s;
  2352. };
  2353. /**
  2354. * Returns a new Vector3 set from the index "offset" of the passed array.
  2355. */
  2356. Vector3.FromArray = function (array, offset) {
  2357. if (!offset) {
  2358. offset = 0;
  2359. }
  2360. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2361. };
  2362. /**
  2363. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2364. * This function is deprecated. Use FromArray instead.
  2365. */
  2366. Vector3.FromFloatArray = function (array, offset) {
  2367. return Vector3.FromArray(array, offset);
  2368. };
  2369. /**
  2370. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2371. */
  2372. Vector3.FromArrayToRef = function (array, offset, result) {
  2373. result.x = array[offset];
  2374. result.y = array[offset + 1];
  2375. result.z = array[offset + 2];
  2376. };
  2377. /**
  2378. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2379. * This function is deprecated. Use FromArrayToRef instead.
  2380. */
  2381. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2382. return Vector3.FromArrayToRef(array, offset, result);
  2383. };
  2384. /**
  2385. * Sets the passed vector "result" with the passed floats.
  2386. */
  2387. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2388. result.x = x;
  2389. result.y = y;
  2390. result.z = z;
  2391. };
  2392. /**
  2393. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2394. */
  2395. Vector3.Zero = function () {
  2396. return new Vector3(0.0, 0.0, 0.0);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2400. */
  2401. Vector3.One = function () {
  2402. return new Vector3(1.0, 1.0, 1.0);
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2406. */
  2407. Vector3.Up = function () {
  2408. return new Vector3(0.0, 1.0, 0.0);
  2409. };
  2410. /**
  2411. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2412. */
  2413. Vector3.Forward = function () {
  2414. return new Vector3(0.0, 0.0, 1.0);
  2415. };
  2416. /**
  2417. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2418. */
  2419. Vector3.Right = function () {
  2420. return new Vector3(1.0, 0.0, 0.0);
  2421. };
  2422. /**
  2423. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2424. */
  2425. Vector3.Left = function () {
  2426. return new Vector3(-1.0, 0.0, 0.0);
  2427. };
  2428. /**
  2429. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2430. * This method computes tranformed coordinates only, not transformed direction vectors.
  2431. */
  2432. Vector3.TransformCoordinates = function (vector, transformation) {
  2433. var result = Vector3.Zero();
  2434. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2435. return result;
  2436. };
  2437. /**
  2438. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2439. * This method computes tranformed coordinates only, not transformed direction vectors.
  2440. */
  2441. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2442. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2443. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2444. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2445. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2446. result.x = x / w;
  2447. result.y = y / w;
  2448. result.z = z / w;
  2449. };
  2450. /**
  2451. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2452. * This method computes tranformed coordinates only, not transformed direction vectors.
  2453. */
  2454. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2455. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2456. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2457. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2458. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2459. result.x = rx / rw;
  2460. result.y = ry / rw;
  2461. result.z = rz / rw;
  2462. };
  2463. /**
  2464. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2465. * This methods computes transformed normalized direction vectors only.
  2466. */
  2467. Vector3.TransformNormal = function (vector, transformation) {
  2468. var result = Vector3.Zero();
  2469. Vector3.TransformNormalToRef(vector, transformation, result);
  2470. return result;
  2471. };
  2472. /**
  2473. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2474. * This methods computes transformed normalized direction vectors only.
  2475. */
  2476. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2477. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2478. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2479. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2480. result.x = x;
  2481. result.y = y;
  2482. result.z = z;
  2483. };
  2484. /**
  2485. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2486. * This methods computes transformed normalized direction vectors only.
  2487. */
  2488. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2489. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2490. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2491. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2492. };
  2493. /**
  2494. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2495. */
  2496. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2497. var squared = amount * amount;
  2498. var cubed = amount * squared;
  2499. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2500. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2501. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2502. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2503. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2504. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2505. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2506. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2507. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2508. return new Vector3(x, y, z);
  2509. };
  2510. /**
  2511. * 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".
  2512. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2513. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2514. */
  2515. Vector3.Clamp = function (value, min, max) {
  2516. var x = value.x;
  2517. x = (x > max.x) ? max.x : x;
  2518. x = (x < min.x) ? min.x : x;
  2519. var y = value.y;
  2520. y = (y > max.y) ? max.y : y;
  2521. y = (y < min.y) ? min.y : y;
  2522. var z = value.z;
  2523. z = (z > max.z) ? max.z : z;
  2524. z = (z < min.z) ? min.z : z;
  2525. return new Vector3(x, y, z);
  2526. };
  2527. /**
  2528. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2529. */
  2530. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2531. var squared = amount * amount;
  2532. var cubed = amount * squared;
  2533. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2534. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2535. var part3 = (cubed - (2.0 * squared)) + amount;
  2536. var part4 = cubed - squared;
  2537. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2538. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2539. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2540. return new Vector3(x, y, z);
  2541. };
  2542. /**
  2543. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2544. */
  2545. Vector3.Lerp = function (start, end, amount) {
  2546. var result = new Vector3(0, 0, 0);
  2547. Vector3.LerpToRef(start, end, amount, result);
  2548. return result;
  2549. };
  2550. /**
  2551. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2552. */
  2553. Vector3.LerpToRef = function (start, end, amount, result) {
  2554. result.x = start.x + ((end.x - start.x) * amount);
  2555. result.y = start.y + ((end.y - start.y) * amount);
  2556. result.z = start.z + ((end.z - start.z) * amount);
  2557. };
  2558. /**
  2559. * Returns the dot product (float) between the vectors "left" and "right".
  2560. */
  2561. Vector3.Dot = function (left, right) {
  2562. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2563. };
  2564. /**
  2565. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2566. * The cross product is then orthogonal to both "left" and "right".
  2567. */
  2568. Vector3.Cross = function (left, right) {
  2569. var result = Vector3.Zero();
  2570. Vector3.CrossToRef(left, right, result);
  2571. return result;
  2572. };
  2573. /**
  2574. * Sets the passed vector "result" with the cross product of "left" and "right".
  2575. * The cross product is then orthogonal to both "left" and "right".
  2576. */
  2577. Vector3.CrossToRef = function (left, right, result) {
  2578. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2579. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2580. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2581. result.copyFrom(MathTmp.Vector3[0]);
  2582. };
  2583. /**
  2584. * Returns a new Vector3 as the normalization of the passed vector.
  2585. */
  2586. Vector3.Normalize = function (vector) {
  2587. var result = Vector3.Zero();
  2588. Vector3.NormalizeToRef(vector, result);
  2589. return result;
  2590. };
  2591. /**
  2592. * Sets the passed vector "result" with the normalization of the passed first vector.
  2593. */
  2594. Vector3.NormalizeToRef = function (vector, result) {
  2595. result.copyFrom(vector);
  2596. result.normalize();
  2597. };
  2598. Vector3.Project = function (vector, world, transform, viewport) {
  2599. var cw = viewport.width;
  2600. var ch = viewport.height;
  2601. var cx = viewport.x;
  2602. var cy = viewport.y;
  2603. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2604. 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);
  2605. var matrix = MathTmp.Matrix[0];
  2606. world.multiplyToRef(transform, matrix);
  2607. matrix.multiplyToRef(viewportMatrix, matrix);
  2608. return Vector3.TransformCoordinates(vector, matrix);
  2609. };
  2610. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2611. var matrix = MathTmp.Matrix[0];
  2612. world.multiplyToRef(transform, matrix);
  2613. matrix.invert();
  2614. source.x = source.x / viewportWidth * 2 - 1;
  2615. source.y = -(source.y / viewportHeight * 2 - 1);
  2616. var vector = Vector3.TransformCoordinates(source, matrix);
  2617. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2618. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2619. vector = vector.scale(1.0 / num);
  2620. }
  2621. return vector;
  2622. };
  2623. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2624. var result = Vector3.Zero();
  2625. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2626. return result;
  2627. };
  2628. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2629. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2630. };
  2631. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2632. var matrix = MathTmp.Matrix[0];
  2633. world.multiplyToRef(view, matrix);
  2634. matrix.multiplyToRef(projection, matrix);
  2635. matrix.invert();
  2636. var screenSource = MathTmp.Vector3[0];
  2637. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2638. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2639. screenSource.z = 2 * sourceZ - 1.0;
  2640. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2641. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2642. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2643. result.scaleInPlace(1.0 / num);
  2644. }
  2645. };
  2646. Vector3.Minimize = function (left, right) {
  2647. var min = left.clone();
  2648. min.MinimizeInPlace(right);
  2649. return min;
  2650. };
  2651. Vector3.Maximize = function (left, right) {
  2652. var max = left.clone();
  2653. max.MaximizeInPlace(right);
  2654. return max;
  2655. };
  2656. /**
  2657. * Returns the distance (float) between the vectors "value1" and "value2".
  2658. */
  2659. Vector3.Distance = function (value1, value2) {
  2660. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2661. };
  2662. /**
  2663. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2664. */
  2665. Vector3.DistanceSquared = function (value1, value2) {
  2666. var x = value1.x - value2.x;
  2667. var y = value1.y - value2.y;
  2668. var z = value1.z - value2.z;
  2669. return (x * x) + (y * y) + (z * z);
  2670. };
  2671. /**
  2672. * Returns a new Vector3 located at the center between "value1" and "value2".
  2673. */
  2674. Vector3.Center = function (value1, value2) {
  2675. var center = value1.add(value2);
  2676. center.scaleInPlace(0.5);
  2677. return center;
  2678. };
  2679. /**
  2680. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2681. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2682. * to something in order to rotate it from its local system to the given target system.
  2683. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2684. * Returns a new Vector3.
  2685. */
  2686. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2687. var rotation = Vector3.Zero();
  2688. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2689. return rotation;
  2690. };
  2691. /**
  2692. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2693. */
  2694. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2695. var quat = MathTmp.Quaternion[0];
  2696. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2697. quat.toEulerAnglesToRef(ref);
  2698. };
  2699. return Vector3;
  2700. }());
  2701. BABYLON.Vector3 = Vector3;
  2702. //Vector4 class created for EulerAngle class conversion to Quaternion
  2703. var Vector4 = /** @class */ (function () {
  2704. /**
  2705. * Creates a Vector4 object from the passed floats.
  2706. */
  2707. function Vector4(x, y, z, w) {
  2708. this.x = x;
  2709. this.y = y;
  2710. this.z = z;
  2711. this.w = w;
  2712. }
  2713. /**
  2714. * Returns the string with the Vector4 coordinates.
  2715. */
  2716. Vector4.prototype.toString = function () {
  2717. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2718. };
  2719. /**
  2720. * Returns the string "Vector4".
  2721. */
  2722. Vector4.prototype.getClassName = function () {
  2723. return "Vector4";
  2724. };
  2725. /**
  2726. * Returns the Vector4 hash code.
  2727. */
  2728. Vector4.prototype.getHashCode = function () {
  2729. var hash = this.x || 0;
  2730. hash = (hash * 397) ^ (this.y || 0);
  2731. hash = (hash * 397) ^ (this.z || 0);
  2732. hash = (hash * 397) ^ (this.w || 0);
  2733. return hash;
  2734. };
  2735. // Operators
  2736. /**
  2737. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2738. */
  2739. Vector4.prototype.asArray = function () {
  2740. var result = new Array();
  2741. this.toArray(result, 0);
  2742. return result;
  2743. };
  2744. /**
  2745. * Populates the passed array from the passed index with the Vector4 coordinates.
  2746. * Returns the Vector4.
  2747. */
  2748. Vector4.prototype.toArray = function (array, index) {
  2749. if (index === undefined) {
  2750. index = 0;
  2751. }
  2752. array[index] = this.x;
  2753. array[index + 1] = this.y;
  2754. array[index + 2] = this.z;
  2755. array[index + 3] = this.w;
  2756. return this;
  2757. };
  2758. /**
  2759. * Adds the passed vector to the current Vector4.
  2760. * Returns the updated Vector4.
  2761. */
  2762. Vector4.prototype.addInPlace = function (otherVector) {
  2763. this.x += otherVector.x;
  2764. this.y += otherVector.y;
  2765. this.z += otherVector.z;
  2766. this.w += otherVector.w;
  2767. return this;
  2768. };
  2769. /**
  2770. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2771. */
  2772. Vector4.prototype.add = function (otherVector) {
  2773. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2774. };
  2775. /**
  2776. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2777. * Returns the current Vector4.
  2778. */
  2779. Vector4.prototype.addToRef = function (otherVector, result) {
  2780. result.x = this.x + otherVector.x;
  2781. result.y = this.y + otherVector.y;
  2782. result.z = this.z + otherVector.z;
  2783. result.w = this.w + otherVector.w;
  2784. return this;
  2785. };
  2786. /**
  2787. * Subtract in place the passed vector from the current Vector4.
  2788. * Returns the updated Vector4.
  2789. */
  2790. Vector4.prototype.subtractInPlace = function (otherVector) {
  2791. this.x -= otherVector.x;
  2792. this.y -= otherVector.y;
  2793. this.z -= otherVector.z;
  2794. this.w -= otherVector.w;
  2795. return this;
  2796. };
  2797. /**
  2798. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2799. */
  2800. Vector4.prototype.subtract = function (otherVector) {
  2801. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2802. };
  2803. /**
  2804. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2805. * Returns the current Vector4.
  2806. */
  2807. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2808. result.x = this.x - otherVector.x;
  2809. result.y = this.y - otherVector.y;
  2810. result.z = this.z - otherVector.z;
  2811. result.w = this.w - otherVector.w;
  2812. return this;
  2813. };
  2814. /**
  2815. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2816. */
  2817. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2818. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2819. };
  2820. /**
  2821. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2822. * Returns the current Vector4.
  2823. */
  2824. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2825. result.x = this.x - x;
  2826. result.y = this.y - y;
  2827. result.z = this.z - z;
  2828. result.w = this.w - w;
  2829. return this;
  2830. };
  2831. /**
  2832. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2833. */
  2834. Vector4.prototype.negate = function () {
  2835. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2836. };
  2837. /**
  2838. * Multiplies the current Vector4 coordinates by scale (float).
  2839. * Returns the updated Vector4.
  2840. */
  2841. Vector4.prototype.scaleInPlace = function (scale) {
  2842. this.x *= scale;
  2843. this.y *= scale;
  2844. this.z *= scale;
  2845. this.w *= scale;
  2846. return this;
  2847. };
  2848. /**
  2849. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2850. */
  2851. Vector4.prototype.scale = function (scale) {
  2852. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2853. };
  2854. /**
  2855. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2856. * Returns the current Vector4.
  2857. */
  2858. Vector4.prototype.scaleToRef = function (scale, result) {
  2859. result.x = this.x * scale;
  2860. result.y = this.y * scale;
  2861. result.z = this.z * scale;
  2862. result.w = this.w * scale;
  2863. return this;
  2864. };
  2865. /**
  2866. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2867. */
  2868. Vector4.prototype.equals = function (otherVector) {
  2869. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2870. };
  2871. /**
  2872. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2873. */
  2874. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2875. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2876. return otherVector
  2877. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2878. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2879. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2880. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2881. };
  2882. /**
  2883. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2884. */
  2885. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2886. return this.x === x && this.y === y && this.z === z && this.w === w;
  2887. };
  2888. /**
  2889. * Multiplies in place the current Vector4 by the passed one.
  2890. * Returns the updated Vector4.
  2891. */
  2892. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2893. this.x *= otherVector.x;
  2894. this.y *= otherVector.y;
  2895. this.z *= otherVector.z;
  2896. this.w *= otherVector.w;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2901. */
  2902. Vector4.prototype.multiply = function (otherVector) {
  2903. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2904. };
  2905. /**
  2906. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2907. * Returns the current Vector4.
  2908. */
  2909. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2910. result.x = this.x * otherVector.x;
  2911. result.y = this.y * otherVector.y;
  2912. result.z = this.z * otherVector.z;
  2913. result.w = this.w * otherVector.w;
  2914. return this;
  2915. };
  2916. /**
  2917. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2918. */
  2919. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2920. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2921. };
  2922. /**
  2923. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2924. */
  2925. Vector4.prototype.divide = function (otherVector) {
  2926. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2927. };
  2928. /**
  2929. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2930. * Returns the current Vector4.
  2931. */
  2932. Vector4.prototype.divideToRef = function (otherVector, result) {
  2933. result.x = this.x / otherVector.x;
  2934. result.y = this.y / otherVector.y;
  2935. result.z = this.z / otherVector.z;
  2936. result.w = this.w / otherVector.w;
  2937. return this;
  2938. };
  2939. /**
  2940. * Divides the current Vector3 coordinates by the passed ones.
  2941. * Returns the updated Vector3.
  2942. */
  2943. Vector4.prototype.divideInPlace = function (otherVector) {
  2944. return this.divideToRef(otherVector, this);
  2945. };
  2946. /**
  2947. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2948. */
  2949. Vector4.prototype.MinimizeInPlace = function (other) {
  2950. if (other.x < this.x)
  2951. this.x = other.x;
  2952. if (other.y < this.y)
  2953. this.y = other.y;
  2954. if (other.z < this.z)
  2955. this.z = other.z;
  2956. if (other.w < this.w)
  2957. this.w = other.w;
  2958. return this;
  2959. };
  2960. /**
  2961. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2962. */
  2963. Vector4.prototype.MaximizeInPlace = function (other) {
  2964. if (other.x > this.x)
  2965. this.x = other.x;
  2966. if (other.y > this.y)
  2967. this.y = other.y;
  2968. if (other.z > this.z)
  2969. this.z = other.z;
  2970. if (other.w > this.w)
  2971. this.w = other.w;
  2972. return this;
  2973. };
  2974. // Properties
  2975. /**
  2976. * Returns the Vector4 length (float).
  2977. */
  2978. Vector4.prototype.length = function () {
  2979. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2980. };
  2981. /**
  2982. * Returns the Vector4 squared length (float).
  2983. */
  2984. Vector4.prototype.lengthSquared = function () {
  2985. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2986. };
  2987. // Methods
  2988. /**
  2989. * Normalizes in place the Vector4.
  2990. * Returns the updated Vector4.
  2991. */
  2992. Vector4.prototype.normalize = function () {
  2993. var len = this.length();
  2994. if (len === 0)
  2995. return this;
  2996. var num = 1.0 / len;
  2997. this.x *= num;
  2998. this.y *= num;
  2999. this.z *= num;
  3000. this.w *= num;
  3001. return this;
  3002. };
  3003. /**
  3004. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3005. */
  3006. Vector4.prototype.toVector3 = function () {
  3007. return new Vector3(this.x, this.y, this.z);
  3008. };
  3009. /**
  3010. * Returns a new Vector4 copied from the current one.
  3011. */
  3012. Vector4.prototype.clone = function () {
  3013. return new Vector4(this.x, this.y, this.z, this.w);
  3014. };
  3015. /**
  3016. * Updates the current Vector4 with the passed one coordinates.
  3017. * Returns the updated Vector4.
  3018. */
  3019. Vector4.prototype.copyFrom = function (source) {
  3020. this.x = source.x;
  3021. this.y = source.y;
  3022. this.z = source.z;
  3023. this.w = source.w;
  3024. return this;
  3025. };
  3026. /**
  3027. * Updates the current Vector4 coordinates with the passed floats.
  3028. * Returns the updated Vector4.
  3029. */
  3030. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3031. this.x = x;
  3032. this.y = y;
  3033. this.z = z;
  3034. this.w = w;
  3035. return this;
  3036. };
  3037. /**
  3038. * Updates the current Vector4 coordinates with the passed floats.
  3039. * Returns the updated Vector4.
  3040. */
  3041. Vector4.prototype.set = function (x, y, z, w) {
  3042. return this.copyFromFloats(x, y, z, w);
  3043. };
  3044. // Statics
  3045. /**
  3046. * Returns a new Vector4 set from the starting index of the passed array.
  3047. */
  3048. Vector4.FromArray = function (array, offset) {
  3049. if (!offset) {
  3050. offset = 0;
  3051. }
  3052. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3053. };
  3054. /**
  3055. * Updates the passed vector "result" from the starting index of the passed array.
  3056. */
  3057. Vector4.FromArrayToRef = function (array, offset, result) {
  3058. result.x = array[offset];
  3059. result.y = array[offset + 1];
  3060. result.z = array[offset + 2];
  3061. result.w = array[offset + 3];
  3062. };
  3063. /**
  3064. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3065. */
  3066. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3067. Vector4.FromArrayToRef(array, offset, result);
  3068. };
  3069. /**
  3070. * Updates the passed vector "result" coordinates from the passed floats.
  3071. */
  3072. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3073. result.x = x;
  3074. result.y = y;
  3075. result.z = z;
  3076. result.w = w;
  3077. };
  3078. /**
  3079. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3080. */
  3081. Vector4.Zero = function () {
  3082. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3083. };
  3084. /**
  3085. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3086. */
  3087. Vector4.One = function () {
  3088. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3089. };
  3090. /**
  3091. * Returns a new normalized Vector4 from the passed one.
  3092. */
  3093. Vector4.Normalize = function (vector) {
  3094. var result = Vector4.Zero();
  3095. Vector4.NormalizeToRef(vector, result);
  3096. return result;
  3097. };
  3098. /**
  3099. * Updates the passed vector "result" from the normalization of the passed one.
  3100. */
  3101. Vector4.NormalizeToRef = function (vector, result) {
  3102. result.copyFrom(vector);
  3103. result.normalize();
  3104. };
  3105. Vector4.Minimize = function (left, right) {
  3106. var min = left.clone();
  3107. min.MinimizeInPlace(right);
  3108. return min;
  3109. };
  3110. Vector4.Maximize = function (left, right) {
  3111. var max = left.clone();
  3112. max.MaximizeInPlace(right);
  3113. return max;
  3114. };
  3115. /**
  3116. * Returns the distance (float) between the vectors "value1" and "value2".
  3117. */
  3118. Vector4.Distance = function (value1, value2) {
  3119. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3120. };
  3121. /**
  3122. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3123. */
  3124. Vector4.DistanceSquared = function (value1, value2) {
  3125. var x = value1.x - value2.x;
  3126. var y = value1.y - value2.y;
  3127. var z = value1.z - value2.z;
  3128. var w = value1.w - value2.w;
  3129. return (x * x) + (y * y) + (z * z) + (w * w);
  3130. };
  3131. /**
  3132. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3133. */
  3134. Vector4.Center = function (value1, value2) {
  3135. var center = value1.add(value2);
  3136. center.scaleInPlace(0.5);
  3137. return center;
  3138. };
  3139. /**
  3140. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3141. * This methods computes transformed normalized direction vectors only.
  3142. */
  3143. Vector4.TransformNormal = function (vector, transformation) {
  3144. var result = Vector4.Zero();
  3145. Vector4.TransformNormalToRef(vector, transformation, result);
  3146. return result;
  3147. };
  3148. /**
  3149. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3150. * This methods computes transformed normalized direction vectors only.
  3151. */
  3152. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3153. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3154. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3155. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3156. result.x = x;
  3157. result.y = y;
  3158. result.z = z;
  3159. result.w = vector.w;
  3160. };
  3161. /**
  3162. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3163. * This methods computes transformed normalized direction vectors only.
  3164. */
  3165. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3166. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3167. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3168. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3169. result.w = w;
  3170. };
  3171. return Vector4;
  3172. }());
  3173. BABYLON.Vector4 = Vector4;
  3174. var Size = /** @class */ (function () {
  3175. /**
  3176. * Creates a Size object from the passed width and height (floats).
  3177. */
  3178. function Size(width, height) {
  3179. this.width = width;
  3180. this.height = height;
  3181. }
  3182. // Returns a string with the Size width and height.
  3183. Size.prototype.toString = function () {
  3184. return "{W: " + this.width + ", H: " + this.height + "}";
  3185. };
  3186. /**
  3187. * Returns the string "Size"
  3188. */
  3189. Size.prototype.getClassName = function () {
  3190. return "Size";
  3191. };
  3192. /**
  3193. * Returns the Size hash code.
  3194. */
  3195. Size.prototype.getHashCode = function () {
  3196. var hash = this.width || 0;
  3197. hash = (hash * 397) ^ (this.height || 0);
  3198. return hash;
  3199. };
  3200. /**
  3201. * Updates the current size from the passed one.
  3202. * Returns the updated Size.
  3203. */
  3204. Size.prototype.copyFrom = function (src) {
  3205. this.width = src.width;
  3206. this.height = src.height;
  3207. };
  3208. /**
  3209. * Updates in place the current Size from the passed floats.
  3210. * Returns the updated Size.
  3211. */
  3212. Size.prototype.copyFromFloats = function (width, height) {
  3213. this.width = width;
  3214. this.height = height;
  3215. return this;
  3216. };
  3217. /**
  3218. * Updates in place the current Size from the passed floats.
  3219. * Returns the updated Size.
  3220. */
  3221. Size.prototype.set = function (width, height) {
  3222. return this.copyFromFloats(width, height);
  3223. };
  3224. /**
  3225. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3226. */
  3227. Size.prototype.multiplyByFloats = function (w, h) {
  3228. return new Size(this.width * w, this.height * h);
  3229. };
  3230. /**
  3231. * Returns a new Size copied from the passed one.
  3232. */
  3233. Size.prototype.clone = function () {
  3234. return new Size(this.width, this.height);
  3235. };
  3236. /**
  3237. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3238. */
  3239. Size.prototype.equals = function (other) {
  3240. if (!other) {
  3241. return false;
  3242. }
  3243. return (this.width === other.width) && (this.height === other.height);
  3244. };
  3245. Object.defineProperty(Size.prototype, "surface", {
  3246. /**
  3247. * Returns the surface of the Size : width * height (float).
  3248. */
  3249. get: function () {
  3250. return this.width * this.height;
  3251. },
  3252. enumerable: true,
  3253. configurable: true
  3254. });
  3255. /**
  3256. * Returns a new Size set to (0.0, 0.0)
  3257. */
  3258. Size.Zero = function () {
  3259. return new Size(0.0, 0.0);
  3260. };
  3261. /**
  3262. * Returns a new Size set as the addition result of the current Size and the passed one.
  3263. */
  3264. Size.prototype.add = function (otherSize) {
  3265. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3266. return r;
  3267. };
  3268. /**
  3269. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3270. */
  3271. Size.prototype.subtract = function (otherSize) {
  3272. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3273. return r;
  3274. };
  3275. /**
  3276. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3277. */
  3278. Size.Lerp = function (start, end, amount) {
  3279. var w = start.width + ((end.width - start.width) * amount);
  3280. var h = start.height + ((end.height - start.height) * amount);
  3281. return new Size(w, h);
  3282. };
  3283. return Size;
  3284. }());
  3285. BABYLON.Size = Size;
  3286. var Quaternion = /** @class */ (function () {
  3287. /**
  3288. * Creates a new Quaternion from the passed floats.
  3289. */
  3290. function Quaternion(x, y, z, w) {
  3291. if (x === void 0) { x = 0.0; }
  3292. if (y === void 0) { y = 0.0; }
  3293. if (z === void 0) { z = 0.0; }
  3294. if (w === void 0) { w = 1.0; }
  3295. this.x = x;
  3296. this.y = y;
  3297. this.z = z;
  3298. this.w = w;
  3299. }
  3300. /**
  3301. * Returns a string with the Quaternion coordinates.
  3302. */
  3303. Quaternion.prototype.toString = function () {
  3304. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3305. };
  3306. /**
  3307. * Returns the string "Quaternion".
  3308. */
  3309. Quaternion.prototype.getClassName = function () {
  3310. return "Quaternion";
  3311. };
  3312. /**
  3313. * Returns the Quaternion hash code.
  3314. */
  3315. Quaternion.prototype.getHashCode = function () {
  3316. var hash = this.x || 0;
  3317. hash = (hash * 397) ^ (this.y || 0);
  3318. hash = (hash * 397) ^ (this.z || 0);
  3319. hash = (hash * 397) ^ (this.w || 0);
  3320. return hash;
  3321. };
  3322. /**
  3323. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3324. */
  3325. Quaternion.prototype.asArray = function () {
  3326. return [this.x, this.y, this.z, this.w];
  3327. };
  3328. /**
  3329. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3330. */
  3331. Quaternion.prototype.equals = function (otherQuaternion) {
  3332. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3333. };
  3334. /**
  3335. * Returns a new Quaternion copied from the current one.
  3336. */
  3337. Quaternion.prototype.clone = function () {
  3338. return new Quaternion(this.x, this.y, this.z, this.w);
  3339. };
  3340. /**
  3341. * Updates the current Quaternion from the passed one coordinates.
  3342. * Returns the updated Quaterion.
  3343. */
  3344. Quaternion.prototype.copyFrom = function (other) {
  3345. this.x = other.x;
  3346. this.y = other.y;
  3347. this.z = other.z;
  3348. this.w = other.w;
  3349. return this;
  3350. };
  3351. /**
  3352. * Updates the current Quaternion from the passed float coordinates.
  3353. * Returns the updated Quaterion.
  3354. */
  3355. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3356. this.x = x;
  3357. this.y = y;
  3358. this.z = z;
  3359. this.w = w;
  3360. return this;
  3361. };
  3362. /**
  3363. * Updates the current Quaternion from the passed float coordinates.
  3364. * Returns the updated Quaterion.
  3365. */
  3366. Quaternion.prototype.set = function (x, y, z, w) {
  3367. return this.copyFromFloats(x, y, z, w);
  3368. };
  3369. /**
  3370. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3371. */
  3372. Quaternion.prototype.add = function (other) {
  3373. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3374. };
  3375. /**
  3376. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3377. */
  3378. Quaternion.prototype.subtract = function (other) {
  3379. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3380. };
  3381. /**
  3382. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3383. */
  3384. Quaternion.prototype.scale = function (value) {
  3385. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3386. };
  3387. /**
  3388. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3389. */
  3390. Quaternion.prototype.multiply = function (q1) {
  3391. var result = new Quaternion(0, 0, 0, 1.0);
  3392. this.multiplyToRef(q1, result);
  3393. return result;
  3394. };
  3395. /**
  3396. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3397. * Returns the current Quaternion.
  3398. */
  3399. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3400. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3401. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3402. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3403. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3404. result.copyFromFloats(x, y, z, w);
  3405. return this;
  3406. };
  3407. /**
  3408. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3409. * Returns the updated Quaternion.
  3410. */
  3411. Quaternion.prototype.multiplyInPlace = function (q1) {
  3412. this.multiplyToRef(q1, this);
  3413. return this;
  3414. };
  3415. /**
  3416. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3417. * Returns the current Quaternion.
  3418. */
  3419. Quaternion.prototype.conjugateToRef = function (ref) {
  3420. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3421. return this;
  3422. };
  3423. /**
  3424. * Conjugates in place the current Quaternion.
  3425. * Returns the updated Quaternion.
  3426. */
  3427. Quaternion.prototype.conjugateInPlace = function () {
  3428. this.x *= -1;
  3429. this.y *= -1;
  3430. this.z *= -1;
  3431. return this;
  3432. };
  3433. /**
  3434. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3435. */
  3436. Quaternion.prototype.conjugate = function () {
  3437. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3438. return result;
  3439. };
  3440. /**
  3441. * Returns the Quaternion length (float).
  3442. */
  3443. Quaternion.prototype.length = function () {
  3444. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3445. };
  3446. /**
  3447. * Normalize in place the current Quaternion.
  3448. * Returns the updated Quaternion.
  3449. */
  3450. Quaternion.prototype.normalize = function () {
  3451. var length = 1.0 / this.length();
  3452. this.x *= length;
  3453. this.y *= length;
  3454. this.z *= length;
  3455. this.w *= length;
  3456. return this;
  3457. };
  3458. /**
  3459. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3460. */
  3461. Quaternion.prototype.toEulerAngles = function (order) {
  3462. if (order === void 0) { order = "YZX"; }
  3463. var result = Vector3.Zero();
  3464. this.toEulerAnglesToRef(result, order);
  3465. return result;
  3466. };
  3467. /**
  3468. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3469. * Returns the current Quaternion.
  3470. */
  3471. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3472. if (order === void 0) { order = "YZX"; }
  3473. var qz = this.z;
  3474. var qx = this.x;
  3475. var qy = this.y;
  3476. var qw = this.w;
  3477. var sqw = qw * qw;
  3478. var sqz = qz * qz;
  3479. var sqx = qx * qx;
  3480. var sqy = qy * qy;
  3481. var zAxisY = qy * qz - qx * qw;
  3482. var limit = .4999999;
  3483. if (zAxisY < -limit) {
  3484. result.y = 2 * Math.atan2(qy, qw);
  3485. result.x = Math.PI / 2;
  3486. result.z = 0;
  3487. }
  3488. else if (zAxisY > limit) {
  3489. result.y = 2 * Math.atan2(qy, qw);
  3490. result.x = -Math.PI / 2;
  3491. result.z = 0;
  3492. }
  3493. else {
  3494. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3495. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3496. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3497. }
  3498. return this;
  3499. };
  3500. /**
  3501. * Updates the passed rotation matrix with the current Quaternion values.
  3502. * Returns the current Quaternion.
  3503. */
  3504. Quaternion.prototype.toRotationMatrix = function (result) {
  3505. var xx = this.x * this.x;
  3506. var yy = this.y * this.y;
  3507. var zz = this.z * this.z;
  3508. var xy = this.x * this.y;
  3509. var zw = this.z * this.w;
  3510. var zx = this.z * this.x;
  3511. var yw = this.y * this.w;
  3512. var yz = this.y * this.z;
  3513. var xw = this.x * this.w;
  3514. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3515. result.m[1] = 2.0 * (xy + zw);
  3516. result.m[2] = 2.0 * (zx - yw);
  3517. result.m[3] = 0;
  3518. result.m[4] = 2.0 * (xy - zw);
  3519. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3520. result.m[6] = 2.0 * (yz + xw);
  3521. result.m[7] = 0;
  3522. result.m[8] = 2.0 * (zx + yw);
  3523. result.m[9] = 2.0 * (yz - xw);
  3524. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3525. result.m[11] = 0;
  3526. result.m[12] = 0;
  3527. result.m[13] = 0;
  3528. result.m[14] = 0;
  3529. result.m[15] = 1.0;
  3530. result._markAsUpdated();
  3531. return this;
  3532. };
  3533. /**
  3534. * Updates the current Quaternion from the passed rotation matrix values.
  3535. * Returns the updated Quaternion.
  3536. */
  3537. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3538. Quaternion.FromRotationMatrixToRef(matrix, this);
  3539. return this;
  3540. };
  3541. // Statics
  3542. /**
  3543. * Returns a new Quaternion set from the passed rotation matrix values.
  3544. */
  3545. Quaternion.FromRotationMatrix = function (matrix) {
  3546. var result = new Quaternion();
  3547. Quaternion.FromRotationMatrixToRef(matrix, result);
  3548. return result;
  3549. };
  3550. /**
  3551. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3552. */
  3553. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3554. var data = matrix.m;
  3555. var m11 = data[0], m12 = data[4], m13 = data[8];
  3556. var m21 = data[1], m22 = data[5], m23 = data[9];
  3557. var m31 = data[2], m32 = data[6], m33 = data[10];
  3558. var trace = m11 + m22 + m33;
  3559. var s;
  3560. if (trace > 0) {
  3561. s = 0.5 / Math.sqrt(trace + 1.0);
  3562. result.w = 0.25 / s;
  3563. result.x = (m32 - m23) * s;
  3564. result.y = (m13 - m31) * s;
  3565. result.z = (m21 - m12) * s;
  3566. }
  3567. else if (m11 > m22 && m11 > m33) {
  3568. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3569. result.w = (m32 - m23) / s;
  3570. result.x = 0.25 * s;
  3571. result.y = (m12 + m21) / s;
  3572. result.z = (m13 + m31) / s;
  3573. }
  3574. else if (m22 > m33) {
  3575. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3576. result.w = (m13 - m31) / s;
  3577. result.x = (m12 + m21) / s;
  3578. result.y = 0.25 * s;
  3579. result.z = (m23 + m32) / s;
  3580. }
  3581. else {
  3582. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3583. result.w = (m21 - m12) / s;
  3584. result.x = (m13 + m31) / s;
  3585. result.y = (m23 + m32) / s;
  3586. result.z = 0.25 * s;
  3587. }
  3588. };
  3589. /**
  3590. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3591. */
  3592. Quaternion.Zero = function () {
  3593. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3594. };
  3595. /**
  3596. * Returns a new Quaternion as the inverted current Quaternion.
  3597. */
  3598. Quaternion.Inverse = function (q) {
  3599. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3600. };
  3601. /**
  3602. * Returns the identity Quaternion.
  3603. */
  3604. Quaternion.Identity = function () {
  3605. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3606. };
  3607. Quaternion.IsIdentity = function (quaternion) {
  3608. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3609. };
  3610. /**
  3611. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3612. */
  3613. Quaternion.RotationAxis = function (axis, angle) {
  3614. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3615. };
  3616. /**
  3617. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3618. */
  3619. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3620. var sin = Math.sin(angle / 2);
  3621. axis.normalize();
  3622. result.w = Math.cos(angle / 2);
  3623. result.x = axis.x * sin;
  3624. result.y = axis.y * sin;
  3625. result.z = axis.z * sin;
  3626. return result;
  3627. };
  3628. /**
  3629. * Retuns a new Quaternion set from the starting index of the passed array.
  3630. */
  3631. Quaternion.FromArray = function (array, offset) {
  3632. if (!offset) {
  3633. offset = 0;
  3634. }
  3635. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3636. };
  3637. /**
  3638. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3639. */
  3640. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3641. var q = new Quaternion();
  3642. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3643. return q;
  3644. };
  3645. /**
  3646. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3647. */
  3648. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3649. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3650. var halfRoll = roll * 0.5;
  3651. var halfPitch = pitch * 0.5;
  3652. var halfYaw = yaw * 0.5;
  3653. var sinRoll = Math.sin(halfRoll);
  3654. var cosRoll = Math.cos(halfRoll);
  3655. var sinPitch = Math.sin(halfPitch);
  3656. var cosPitch = Math.cos(halfPitch);
  3657. var sinYaw = Math.sin(halfYaw);
  3658. var cosYaw = Math.cos(halfYaw);
  3659. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3660. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3661. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3662. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3663. };
  3664. /**
  3665. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3666. */
  3667. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3668. var result = new Quaternion();
  3669. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3670. return result;
  3671. };
  3672. /**
  3673. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3674. */
  3675. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3676. // Produces a quaternion from Euler angles in the z-x-z orientation
  3677. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3678. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3679. var halfBeta = beta * 0.5;
  3680. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3681. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3682. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3683. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3684. };
  3685. /**
  3686. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3687. * cf to Vector3.RotationFromAxis() documentation.
  3688. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3689. */
  3690. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3691. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3692. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3693. return quat;
  3694. };
  3695. /**
  3696. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3697. * cf to Vector3.RotationFromAxis() documentation.
  3698. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3699. */
  3700. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3701. var rotMat = MathTmp.Matrix[0];
  3702. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3703. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3704. };
  3705. Quaternion.Slerp = function (left, right, amount) {
  3706. var result = Quaternion.Identity();
  3707. Quaternion.SlerpToRef(left, right, amount, result);
  3708. return result;
  3709. };
  3710. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3711. var num2;
  3712. var num3;
  3713. var num = amount;
  3714. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3715. var flag = false;
  3716. if (num4 < 0) {
  3717. flag = true;
  3718. num4 = -num4;
  3719. }
  3720. if (num4 > 0.999999) {
  3721. num3 = 1 - num;
  3722. num2 = flag ? -num : num;
  3723. }
  3724. else {
  3725. var num5 = Math.acos(num4);
  3726. var num6 = (1.0 / Math.sin(num5));
  3727. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3728. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3729. }
  3730. result.x = (num3 * left.x) + (num2 * right.x);
  3731. result.y = (num3 * left.y) + (num2 * right.y);
  3732. result.z = (num3 * left.z) + (num2 * right.z);
  3733. result.w = (num3 * left.w) + (num2 * right.w);
  3734. };
  3735. /**
  3736. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3737. */
  3738. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3739. var squared = amount * amount;
  3740. var cubed = amount * squared;
  3741. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3742. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3743. var part3 = (cubed - (2.0 * squared)) + amount;
  3744. var part4 = cubed - squared;
  3745. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3746. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3747. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3748. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3749. return new Quaternion(x, y, z, w);
  3750. };
  3751. return Quaternion;
  3752. }());
  3753. BABYLON.Quaternion = Quaternion;
  3754. var Matrix = /** @class */ (function () {
  3755. function Matrix() {
  3756. this._isIdentity = false;
  3757. this._isIdentityDirty = true;
  3758. this.m = new Float32Array(16);
  3759. this._markAsUpdated();
  3760. }
  3761. Matrix.prototype._markAsUpdated = function () {
  3762. this.updateFlag = Matrix._updateFlagSeed++;
  3763. this._isIdentityDirty = true;
  3764. };
  3765. // Properties
  3766. /**
  3767. * Boolean : True is the matrix is the identity matrix
  3768. */
  3769. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3770. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3771. if (this._isIdentityDirty) {
  3772. this._isIdentityDirty = false;
  3773. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3774. this._isIdentity = false;
  3775. }
  3776. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3780. this._isIdentity = false;
  3781. }
  3782. else {
  3783. this._isIdentity = true;
  3784. }
  3785. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3786. this._isIdentity = false;
  3787. }
  3788. }
  3789. return this._isIdentity;
  3790. };
  3791. /**
  3792. * Returns the matrix determinant (float).
  3793. */
  3794. Matrix.prototype.determinant = function () {
  3795. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3796. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3797. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3798. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3799. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3800. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3801. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3802. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3803. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3804. };
  3805. // Methods
  3806. /**
  3807. * Returns the matrix underlying array.
  3808. */
  3809. Matrix.prototype.toArray = function () {
  3810. return this.m;
  3811. };
  3812. /**
  3813. * Returns the matrix underlying array.
  3814. */
  3815. Matrix.prototype.asArray = function () {
  3816. return this.toArray();
  3817. };
  3818. /**
  3819. * Inverts in place the Matrix.
  3820. * Returns the Matrix inverted.
  3821. */
  3822. Matrix.prototype.invert = function () {
  3823. this.invertToRef(this);
  3824. return this;
  3825. };
  3826. /**
  3827. * Sets all the matrix elements to zero.
  3828. * Returns the Matrix.
  3829. */
  3830. Matrix.prototype.reset = function () {
  3831. for (var index = 0; index < 16; index++) {
  3832. this.m[index] = 0.0;
  3833. }
  3834. this._markAsUpdated();
  3835. return this;
  3836. };
  3837. /**
  3838. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3839. */
  3840. Matrix.prototype.add = function (other) {
  3841. var result = new Matrix();
  3842. this.addToRef(other, result);
  3843. return result;
  3844. };
  3845. /**
  3846. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3847. * Returns the Matrix.
  3848. */
  3849. Matrix.prototype.addToRef = function (other, result) {
  3850. for (var index = 0; index < 16; index++) {
  3851. result.m[index] = this.m[index] + other.m[index];
  3852. }
  3853. result._markAsUpdated();
  3854. return this;
  3855. };
  3856. /**
  3857. * Adds in place the passed matrix to the current Matrix.
  3858. * Returns the updated Matrix.
  3859. */
  3860. Matrix.prototype.addToSelf = function (other) {
  3861. for (var index = 0; index < 16; index++) {
  3862. this.m[index] += other.m[index];
  3863. }
  3864. this._markAsUpdated();
  3865. return this;
  3866. };
  3867. /**
  3868. * Sets the passed matrix with the current inverted Matrix.
  3869. * Returns the unmodified current Matrix.
  3870. */
  3871. Matrix.prototype.invertToRef = function (other) {
  3872. var l1 = this.m[0];
  3873. var l2 = this.m[1];
  3874. var l3 = this.m[2];
  3875. var l4 = this.m[3];
  3876. var l5 = this.m[4];
  3877. var l6 = this.m[5];
  3878. var l7 = this.m[6];
  3879. var l8 = this.m[7];
  3880. var l9 = this.m[8];
  3881. var l10 = this.m[9];
  3882. var l11 = this.m[10];
  3883. var l12 = this.m[11];
  3884. var l13 = this.m[12];
  3885. var l14 = this.m[13];
  3886. var l15 = this.m[14];
  3887. var l16 = this.m[15];
  3888. var l17 = (l11 * l16) - (l12 * l15);
  3889. var l18 = (l10 * l16) - (l12 * l14);
  3890. var l19 = (l10 * l15) - (l11 * l14);
  3891. var l20 = (l9 * l16) - (l12 * l13);
  3892. var l21 = (l9 * l15) - (l11 * l13);
  3893. var l22 = (l9 * l14) - (l10 * l13);
  3894. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3895. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3896. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3897. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3898. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3899. var l28 = (l7 * l16) - (l8 * l15);
  3900. var l29 = (l6 * l16) - (l8 * l14);
  3901. var l30 = (l6 * l15) - (l7 * l14);
  3902. var l31 = (l5 * l16) - (l8 * l13);
  3903. var l32 = (l5 * l15) - (l7 * l13);
  3904. var l33 = (l5 * l14) - (l6 * l13);
  3905. var l34 = (l7 * l12) - (l8 * l11);
  3906. var l35 = (l6 * l12) - (l8 * l10);
  3907. var l36 = (l6 * l11) - (l7 * l10);
  3908. var l37 = (l5 * l12) - (l8 * l9);
  3909. var l38 = (l5 * l11) - (l7 * l9);
  3910. var l39 = (l5 * l10) - (l6 * l9);
  3911. other.m[0] = l23 * l27;
  3912. other.m[4] = l24 * l27;
  3913. other.m[8] = l25 * l27;
  3914. other.m[12] = l26 * l27;
  3915. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3916. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3917. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3918. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3919. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3920. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3921. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3922. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3923. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3924. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3925. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3926. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3927. other._markAsUpdated();
  3928. return this;
  3929. };
  3930. /**
  3931. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3932. * Returns the updated Matrix.
  3933. */
  3934. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3935. this.m[12] = x;
  3936. this.m[13] = y;
  3937. this.m[14] = z;
  3938. this._markAsUpdated();
  3939. return this;
  3940. };
  3941. /**
  3942. * Inserts the translation vector in the current Matrix.
  3943. * Returns the updated Matrix.
  3944. */
  3945. Matrix.prototype.setTranslation = function (vector3) {
  3946. this.m[12] = vector3.x;
  3947. this.m[13] = vector3.y;
  3948. this.m[14] = vector3.z;
  3949. this._markAsUpdated();
  3950. return this;
  3951. };
  3952. /**
  3953. * Returns a new Vector3 as the extracted translation from the Matrix.
  3954. */
  3955. Matrix.prototype.getTranslation = function () {
  3956. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3957. };
  3958. /**
  3959. * Fill a Vector3 with the extracted translation from the Matrix.
  3960. */
  3961. Matrix.prototype.getTranslationToRef = function (result) {
  3962. result.x = this.m[12];
  3963. result.y = this.m[13];
  3964. result.z = this.m[14];
  3965. return this;
  3966. };
  3967. /**
  3968. * Remove rotation and scaling part from the Matrix.
  3969. * Returns the updated Matrix.
  3970. */
  3971. Matrix.prototype.removeRotationAndScaling = function () {
  3972. this.setRowFromFloats(0, 1, 0, 0, 0);
  3973. this.setRowFromFloats(1, 0, 1, 0, 0);
  3974. this.setRowFromFloats(2, 0, 0, 1, 0);
  3975. return this;
  3976. };
  3977. /**
  3978. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3979. */
  3980. Matrix.prototype.multiply = function (other) {
  3981. var result = new Matrix();
  3982. this.multiplyToRef(other, result);
  3983. return result;
  3984. };
  3985. /**
  3986. * Updates the current Matrix from the passed one values.
  3987. * Returns the updated Matrix.
  3988. */
  3989. Matrix.prototype.copyFrom = function (other) {
  3990. for (var index = 0; index < 16; index++) {
  3991. this.m[index] = other.m[index];
  3992. }
  3993. this._markAsUpdated();
  3994. return this;
  3995. };
  3996. /**
  3997. * Populates the passed array from the starting index with the Matrix values.
  3998. * Returns the Matrix.
  3999. */
  4000. Matrix.prototype.copyToArray = function (array, offset) {
  4001. if (offset === void 0) { offset = 0; }
  4002. for (var index = 0; index < 16; index++) {
  4003. array[offset + index] = this.m[index];
  4004. }
  4005. return this;
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4009. */
  4010. Matrix.prototype.multiplyToRef = function (other, result) {
  4011. this.multiplyToArray(other, result.m, 0);
  4012. result._markAsUpdated();
  4013. return this;
  4014. };
  4015. /**
  4016. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4017. */
  4018. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4019. var tm0 = this.m[0];
  4020. var tm1 = this.m[1];
  4021. var tm2 = this.m[2];
  4022. var tm3 = this.m[3];
  4023. var tm4 = this.m[4];
  4024. var tm5 = this.m[5];
  4025. var tm6 = this.m[6];
  4026. var tm7 = this.m[7];
  4027. var tm8 = this.m[8];
  4028. var tm9 = this.m[9];
  4029. var tm10 = this.m[10];
  4030. var tm11 = this.m[11];
  4031. var tm12 = this.m[12];
  4032. var tm13 = this.m[13];
  4033. var tm14 = this.m[14];
  4034. var tm15 = this.m[15];
  4035. var om0 = other.m[0];
  4036. var om1 = other.m[1];
  4037. var om2 = other.m[2];
  4038. var om3 = other.m[3];
  4039. var om4 = other.m[4];
  4040. var om5 = other.m[5];
  4041. var om6 = other.m[6];
  4042. var om7 = other.m[7];
  4043. var om8 = other.m[8];
  4044. var om9 = other.m[9];
  4045. var om10 = other.m[10];
  4046. var om11 = other.m[11];
  4047. var om12 = other.m[12];
  4048. var om13 = other.m[13];
  4049. var om14 = other.m[14];
  4050. var om15 = other.m[15];
  4051. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4052. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4053. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4054. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4055. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4056. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4057. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4058. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4059. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4060. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4061. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4062. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4063. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4064. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4065. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4066. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4067. return this;
  4068. };
  4069. /**
  4070. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4071. */
  4072. Matrix.prototype.equals = function (value) {
  4073. return value &&
  4074. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4075. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4076. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4077. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4078. };
  4079. /**
  4080. * Returns a new Matrix from the current Matrix.
  4081. */
  4082. Matrix.prototype.clone = function () {
  4083. 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]);
  4084. };
  4085. /**
  4086. * Returns the string "Matrix"
  4087. */
  4088. Matrix.prototype.getClassName = function () {
  4089. return "Matrix";
  4090. };
  4091. /**
  4092. * Returns the Matrix hash code.
  4093. */
  4094. Matrix.prototype.getHashCode = function () {
  4095. var hash = this.m[0] || 0;
  4096. for (var i = 1; i < 16; i++) {
  4097. hash = (hash * 397) ^ (this.m[i] || 0);
  4098. }
  4099. return hash;
  4100. };
  4101. /**
  4102. * Decomposes the current Matrix into :
  4103. * - a scale vector3 passed as a reference to update,
  4104. * - a rotation quaternion passed as a reference to update,
  4105. * - a translation vector3 passed as a reference to update.
  4106. * Returns the boolean `true`.
  4107. */
  4108. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4109. translation.x = this.m[12];
  4110. translation.y = this.m[13];
  4111. translation.z = this.m[14];
  4112. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4113. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4114. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4115. if (this.determinant() <= 0) {
  4116. scale.y *= -1;
  4117. }
  4118. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4119. rotation.x = 0;
  4120. rotation.y = 0;
  4121. rotation.z = 0;
  4122. rotation.w = 1;
  4123. return false;
  4124. }
  4125. 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]);
  4126. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4127. return true;
  4128. };
  4129. /**
  4130. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4131. */
  4132. Matrix.prototype.getRotationMatrix = function () {
  4133. var result = Matrix.Identity();
  4134. this.getRotationMatrixToRef(result);
  4135. return result;
  4136. };
  4137. /**
  4138. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4139. * Returns the current Matrix.
  4140. */
  4141. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4142. var m = this.m;
  4143. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4144. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4145. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4146. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4147. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4148. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4149. 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);
  4150. return this;
  4151. };
  4152. // Statics
  4153. /**
  4154. * Returns a new Matrix set from the starting index of the passed array.
  4155. */
  4156. Matrix.FromArray = function (array, offset) {
  4157. var result = new Matrix();
  4158. if (!offset) {
  4159. offset = 0;
  4160. }
  4161. Matrix.FromArrayToRef(array, offset, result);
  4162. return result;
  4163. };
  4164. /**
  4165. * Sets the passed "result" matrix from the starting index of the passed array.
  4166. */
  4167. Matrix.FromArrayToRef = function (array, offset, result) {
  4168. for (var index = 0; index < 16; index++) {
  4169. result.m[index] = array[index + offset];
  4170. }
  4171. result._markAsUpdated();
  4172. };
  4173. /**
  4174. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4175. */
  4176. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4177. for (var index = 0; index < 16; index++) {
  4178. result.m[index] = array[index + offset] * scale;
  4179. }
  4180. result._markAsUpdated();
  4181. };
  4182. /**
  4183. * Sets the passed matrix "result" with the 16 passed floats.
  4184. */
  4185. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4186. result.m[0] = initialM11;
  4187. result.m[1] = initialM12;
  4188. result.m[2] = initialM13;
  4189. result.m[3] = initialM14;
  4190. result.m[4] = initialM21;
  4191. result.m[5] = initialM22;
  4192. result.m[6] = initialM23;
  4193. result.m[7] = initialM24;
  4194. result.m[8] = initialM31;
  4195. result.m[9] = initialM32;
  4196. result.m[10] = initialM33;
  4197. result.m[11] = initialM34;
  4198. result.m[12] = initialM41;
  4199. result.m[13] = initialM42;
  4200. result.m[14] = initialM43;
  4201. result.m[15] = initialM44;
  4202. result._markAsUpdated();
  4203. };
  4204. /**
  4205. * Returns the index-th row of the current matrix as a new Vector4.
  4206. */
  4207. Matrix.prototype.getRow = function (index) {
  4208. if (index < 0 || index > 3) {
  4209. return null;
  4210. }
  4211. var i = index * 4;
  4212. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4213. };
  4214. /**
  4215. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4216. * Returns the updated Matrix.
  4217. */
  4218. Matrix.prototype.setRow = function (index, row) {
  4219. if (index < 0 || index > 3) {
  4220. return this;
  4221. }
  4222. var i = index * 4;
  4223. this.m[i + 0] = row.x;
  4224. this.m[i + 1] = row.y;
  4225. this.m[i + 2] = row.z;
  4226. this.m[i + 3] = row.w;
  4227. this._markAsUpdated();
  4228. return this;
  4229. };
  4230. /**
  4231. * Compute the transpose of the matrix.
  4232. * Returns a new Matrix.
  4233. */
  4234. Matrix.prototype.transpose = function () {
  4235. return Matrix.Transpose(this);
  4236. };
  4237. /**
  4238. * Compute the transpose of the matrix.
  4239. * Returns the current matrix.
  4240. */
  4241. Matrix.prototype.transposeToRef = function (result) {
  4242. Matrix.TransposeToRef(this, result);
  4243. return this;
  4244. };
  4245. /**
  4246. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4247. * Returns the updated Matrix.
  4248. */
  4249. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4250. if (index < 0 || index > 3) {
  4251. return this;
  4252. }
  4253. var i = index * 4;
  4254. this.m[i + 0] = x;
  4255. this.m[i + 1] = y;
  4256. this.m[i + 2] = z;
  4257. this.m[i + 3] = w;
  4258. this._markAsUpdated();
  4259. return this;
  4260. };
  4261. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4262. /**
  4263. * Static identity matrix to be used as readonly matrix
  4264. * Must not be updated.
  4265. */
  4266. get: function () {
  4267. return Matrix._identityReadOnly;
  4268. },
  4269. enumerable: true,
  4270. configurable: true
  4271. });
  4272. /**
  4273. * Returns a new Matrix set from the 16 passed floats.
  4274. */
  4275. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4276. var result = new Matrix();
  4277. result.m[0] = initialM11;
  4278. result.m[1] = initialM12;
  4279. result.m[2] = initialM13;
  4280. result.m[3] = initialM14;
  4281. result.m[4] = initialM21;
  4282. result.m[5] = initialM22;
  4283. result.m[6] = initialM23;
  4284. result.m[7] = initialM24;
  4285. result.m[8] = initialM31;
  4286. result.m[9] = initialM32;
  4287. result.m[10] = initialM33;
  4288. result.m[11] = initialM34;
  4289. result.m[12] = initialM41;
  4290. result.m[13] = initialM42;
  4291. result.m[14] = initialM43;
  4292. result.m[15] = initialM44;
  4293. return result;
  4294. };
  4295. /**
  4296. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4297. */
  4298. Matrix.Compose = function (scale, rotation, translation) {
  4299. var result = Matrix.Identity();
  4300. Matrix.ComposeToRef(scale, rotation, translation, result);
  4301. return result;
  4302. };
  4303. /**
  4304. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4305. */
  4306. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4307. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4308. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4309. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4310. result.setTranslation(translation);
  4311. };
  4312. /**
  4313. * Returns a new indentity Matrix.
  4314. */
  4315. Matrix.Identity = function () {
  4316. 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);
  4317. };
  4318. /**
  4319. * Sets the passed "result" as an identity matrix.
  4320. */
  4321. Matrix.IdentityToRef = function (result) {
  4322. 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);
  4323. };
  4324. /**
  4325. * Returns a new zero Matrix.
  4326. */
  4327. Matrix.Zero = function () {
  4328. 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);
  4329. };
  4330. /**
  4331. * Returns a new rotation matrix for "angle" radians around the X axis.
  4332. */
  4333. Matrix.RotationX = function (angle) {
  4334. var result = new Matrix();
  4335. Matrix.RotationXToRef(angle, result);
  4336. return result;
  4337. };
  4338. /**
  4339. * Returns a new Matrix as the passed inverted one.
  4340. */
  4341. Matrix.Invert = function (source) {
  4342. var result = new Matrix();
  4343. source.invertToRef(result);
  4344. return result;
  4345. };
  4346. /**
  4347. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4348. */
  4349. Matrix.RotationXToRef = function (angle, result) {
  4350. var s = Math.sin(angle);
  4351. var c = Math.cos(angle);
  4352. result.m[0] = 1.0;
  4353. result.m[15] = 1.0;
  4354. result.m[5] = c;
  4355. result.m[10] = c;
  4356. result.m[9] = -s;
  4357. result.m[6] = s;
  4358. result.m[1] = 0.0;
  4359. result.m[2] = 0.0;
  4360. result.m[3] = 0.0;
  4361. result.m[4] = 0.0;
  4362. result.m[7] = 0.0;
  4363. result.m[8] = 0.0;
  4364. result.m[11] = 0.0;
  4365. result.m[12] = 0.0;
  4366. result.m[13] = 0.0;
  4367. result.m[14] = 0.0;
  4368. result._markAsUpdated();
  4369. };
  4370. /**
  4371. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4372. */
  4373. Matrix.RotationY = function (angle) {
  4374. var result = new Matrix();
  4375. Matrix.RotationYToRef(angle, result);
  4376. return result;
  4377. };
  4378. /**
  4379. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4380. */
  4381. Matrix.RotationYToRef = function (angle, result) {
  4382. var s = Math.sin(angle);
  4383. var c = Math.cos(angle);
  4384. result.m[5] = 1.0;
  4385. result.m[15] = 1.0;
  4386. result.m[0] = c;
  4387. result.m[2] = -s;
  4388. result.m[8] = s;
  4389. result.m[10] = c;
  4390. result.m[1] = 0.0;
  4391. result.m[3] = 0.0;
  4392. result.m[4] = 0.0;
  4393. result.m[6] = 0.0;
  4394. result.m[7] = 0.0;
  4395. result.m[9] = 0.0;
  4396. result.m[11] = 0.0;
  4397. result.m[12] = 0.0;
  4398. result.m[13] = 0.0;
  4399. result.m[14] = 0.0;
  4400. result._markAsUpdated();
  4401. };
  4402. /**
  4403. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4404. */
  4405. Matrix.RotationZ = function (angle) {
  4406. var result = new Matrix();
  4407. Matrix.RotationZToRef(angle, result);
  4408. return result;
  4409. };
  4410. /**
  4411. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4412. */
  4413. Matrix.RotationZToRef = function (angle, result) {
  4414. var s = Math.sin(angle);
  4415. var c = Math.cos(angle);
  4416. result.m[10] = 1.0;
  4417. result.m[15] = 1.0;
  4418. result.m[0] = c;
  4419. result.m[1] = s;
  4420. result.m[4] = -s;
  4421. result.m[5] = c;
  4422. result.m[2] = 0.0;
  4423. result.m[3] = 0.0;
  4424. result.m[6] = 0.0;
  4425. result.m[7] = 0.0;
  4426. result.m[8] = 0.0;
  4427. result.m[9] = 0.0;
  4428. result.m[11] = 0.0;
  4429. result.m[12] = 0.0;
  4430. result.m[13] = 0.0;
  4431. result.m[14] = 0.0;
  4432. result._markAsUpdated();
  4433. };
  4434. /**
  4435. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4436. */
  4437. Matrix.RotationAxis = function (axis, angle) {
  4438. var result = Matrix.Zero();
  4439. Matrix.RotationAxisToRef(axis, angle, result);
  4440. return result;
  4441. };
  4442. /**
  4443. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4444. */
  4445. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4446. var s = Math.sin(-angle);
  4447. var c = Math.cos(-angle);
  4448. var c1 = 1 - c;
  4449. axis.normalize();
  4450. result.m[0] = (axis.x * axis.x) * c1 + c;
  4451. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4452. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4453. result.m[3] = 0.0;
  4454. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4455. result.m[5] = (axis.y * axis.y) * c1 + c;
  4456. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4457. result.m[7] = 0.0;
  4458. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4459. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4460. result.m[10] = (axis.z * axis.z) * c1 + c;
  4461. result.m[11] = 0.0;
  4462. result.m[15] = 1.0;
  4463. result._markAsUpdated();
  4464. };
  4465. /**
  4466. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4467. */
  4468. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4469. var result = new Matrix();
  4470. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4471. return result;
  4472. };
  4473. /**
  4474. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4475. */
  4476. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4477. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4478. this._tempQuaternion.toRotationMatrix(result);
  4479. };
  4480. /**
  4481. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4482. */
  4483. Matrix.Scaling = function (x, y, z) {
  4484. var result = Matrix.Zero();
  4485. Matrix.ScalingToRef(x, y, z, result);
  4486. return result;
  4487. };
  4488. /**
  4489. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4490. */
  4491. Matrix.ScalingToRef = function (x, y, z, result) {
  4492. result.m[0] = x;
  4493. result.m[1] = 0.0;
  4494. result.m[2] = 0.0;
  4495. result.m[3] = 0.0;
  4496. result.m[4] = 0.0;
  4497. result.m[5] = y;
  4498. result.m[6] = 0.0;
  4499. result.m[7] = 0.0;
  4500. result.m[8] = 0.0;
  4501. result.m[9] = 0.0;
  4502. result.m[10] = z;
  4503. result.m[11] = 0.0;
  4504. result.m[12] = 0.0;
  4505. result.m[13] = 0.0;
  4506. result.m[14] = 0.0;
  4507. result.m[15] = 1.0;
  4508. result._markAsUpdated();
  4509. };
  4510. /**
  4511. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4512. */
  4513. Matrix.Translation = function (x, y, z) {
  4514. var result = Matrix.Identity();
  4515. Matrix.TranslationToRef(x, y, z, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4520. */
  4521. Matrix.TranslationToRef = function (x, y, z, result) {
  4522. 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);
  4523. };
  4524. /**
  4525. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4526. */
  4527. Matrix.Lerp = function (startValue, endValue, gradient) {
  4528. var result = Matrix.Zero();
  4529. for (var index = 0; index < 16; index++) {
  4530. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4531. }
  4532. result._markAsUpdated();
  4533. return result;
  4534. };
  4535. /**
  4536. * Returns a new Matrix whose values are computed by :
  4537. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4538. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4539. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4540. */
  4541. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4542. var startScale = new Vector3(0, 0, 0);
  4543. var startRotation = new Quaternion();
  4544. var startTranslation = new Vector3(0, 0, 0);
  4545. startValue.decompose(startScale, startRotation, startTranslation);
  4546. var endScale = new Vector3(0, 0, 0);
  4547. var endRotation = new Quaternion();
  4548. var endTranslation = new Vector3(0, 0, 0);
  4549. endValue.decompose(endScale, endRotation, endTranslation);
  4550. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4551. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4552. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4553. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4554. };
  4555. /**
  4556. * 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".
  4557. * This methods works for a Left-Handed system.
  4558. */
  4559. Matrix.LookAtLH = function (eye, target, up) {
  4560. var result = Matrix.Zero();
  4561. Matrix.LookAtLHToRef(eye, target, up, result);
  4562. return result;
  4563. };
  4564. /**
  4565. * 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".
  4566. * This methods works for a Left-Handed system.
  4567. */
  4568. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4569. // Z axis
  4570. target.subtractToRef(eye, this._zAxis);
  4571. this._zAxis.normalize();
  4572. // X axis
  4573. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4574. if (this._xAxis.lengthSquared() === 0) {
  4575. this._xAxis.x = 1.0;
  4576. }
  4577. else {
  4578. this._xAxis.normalize();
  4579. }
  4580. // Y axis
  4581. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4582. this._yAxis.normalize();
  4583. // Eye angles
  4584. var ex = -Vector3.Dot(this._xAxis, eye);
  4585. var ey = -Vector3.Dot(this._yAxis, eye);
  4586. var ez = -Vector3.Dot(this._zAxis, eye);
  4587. 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);
  4588. };
  4589. /**
  4590. * 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".
  4591. * This methods works for a Right-Handed system.
  4592. */
  4593. Matrix.LookAtRH = function (eye, target, up) {
  4594. var result = Matrix.Zero();
  4595. Matrix.LookAtRHToRef(eye, target, up, result);
  4596. return result;
  4597. };
  4598. /**
  4599. * 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".
  4600. * This methods works for a Left-Handed system.
  4601. */
  4602. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4603. // Z axis
  4604. eye.subtractToRef(target, this._zAxis);
  4605. this._zAxis.normalize();
  4606. // X axis
  4607. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4608. if (this._xAxis.lengthSquared() === 0) {
  4609. this._xAxis.x = 1.0;
  4610. }
  4611. else {
  4612. this._xAxis.normalize();
  4613. }
  4614. // Y axis
  4615. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4616. this._yAxis.normalize();
  4617. // Eye angles
  4618. var ex = -Vector3.Dot(this._xAxis, eye);
  4619. var ey = -Vector3.Dot(this._yAxis, eye);
  4620. var ez = -Vector3.Dot(this._zAxis, eye);
  4621. 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);
  4622. };
  4623. /**
  4624. * 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.
  4625. */
  4626. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4627. var matrix = Matrix.Zero();
  4628. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4629. return matrix;
  4630. };
  4631. /**
  4632. * 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.
  4633. */
  4634. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4635. var n = znear;
  4636. var f = zfar;
  4637. var a = 2.0 / width;
  4638. var b = 2.0 / height;
  4639. var c = 2.0 / (f - n);
  4640. var d = -(f + n) / (f - n);
  4641. 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);
  4642. };
  4643. /**
  4644. * 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.
  4645. */
  4646. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4647. var matrix = Matrix.Zero();
  4648. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4649. return matrix;
  4650. };
  4651. /**
  4652. * 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.
  4653. */
  4654. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4655. var n = znear;
  4656. var f = zfar;
  4657. var a = 2.0 / (right - left);
  4658. var b = 2.0 / (top - bottom);
  4659. var c = 2.0 / (f - n);
  4660. var d = -(f + n) / (f - n);
  4661. var i0 = (left + right) / (left - right);
  4662. var i1 = (top + bottom) / (bottom - top);
  4663. 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);
  4664. };
  4665. /**
  4666. * 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.
  4667. */
  4668. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4669. var matrix = Matrix.Zero();
  4670. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4671. return matrix;
  4672. };
  4673. /**
  4674. * 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.
  4675. */
  4676. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4677. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4678. result.m[10] *= -1.0;
  4679. };
  4680. /**
  4681. * 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.
  4682. */
  4683. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4684. var matrix = Matrix.Zero();
  4685. var n = znear;
  4686. var f = zfar;
  4687. var a = 2.0 * n / width;
  4688. var b = 2.0 * n / height;
  4689. var c = (f + n) / (f - n);
  4690. var d = -2.0 * f * n / (f - n);
  4691. 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);
  4692. return matrix;
  4693. };
  4694. /**
  4695. * 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.
  4696. */
  4697. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4698. var matrix = Matrix.Zero();
  4699. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4700. return matrix;
  4701. };
  4702. /**
  4703. * 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.
  4704. */
  4705. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4706. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4707. var n = znear;
  4708. var f = zfar;
  4709. var t = 1.0 / (Math.tan(fov * 0.5));
  4710. var a = isVerticalFovFixed ? (t / aspect) : t;
  4711. var b = isVerticalFovFixed ? t : (t * aspect);
  4712. var c = (f + n) / (f - n);
  4713. var d = -2.0 * f * n / (f - n);
  4714. 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);
  4715. };
  4716. /**
  4717. * 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.
  4718. */
  4719. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4720. var matrix = Matrix.Zero();
  4721. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4722. return matrix;
  4723. };
  4724. /**
  4725. * 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.
  4726. */
  4727. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4728. //alternatively this could be expressed as:
  4729. // m = PerspectiveFovLHToRef
  4730. // m[10] *= -1.0;
  4731. // m[11] *= -1.0;
  4732. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4733. var n = znear;
  4734. var f = zfar;
  4735. var t = 1.0 / (Math.tan(fov * 0.5));
  4736. var a = isVerticalFovFixed ? (t / aspect) : t;
  4737. var b = isVerticalFovFixed ? t : (t * aspect);
  4738. var c = -(f + n) / (f - n);
  4739. var d = -2 * f * n / (f - n);
  4740. 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);
  4741. };
  4742. /**
  4743. * 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.
  4744. */
  4745. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4746. if (rightHanded === void 0) { rightHanded = false; }
  4747. var rightHandedFactor = rightHanded ? -1 : 1;
  4748. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4749. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4750. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4751. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4752. var xScale = 2.0 / (leftTan + rightTan);
  4753. var yScale = 2.0 / (upTan + downTan);
  4754. result.m[0] = xScale;
  4755. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4756. result.m[5] = yScale;
  4757. result.m[6] = result.m[7] = 0.0;
  4758. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4759. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4760. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4761. result.m[10] = -zfar / (znear - zfar);
  4762. result.m[11] = 1.0 * rightHandedFactor;
  4763. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4764. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4765. // result.m[14] = (znear * zfar) / (znear - zfar);
  4766. result._markAsUpdated();
  4767. };
  4768. /**
  4769. * Returns the final transformation matrix : world * view * projection * viewport
  4770. */
  4771. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4772. var cw = viewport.width;
  4773. var ch = viewport.height;
  4774. var cx = viewport.x;
  4775. var cy = viewport.y;
  4776. 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);
  4777. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4778. };
  4779. /**
  4780. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4781. */
  4782. Matrix.GetAsMatrix2x2 = function (matrix) {
  4783. return new Float32Array([
  4784. matrix.m[0], matrix.m[1],
  4785. matrix.m[4], matrix.m[5]
  4786. ]);
  4787. };
  4788. /**
  4789. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4790. */
  4791. Matrix.GetAsMatrix3x3 = function (matrix) {
  4792. return new Float32Array([
  4793. matrix.m[0], matrix.m[1], matrix.m[2],
  4794. matrix.m[4], matrix.m[5], matrix.m[6],
  4795. matrix.m[8], matrix.m[9], matrix.m[10]
  4796. ]);
  4797. };
  4798. /**
  4799. * Compute the transpose of the passed Matrix.
  4800. * Returns a new Matrix.
  4801. */
  4802. Matrix.Transpose = function (matrix) {
  4803. var result = new Matrix();
  4804. Matrix.TransposeToRef(matrix, result);
  4805. return result;
  4806. };
  4807. /**
  4808. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4809. */
  4810. Matrix.TransposeToRef = function (matrix, result) {
  4811. result.m[0] = matrix.m[0];
  4812. result.m[1] = matrix.m[4];
  4813. result.m[2] = matrix.m[8];
  4814. result.m[3] = matrix.m[12];
  4815. result.m[4] = matrix.m[1];
  4816. result.m[5] = matrix.m[5];
  4817. result.m[6] = matrix.m[9];
  4818. result.m[7] = matrix.m[13];
  4819. result.m[8] = matrix.m[2];
  4820. result.m[9] = matrix.m[6];
  4821. result.m[10] = matrix.m[10];
  4822. result.m[11] = matrix.m[14];
  4823. result.m[12] = matrix.m[3];
  4824. result.m[13] = matrix.m[7];
  4825. result.m[14] = matrix.m[11];
  4826. result.m[15] = matrix.m[15];
  4827. };
  4828. /**
  4829. * Returns a new Matrix as the reflection matrix across the passed plane.
  4830. */
  4831. Matrix.Reflection = function (plane) {
  4832. var matrix = new Matrix();
  4833. Matrix.ReflectionToRef(plane, matrix);
  4834. return matrix;
  4835. };
  4836. /**
  4837. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4838. */
  4839. Matrix.ReflectionToRef = function (plane, result) {
  4840. plane.normalize();
  4841. var x = plane.normal.x;
  4842. var y = plane.normal.y;
  4843. var z = plane.normal.z;
  4844. var temp = -2 * x;
  4845. var temp2 = -2 * y;
  4846. var temp3 = -2 * z;
  4847. result.m[0] = (temp * x) + 1;
  4848. result.m[1] = temp2 * x;
  4849. result.m[2] = temp3 * x;
  4850. result.m[3] = 0.0;
  4851. result.m[4] = temp * y;
  4852. result.m[5] = (temp2 * y) + 1;
  4853. result.m[6] = temp3 * y;
  4854. result.m[7] = 0.0;
  4855. result.m[8] = temp * z;
  4856. result.m[9] = temp2 * z;
  4857. result.m[10] = (temp3 * z) + 1;
  4858. result.m[11] = 0.0;
  4859. result.m[12] = temp * plane.d;
  4860. result.m[13] = temp2 * plane.d;
  4861. result.m[14] = temp3 * plane.d;
  4862. result.m[15] = 1.0;
  4863. result._markAsUpdated();
  4864. };
  4865. /**
  4866. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4867. */
  4868. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4869. result.m[0] = xaxis.x;
  4870. result.m[1] = xaxis.y;
  4871. result.m[2] = xaxis.z;
  4872. result.m[3] = 0.0;
  4873. result.m[4] = yaxis.x;
  4874. result.m[5] = yaxis.y;
  4875. result.m[6] = yaxis.z;
  4876. result.m[7] = 0.0;
  4877. result.m[8] = zaxis.x;
  4878. result.m[9] = zaxis.y;
  4879. result.m[10] = zaxis.z;
  4880. result.m[11] = 0.0;
  4881. result.m[12] = 0.0;
  4882. result.m[13] = 0.0;
  4883. result.m[14] = 0.0;
  4884. result.m[15] = 1.0;
  4885. result._markAsUpdated();
  4886. };
  4887. /**
  4888. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4889. */
  4890. Matrix.FromQuaternionToRef = function (quat, result) {
  4891. var xx = quat.x * quat.x;
  4892. var yy = quat.y * quat.y;
  4893. var zz = quat.z * quat.z;
  4894. var xy = quat.x * quat.y;
  4895. var zw = quat.z * quat.w;
  4896. var zx = quat.z * quat.x;
  4897. var yw = quat.y * quat.w;
  4898. var yz = quat.y * quat.z;
  4899. var xw = quat.x * quat.w;
  4900. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4901. result.m[1] = 2.0 * (xy + zw);
  4902. result.m[2] = 2.0 * (zx - yw);
  4903. result.m[3] = 0.0;
  4904. result.m[4] = 2.0 * (xy - zw);
  4905. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4906. result.m[6] = 2.0 * (yz + xw);
  4907. result.m[7] = 0.0;
  4908. result.m[8] = 2.0 * (zx + yw);
  4909. result.m[9] = 2.0 * (yz - xw);
  4910. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4911. result.m[11] = 0.0;
  4912. result.m[12] = 0.0;
  4913. result.m[13] = 0.0;
  4914. result.m[14] = 0.0;
  4915. result.m[15] = 1.0;
  4916. result._markAsUpdated();
  4917. };
  4918. Matrix._tempQuaternion = new Quaternion();
  4919. Matrix._xAxis = Vector3.Zero();
  4920. Matrix._yAxis = Vector3.Zero();
  4921. Matrix._zAxis = Vector3.Zero();
  4922. Matrix._updateFlagSeed = 0;
  4923. Matrix._identityReadOnly = Matrix.Identity();
  4924. return Matrix;
  4925. }());
  4926. BABYLON.Matrix = Matrix;
  4927. var Plane = /** @class */ (function () {
  4928. /**
  4929. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4930. */
  4931. function Plane(a, b, c, d) {
  4932. this.normal = new Vector3(a, b, c);
  4933. this.d = d;
  4934. }
  4935. /**
  4936. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4937. */
  4938. Plane.prototype.asArray = function () {
  4939. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4940. };
  4941. // Methods
  4942. /**
  4943. * Returns a new plane copied from the current Plane.
  4944. */
  4945. Plane.prototype.clone = function () {
  4946. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4947. };
  4948. /**
  4949. * Returns the string "Plane".
  4950. */
  4951. Plane.prototype.getClassName = function () {
  4952. return "Plane";
  4953. };
  4954. /**
  4955. * Returns the Plane hash code.
  4956. */
  4957. Plane.prototype.getHashCode = function () {
  4958. var hash = this.normal.getHashCode();
  4959. hash = (hash * 397) ^ (this.d || 0);
  4960. return hash;
  4961. };
  4962. /**
  4963. * Normalize the current Plane in place.
  4964. * Returns the updated Plane.
  4965. */
  4966. Plane.prototype.normalize = function () {
  4967. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4968. var magnitude = 0.0;
  4969. if (norm !== 0) {
  4970. magnitude = 1.0 / norm;
  4971. }
  4972. this.normal.x *= magnitude;
  4973. this.normal.y *= magnitude;
  4974. this.normal.z *= magnitude;
  4975. this.d *= magnitude;
  4976. return this;
  4977. };
  4978. /**
  4979. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4980. */
  4981. Plane.prototype.transform = function (transformation) {
  4982. var transposedMatrix = Matrix.Transpose(transformation);
  4983. var x = this.normal.x;
  4984. var y = this.normal.y;
  4985. var z = this.normal.z;
  4986. var d = this.d;
  4987. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4988. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4989. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4990. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4991. return new Plane(normalX, normalY, normalZ, finalD);
  4992. };
  4993. /**
  4994. * Returns the dot product (float) of the point coordinates and the plane normal.
  4995. */
  4996. Plane.prototype.dotCoordinate = function (point) {
  4997. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4998. };
  4999. /**
  5000. * Updates the current Plane from the plane defined by the three passed points.
  5001. * Returns the updated Plane.
  5002. */
  5003. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5004. var x1 = point2.x - point1.x;
  5005. var y1 = point2.y - point1.y;
  5006. var z1 = point2.z - point1.z;
  5007. var x2 = point3.x - point1.x;
  5008. var y2 = point3.y - point1.y;
  5009. var z2 = point3.z - point1.z;
  5010. var yz = (y1 * z2) - (z1 * y2);
  5011. var xz = (z1 * x2) - (x1 * z2);
  5012. var xy = (x1 * y2) - (y1 * x2);
  5013. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5014. var invPyth;
  5015. if (pyth !== 0) {
  5016. invPyth = 1.0 / pyth;
  5017. }
  5018. else {
  5019. invPyth = 0.0;
  5020. }
  5021. this.normal.x = yz * invPyth;
  5022. this.normal.y = xz * invPyth;
  5023. this.normal.z = xy * invPyth;
  5024. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5025. return this;
  5026. };
  5027. /**
  5028. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5029. */
  5030. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5031. var dot = Vector3.Dot(this.normal, direction);
  5032. return (dot <= epsilon);
  5033. };
  5034. /**
  5035. * Returns the signed distance (float) from the passed point to the Plane.
  5036. */
  5037. Plane.prototype.signedDistanceTo = function (point) {
  5038. return Vector3.Dot(point, this.normal) + this.d;
  5039. };
  5040. // Statics
  5041. /**
  5042. * Returns a new Plane from the passed array.
  5043. */
  5044. Plane.FromArray = function (array) {
  5045. return new Plane(array[0], array[1], array[2], array[3]);
  5046. };
  5047. /**
  5048. * Returns a new Plane defined by the three passed points.
  5049. */
  5050. Plane.FromPoints = function (point1, point2, point3) {
  5051. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5052. result.copyFromPoints(point1, point2, point3);
  5053. return result;
  5054. };
  5055. /**
  5056. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5057. * Note : the vector "normal" is updated because normalized.
  5058. */
  5059. Plane.FromPositionAndNormal = function (origin, normal) {
  5060. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5061. normal.normalize();
  5062. result.normal = normal;
  5063. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5064. return result;
  5065. };
  5066. /**
  5067. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5068. */
  5069. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5070. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5071. return Vector3.Dot(point, normal) + d;
  5072. };
  5073. return Plane;
  5074. }());
  5075. BABYLON.Plane = Plane;
  5076. var Viewport = /** @class */ (function () {
  5077. /**
  5078. * Creates a Viewport object located at (x, y) and sized (width, height).
  5079. */
  5080. function Viewport(x, y, width, height) {
  5081. this.x = x;
  5082. this.y = y;
  5083. this.width = width;
  5084. this.height = height;
  5085. }
  5086. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5087. if (renderWidthOrEngine.getRenderWidth) {
  5088. var engine = renderWidthOrEngine;
  5089. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5090. }
  5091. var renderWidth = renderWidthOrEngine;
  5092. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5093. };
  5094. /**
  5095. * Returns a new Viewport copied from the current one.
  5096. */
  5097. Viewport.prototype.clone = function () {
  5098. return new Viewport(this.x, this.y, this.width, this.height);
  5099. };
  5100. return Viewport;
  5101. }());
  5102. BABYLON.Viewport = Viewport;
  5103. var Frustum = /** @class */ (function () {
  5104. function Frustum() {
  5105. }
  5106. /**
  5107. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5108. */
  5109. Frustum.GetPlanes = function (transform) {
  5110. var frustumPlanes = [];
  5111. for (var index = 0; index < 6; index++) {
  5112. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5113. }
  5114. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5115. return frustumPlanes;
  5116. };
  5117. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5118. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5119. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5120. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5121. frustumPlane.d = transform.m[15] + transform.m[14];
  5122. frustumPlane.normalize();
  5123. };
  5124. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5125. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5126. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5127. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5128. frustumPlane.d = transform.m[15] - transform.m[14];
  5129. frustumPlane.normalize();
  5130. };
  5131. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5132. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5133. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5134. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5135. frustumPlane.d = transform.m[15] + transform.m[12];
  5136. frustumPlane.normalize();
  5137. };
  5138. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5139. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5140. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5141. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5142. frustumPlane.d = transform.m[15] - transform.m[12];
  5143. frustumPlane.normalize();
  5144. };
  5145. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5146. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5147. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5148. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5149. frustumPlane.d = transform.m[15] - transform.m[13];
  5150. frustumPlane.normalize();
  5151. };
  5152. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5153. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5154. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5155. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5156. frustumPlane.d = transform.m[15] + transform.m[13];
  5157. frustumPlane.normalize();
  5158. };
  5159. /**
  5160. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5161. */
  5162. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5163. // Near
  5164. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5165. // Far
  5166. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5167. // Left
  5168. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5169. // Right
  5170. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5171. // Top
  5172. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5173. // Bottom
  5174. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5175. };
  5176. return Frustum;
  5177. }());
  5178. BABYLON.Frustum = Frustum;
  5179. var Space;
  5180. (function (Space) {
  5181. Space[Space["LOCAL"] = 0] = "LOCAL";
  5182. Space[Space["WORLD"] = 1] = "WORLD";
  5183. Space[Space["BONE"] = 2] = "BONE";
  5184. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5185. var Axis = /** @class */ (function () {
  5186. function Axis() {
  5187. }
  5188. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5189. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5190. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5191. return Axis;
  5192. }());
  5193. BABYLON.Axis = Axis;
  5194. ;
  5195. var BezierCurve = /** @class */ (function () {
  5196. function BezierCurve() {
  5197. }
  5198. /**
  5199. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5200. */
  5201. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5202. // Extract X (which is equal to time here)
  5203. var f0 = 1 - 3 * x2 + 3 * x1;
  5204. var f1 = 3 * x2 - 6 * x1;
  5205. var f2 = 3 * x1;
  5206. var refinedT = t;
  5207. for (var i = 0; i < 5; i++) {
  5208. var refinedT2 = refinedT * refinedT;
  5209. var refinedT3 = refinedT2 * refinedT;
  5210. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5211. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5212. refinedT -= (x - t) * slope;
  5213. refinedT = Math.min(1, Math.max(0, refinedT));
  5214. }
  5215. // Resolve cubic bezier for the given x
  5216. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5217. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5218. Math.pow(refinedT, 3);
  5219. };
  5220. return BezierCurve;
  5221. }());
  5222. BABYLON.BezierCurve = BezierCurve;
  5223. var Orientation;
  5224. (function (Orientation) {
  5225. Orientation[Orientation["CW"] = 0] = "CW";
  5226. Orientation[Orientation["CCW"] = 1] = "CCW";
  5227. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5228. var Angle = /** @class */ (function () {
  5229. /**
  5230. * Creates an Angle object of "radians" radians (float).
  5231. */
  5232. function Angle(radians) {
  5233. var _this = this;
  5234. /**
  5235. * Returns the Angle value in degrees (float).
  5236. */
  5237. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5238. /**
  5239. * Returns the Angle value in radians (float).
  5240. */
  5241. this.radians = function () { return _this._radians; };
  5242. this._radians = radians;
  5243. if (this._radians < 0.0)
  5244. this._radians += (2.0 * Math.PI);
  5245. }
  5246. /**
  5247. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5248. */
  5249. Angle.BetweenTwoPoints = function (a, b) {
  5250. var delta = b.subtract(a);
  5251. var theta = Math.atan2(delta.y, delta.x);
  5252. return new Angle(theta);
  5253. };
  5254. /**
  5255. * Returns a new Angle object from the passed float in radians.
  5256. */
  5257. Angle.FromRadians = function (radians) {
  5258. return new Angle(radians);
  5259. };
  5260. /**
  5261. * Returns a new Angle object from the passed float in degrees.
  5262. */
  5263. Angle.FromDegrees = function (degrees) {
  5264. return new Angle(degrees * Math.PI / 180.0);
  5265. };
  5266. return Angle;
  5267. }());
  5268. BABYLON.Angle = Angle;
  5269. var Arc2 = /** @class */ (function () {
  5270. /**
  5271. * Creates an Arc object from the three passed points : start, middle and end.
  5272. */
  5273. function Arc2(startPoint, midPoint, endPoint) {
  5274. this.startPoint = startPoint;
  5275. this.midPoint = midPoint;
  5276. this.endPoint = endPoint;
  5277. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5278. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5279. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5280. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5281. 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);
  5282. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5283. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5284. var a1 = this.startAngle.degrees();
  5285. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5286. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5287. // angles correction
  5288. if (a2 - a1 > +180.0)
  5289. a2 -= 360.0;
  5290. if (a2 - a1 < -180.0)
  5291. a2 += 360.0;
  5292. if (a3 - a2 > +180.0)
  5293. a3 -= 360.0;
  5294. if (a3 - a2 < -180.0)
  5295. a3 += 360.0;
  5296. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5297. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5298. }
  5299. return Arc2;
  5300. }());
  5301. BABYLON.Arc2 = Arc2;
  5302. var Path2 = /** @class */ (function () {
  5303. /**
  5304. * Creates a Path2 object from the starting 2D coordinates x and y.
  5305. */
  5306. function Path2(x, y) {
  5307. this._points = new Array();
  5308. this._length = 0.0;
  5309. this.closed = false;
  5310. this._points.push(new Vector2(x, y));
  5311. }
  5312. /**
  5313. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5314. * Returns the updated Path2.
  5315. */
  5316. Path2.prototype.addLineTo = function (x, y) {
  5317. if (this.closed) {
  5318. //Tools.Error("cannot add lines to closed paths");
  5319. return this;
  5320. }
  5321. var newPoint = new Vector2(x, y);
  5322. var previousPoint = this._points[this._points.length - 1];
  5323. this._points.push(newPoint);
  5324. this._length += newPoint.subtract(previousPoint).length();
  5325. return this;
  5326. };
  5327. /**
  5328. * 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.
  5329. * Returns the updated Path2.
  5330. */
  5331. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5332. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5333. if (this.closed) {
  5334. //Tools.Error("cannot add arcs to closed paths");
  5335. return this;
  5336. }
  5337. var startPoint = this._points[this._points.length - 1];
  5338. var midPoint = new Vector2(midX, midY);
  5339. var endPoint = new Vector2(endX, endY);
  5340. var arc = new Arc2(startPoint, midPoint, endPoint);
  5341. var increment = arc.angle.radians() / numberOfSegments;
  5342. if (arc.orientation === Orientation.CW)
  5343. increment *= -1;
  5344. var currentAngle = arc.startAngle.radians() + increment;
  5345. for (var i = 0; i < numberOfSegments; i++) {
  5346. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5347. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5348. this.addLineTo(x, y);
  5349. currentAngle += increment;
  5350. }
  5351. return this;
  5352. };
  5353. /**
  5354. * Closes the Path2.
  5355. * Returns the Path2.
  5356. */
  5357. Path2.prototype.close = function () {
  5358. this.closed = true;
  5359. return this;
  5360. };
  5361. /**
  5362. * Returns the Path2 total length (float).
  5363. */
  5364. Path2.prototype.length = function () {
  5365. var result = this._length;
  5366. if (!this.closed) {
  5367. var lastPoint = this._points[this._points.length - 1];
  5368. var firstPoint = this._points[0];
  5369. result += (firstPoint.subtract(lastPoint).length());
  5370. }
  5371. return result;
  5372. };
  5373. /**
  5374. * Returns the Path2 internal array of points.
  5375. */
  5376. Path2.prototype.getPoints = function () {
  5377. return this._points;
  5378. };
  5379. /**
  5380. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5381. */
  5382. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5383. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5384. //Tools.Error("normalized length position should be between 0 and 1.");
  5385. return Vector2.Zero();
  5386. }
  5387. var lengthPosition = normalizedLengthPosition * this.length();
  5388. var previousOffset = 0;
  5389. for (var i = 0; i < this._points.length; i++) {
  5390. var j = (i + 1) % this._points.length;
  5391. var a = this._points[i];
  5392. var b = this._points[j];
  5393. var bToA = b.subtract(a);
  5394. var nextOffset = (bToA.length() + previousOffset);
  5395. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5396. var dir = bToA.normalize();
  5397. var localOffset = lengthPosition - previousOffset;
  5398. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5399. }
  5400. previousOffset = nextOffset;
  5401. }
  5402. //Tools.Error("internal error");
  5403. return Vector2.Zero();
  5404. };
  5405. /**
  5406. * Returns a new Path2 starting at the coordinates (x, y).
  5407. */
  5408. Path2.StartingAt = function (x, y) {
  5409. return new Path2(x, y);
  5410. };
  5411. return Path2;
  5412. }());
  5413. BABYLON.Path2 = Path2;
  5414. var Path3D = /** @class */ (function () {
  5415. /**
  5416. * new Path3D(path, normal, raw)
  5417. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5418. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5419. * path : an array of Vector3, the curve axis of the Path3D
  5420. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5421. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5422. */
  5423. function Path3D(path, firstNormal, raw) {
  5424. if (firstNormal === void 0) { firstNormal = null; }
  5425. this.path = path;
  5426. this._curve = new Array();
  5427. this._distances = new Array();
  5428. this._tangents = new Array();
  5429. this._normals = new Array();
  5430. this._binormals = new Array();
  5431. for (var p = 0; p < path.length; p++) {
  5432. this._curve[p] = path[p].clone(); // hard copy
  5433. }
  5434. this._raw = raw || false;
  5435. this._compute(firstNormal);
  5436. }
  5437. /**
  5438. * Returns the Path3D array of successive Vector3 designing its curve.
  5439. */
  5440. Path3D.prototype.getCurve = function () {
  5441. return this._curve;
  5442. };
  5443. /**
  5444. * Returns an array populated with tangent vectors on each Path3D curve point.
  5445. */
  5446. Path3D.prototype.getTangents = function () {
  5447. return this._tangents;
  5448. };
  5449. /**
  5450. * Returns an array populated with normal vectors on each Path3D curve point.
  5451. */
  5452. Path3D.prototype.getNormals = function () {
  5453. return this._normals;
  5454. };
  5455. /**
  5456. * Returns an array populated with binormal vectors on each Path3D curve point.
  5457. */
  5458. Path3D.prototype.getBinormals = function () {
  5459. return this._binormals;
  5460. };
  5461. /**
  5462. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5463. */
  5464. Path3D.prototype.getDistances = function () {
  5465. return this._distances;
  5466. };
  5467. /**
  5468. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5469. * Returns the same object updated.
  5470. */
  5471. Path3D.prototype.update = function (path, firstNormal) {
  5472. if (firstNormal === void 0) { firstNormal = null; }
  5473. for (var p = 0; p < path.length; p++) {
  5474. this._curve[p].x = path[p].x;
  5475. this._curve[p].y = path[p].y;
  5476. this._curve[p].z = path[p].z;
  5477. }
  5478. this._compute(firstNormal);
  5479. return this;
  5480. };
  5481. // private function compute() : computes tangents, normals and binormals
  5482. Path3D.prototype._compute = function (firstNormal) {
  5483. var l = this._curve.length;
  5484. // first and last tangents
  5485. this._tangents[0] = this._getFirstNonNullVector(0);
  5486. if (!this._raw) {
  5487. this._tangents[0].normalize();
  5488. }
  5489. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5490. if (!this._raw) {
  5491. this._tangents[l - 1].normalize();
  5492. }
  5493. // normals and binormals at first point : arbitrary vector with _normalVector()
  5494. var tg0 = this._tangents[0];
  5495. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5496. this._normals[0] = pp0;
  5497. if (!this._raw) {
  5498. this._normals[0].normalize();
  5499. }
  5500. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5501. if (!this._raw) {
  5502. this._binormals[0].normalize();
  5503. }
  5504. this._distances[0] = 0.0;
  5505. // normals and binormals : next points
  5506. var prev; // previous vector (segment)
  5507. var cur; // current vector (segment)
  5508. var curTang; // current tangent
  5509. // previous normal
  5510. var prevBinor; // previous binormal
  5511. for (var i = 1; i < l; i++) {
  5512. // tangents
  5513. prev = this._getLastNonNullVector(i);
  5514. if (i < l - 1) {
  5515. cur = this._getFirstNonNullVector(i);
  5516. this._tangents[i] = prev.add(cur);
  5517. this._tangents[i].normalize();
  5518. }
  5519. this._distances[i] = this._distances[i - 1] + prev.length();
  5520. // normals and binormals
  5521. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5522. curTang = this._tangents[i];
  5523. prevBinor = this._binormals[i - 1];
  5524. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5525. if (!this._raw) {
  5526. this._normals[i].normalize();
  5527. }
  5528. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5529. if (!this._raw) {
  5530. this._binormals[i].normalize();
  5531. }
  5532. }
  5533. };
  5534. // private function getFirstNonNullVector(index)
  5535. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5536. Path3D.prototype._getFirstNonNullVector = function (index) {
  5537. var i = 1;
  5538. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5539. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5540. i++;
  5541. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5542. }
  5543. return nNVector;
  5544. };
  5545. // private function getLastNonNullVector(index)
  5546. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5547. Path3D.prototype._getLastNonNullVector = function (index) {
  5548. var i = 1;
  5549. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5550. while (nLVector.length() === 0 && index > i + 1) {
  5551. i++;
  5552. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5553. }
  5554. return nLVector;
  5555. };
  5556. // private function normalVector(v0, vt, va) :
  5557. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5558. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5559. Path3D.prototype._normalVector = function (v0, vt, va) {
  5560. var normal0;
  5561. var tgl = vt.length();
  5562. if (tgl === 0.0) {
  5563. tgl = 1.0;
  5564. }
  5565. if (va === undefined || va === null) {
  5566. var point;
  5567. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5568. point = new Vector3(0.0, -1.0, 0.0);
  5569. }
  5570. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5571. point = new Vector3(1.0, 0.0, 0.0);
  5572. }
  5573. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5574. point = new Vector3(0.0, 0.0, 1.0);
  5575. }
  5576. else {
  5577. point = Vector3.Zero();
  5578. }
  5579. normal0 = Vector3.Cross(vt, point);
  5580. }
  5581. else {
  5582. normal0 = Vector3.Cross(vt, va);
  5583. Vector3.CrossToRef(normal0, vt, normal0);
  5584. }
  5585. normal0.normalize();
  5586. return normal0;
  5587. };
  5588. return Path3D;
  5589. }());
  5590. BABYLON.Path3D = Path3D;
  5591. var Curve3 = /** @class */ (function () {
  5592. /**
  5593. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5594. * A Curve3 is designed from a series of successive Vector3.
  5595. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5596. */
  5597. function Curve3(points) {
  5598. this._length = 0.0;
  5599. this._points = points;
  5600. this._length = this._computeLength(points);
  5601. }
  5602. /**
  5603. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5604. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5605. * @param v1 (Vector3) the control point
  5606. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5607. * @param nbPoints (integer) the wanted number of points in the curve
  5608. */
  5609. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5610. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5611. var bez = new Array();
  5612. var equation = function (t, val0, val1, val2) {
  5613. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5614. return res;
  5615. };
  5616. for (var i = 0; i <= nbPoints; i++) {
  5617. 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)));
  5618. }
  5619. return new Curve3(bez);
  5620. };
  5621. /**
  5622. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5623. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5624. * @param v1 (Vector3) the first control point
  5625. * @param v2 (Vector3) the second control point
  5626. * @param v3 (Vector3) the end point of the Cubic Bezier
  5627. * @param nbPoints (integer) the wanted number of points in the curve
  5628. */
  5629. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5630. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5631. var bez = new Array();
  5632. var equation = function (t, val0, val1, val2, val3) {
  5633. 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;
  5634. return res;
  5635. };
  5636. for (var i = 0; i <= nbPoints; i++) {
  5637. 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)));
  5638. }
  5639. return new Curve3(bez);
  5640. };
  5641. /**
  5642. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5643. * @param p1 (Vector3) the origin point of the Hermite Spline
  5644. * @param t1 (Vector3) the tangent vector at the origin point
  5645. * @param p2 (Vector3) the end point of the Hermite Spline
  5646. * @param t2 (Vector3) the tangent vector at the end point
  5647. * @param nbPoints (integer) the wanted number of points in the curve
  5648. */
  5649. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5650. var hermite = new Array();
  5651. var step = 1.0 / nbPoints;
  5652. for (var i = 0; i <= nbPoints; i++) {
  5653. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5654. }
  5655. return new Curve3(hermite);
  5656. };
  5657. /**
  5658. * Returns a Curve3 object along a CatmullRom Spline curve :
  5659. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5660. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5661. */
  5662. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5663. var totalPoints = new Array();
  5664. totalPoints.push(points[0].clone());
  5665. Array.prototype.push.apply(totalPoints, points);
  5666. totalPoints.push(points[points.length - 1].clone());
  5667. var catmullRom = new Array();
  5668. var step = 1.0 / nbPoints;
  5669. var amount = 0.0;
  5670. for (var i = 0; i < totalPoints.length - 3; i++) {
  5671. amount = 0;
  5672. for (var c = 0; c < nbPoints; c++) {
  5673. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5674. amount += step;
  5675. }
  5676. }
  5677. i--;
  5678. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5679. return new Curve3(catmullRom);
  5680. };
  5681. /**
  5682. * Returns the Curve3 stored array of successive Vector3
  5683. */
  5684. Curve3.prototype.getPoints = function () {
  5685. return this._points;
  5686. };
  5687. /**
  5688. * Returns the computed length (float) of the curve.
  5689. */
  5690. Curve3.prototype.length = function () {
  5691. return this._length;
  5692. };
  5693. /**
  5694. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5695. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5696. * curveA and curveB keep unchanged.
  5697. */
  5698. Curve3.prototype.continue = function (curve) {
  5699. var lastPoint = this._points[this._points.length - 1];
  5700. var continuedPoints = this._points.slice();
  5701. var curvePoints = curve.getPoints();
  5702. for (var i = 1; i < curvePoints.length; i++) {
  5703. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5704. }
  5705. var continuedCurve = new Curve3(continuedPoints);
  5706. return continuedCurve;
  5707. };
  5708. Curve3.prototype._computeLength = function (path) {
  5709. var l = 0;
  5710. for (var i = 1; i < path.length; i++) {
  5711. l += (path[i].subtract(path[i - 1])).length();
  5712. }
  5713. return l;
  5714. };
  5715. return Curve3;
  5716. }());
  5717. BABYLON.Curve3 = Curve3;
  5718. // Vertex formats
  5719. var PositionNormalVertex = /** @class */ (function () {
  5720. function PositionNormalVertex(position, normal) {
  5721. if (position === void 0) { position = Vector3.Zero(); }
  5722. if (normal === void 0) { normal = Vector3.Up(); }
  5723. this.position = position;
  5724. this.normal = normal;
  5725. }
  5726. PositionNormalVertex.prototype.clone = function () {
  5727. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5728. };
  5729. return PositionNormalVertex;
  5730. }());
  5731. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5732. var PositionNormalTextureVertex = /** @class */ (function () {
  5733. function PositionNormalTextureVertex(position, normal, uv) {
  5734. if (position === void 0) { position = Vector3.Zero(); }
  5735. if (normal === void 0) { normal = Vector3.Up(); }
  5736. if (uv === void 0) { uv = Vector2.Zero(); }
  5737. this.position = position;
  5738. this.normal = normal;
  5739. this.uv = uv;
  5740. }
  5741. PositionNormalTextureVertex.prototype.clone = function () {
  5742. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5743. };
  5744. return PositionNormalTextureVertex;
  5745. }());
  5746. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5747. // Temporary pre-allocated objects for engine internal use
  5748. // usage in any internal function :
  5749. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5750. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5751. var Tmp = /** @class */ (function () {
  5752. function Tmp() {
  5753. }
  5754. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5755. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5756. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5757. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5758. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5759. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5760. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5761. Matrix.Zero(), Matrix.Zero(),
  5762. Matrix.Zero(), Matrix.Zero(),
  5763. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5764. return Tmp;
  5765. }());
  5766. BABYLON.Tmp = Tmp;
  5767. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5768. var MathTmp = /** @class */ (function () {
  5769. function MathTmp() {
  5770. }
  5771. MathTmp.Vector3 = [Vector3.Zero()];
  5772. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5773. MathTmp.Quaternion = [Quaternion.Zero()];
  5774. return MathTmp;
  5775. }());
  5776. })(BABYLON || (BABYLON = {}));
  5777. //# sourceMappingURL=babylon.math.js.map
  5778. var BABYLON;
  5779. (function (BABYLON) {
  5780. var Scalar = /** @class */ (function () {
  5781. function Scalar() {
  5782. }
  5783. /**
  5784. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5785. */
  5786. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5787. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5788. var num = a - b;
  5789. return -epsilon <= num && num <= epsilon;
  5790. };
  5791. /**
  5792. * Returns a string : the upper case translation of the number i to hexadecimal.
  5793. */
  5794. Scalar.ToHex = function (i) {
  5795. var str = i.toString(16);
  5796. if (i <= 15) {
  5797. return ("0" + str).toUpperCase();
  5798. }
  5799. return str.toUpperCase();
  5800. };
  5801. /**
  5802. * Returns -1 if value is negative and +1 is value is positive.
  5803. * Returns the value itself if it's equal to zero.
  5804. */
  5805. Scalar.Sign = function (value) {
  5806. value = +value; // convert to a number
  5807. if (value === 0 || isNaN(value))
  5808. return value;
  5809. return value > 0 ? 1 : -1;
  5810. };
  5811. /**
  5812. * Returns the value itself if it's between min and max.
  5813. * Returns min if the value is lower than min.
  5814. * Returns max if the value is greater than max.
  5815. */
  5816. Scalar.Clamp = function (value, min, max) {
  5817. if (min === void 0) { min = 0; }
  5818. if (max === void 0) { max = 1; }
  5819. return Math.min(max, Math.max(min, value));
  5820. };
  5821. /**
  5822. * Returns the log2 of value.
  5823. */
  5824. Scalar.Log2 = function (value) {
  5825. return Math.log(value) * Math.LOG2E;
  5826. };
  5827. /**
  5828. * Loops the value, so that it is never larger than length and never smaller than 0.
  5829. *
  5830. * This is similar to the modulo operator but it works with floating point numbers.
  5831. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5832. * With t = 5 and length = 2.5, the result would be 0.0.
  5833. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5834. */
  5835. Scalar.Repeat = function (value, length) {
  5836. return value - Math.floor(value / length) * length;
  5837. };
  5838. /**
  5839. * Normalize the value between 0.0 and 1.0 using min and max values
  5840. */
  5841. Scalar.Normalize = function (value, min, max) {
  5842. return (value - min) / (max - min);
  5843. };
  5844. /**
  5845. * Denormalize the value from 0.0 and 1.0 using min and max values
  5846. */
  5847. Scalar.Denormalize = function (normalized, min, max) {
  5848. return (normalized * (max - min) + min);
  5849. };
  5850. /**
  5851. * Calculates the shortest difference between two given angles given in degrees.
  5852. */
  5853. Scalar.DeltaAngle = function (current, target) {
  5854. var num = Scalar.Repeat(target - current, 360.0);
  5855. if (num > 180.0) {
  5856. num -= 360.0;
  5857. }
  5858. return num;
  5859. };
  5860. /**
  5861. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5862. *
  5863. * The returned value will move back and forth between 0 and length
  5864. */
  5865. Scalar.PingPong = function (tx, length) {
  5866. var t = Scalar.Repeat(tx, length * 2.0);
  5867. return length - Math.abs(t - length);
  5868. };
  5869. /**
  5870. * Interpolates between min and max with smoothing at the limits.
  5871. *
  5872. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5873. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5874. */
  5875. Scalar.SmoothStep = function (from, to, tx) {
  5876. var t = Scalar.Clamp(tx);
  5877. t = -2.0 * t * t * t + 3.0 * t * t;
  5878. return to * t + from * (1.0 - t);
  5879. };
  5880. /**
  5881. * Moves a value current towards target.
  5882. *
  5883. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5884. * Negative values of maxDelta pushes the value away from target.
  5885. */
  5886. Scalar.MoveTowards = function (current, target, maxDelta) {
  5887. var result = 0;
  5888. if (Math.abs(target - current) <= maxDelta) {
  5889. result = target;
  5890. }
  5891. else {
  5892. result = current + Scalar.Sign(target - current) * maxDelta;
  5893. }
  5894. return result;
  5895. };
  5896. /**
  5897. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5898. *
  5899. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5900. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5901. */
  5902. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5903. var num = Scalar.DeltaAngle(current, target);
  5904. var result = 0;
  5905. if (-maxDelta < num && num < maxDelta) {
  5906. result = target;
  5907. }
  5908. else {
  5909. target = current + num;
  5910. result = Scalar.MoveTowards(current, target, maxDelta);
  5911. }
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5916. */
  5917. Scalar.Lerp = function (start, end, amount) {
  5918. return start + ((end - start) * amount);
  5919. };
  5920. /**
  5921. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5922. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5923. */
  5924. Scalar.LerpAngle = function (start, end, amount) {
  5925. var num = Scalar.Repeat(end - start, 360.0);
  5926. if (num > 180.0) {
  5927. num -= 360.0;
  5928. }
  5929. return start + num * Scalar.Clamp(amount);
  5930. };
  5931. /**
  5932. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5933. */
  5934. Scalar.InverseLerp = function (a, b, value) {
  5935. var result = 0;
  5936. if (a != b) {
  5937. result = Scalar.Clamp((value - a) / (b - a));
  5938. }
  5939. else {
  5940. result = 0.0;
  5941. }
  5942. return result;
  5943. };
  5944. /**
  5945. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5946. */
  5947. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5948. var squared = amount * amount;
  5949. var cubed = amount * squared;
  5950. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5951. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5952. var part3 = (cubed - (2.0 * squared)) + amount;
  5953. var part4 = cubed - squared;
  5954. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5955. };
  5956. /**
  5957. * Returns a random float number between and min and max values
  5958. */
  5959. Scalar.RandomRange = function (min, max) {
  5960. if (min === max)
  5961. return min;
  5962. return ((Math.random() * (max - min)) + min);
  5963. };
  5964. /**
  5965. * This function returns percentage of a number in a given range.
  5966. *
  5967. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5968. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5969. */
  5970. Scalar.RangeToPercent = function (number, min, max) {
  5971. return ((number - min) / (max - min));
  5972. };
  5973. /**
  5974. * This function returns number that corresponds to the percentage in a given range.
  5975. *
  5976. * PercentToRange(0.34,0,100) will return 34.
  5977. */
  5978. Scalar.PercentToRange = function (percent, min, max) {
  5979. return ((max - min) * percent + min);
  5980. };
  5981. /**
  5982. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5983. * @param angle The angle to normalize in radian.
  5984. * @return The converted angle.
  5985. */
  5986. Scalar.NormalizeRadians = function (angle) {
  5987. // More precise but slower version kept for reference.
  5988. // angle = angle % Tools.TwoPi;
  5989. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5990. //if (angle > Math.PI) {
  5991. // angle -= Tools.TwoPi;
  5992. //}
  5993. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5994. return angle;
  5995. };
  5996. /**
  5997. * Two pi constants convenient for computation.
  5998. */
  5999. Scalar.TwoPi = Math.PI * 2;
  6000. return Scalar;
  6001. }());
  6002. BABYLON.Scalar = Scalar;
  6003. })(BABYLON || (BABYLON = {}));
  6004. //# sourceMappingURL=babylon.math.scalar.js.map
  6005. //# sourceMappingURL=babylon.mixins.js.map
  6006. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6007. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6008. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6009. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6010. //# sourceMappingURL=babylon.webgl2.js.map
  6011. var BABYLON;
  6012. (function (BABYLON) {
  6013. var __decoratorInitialStore = {};
  6014. var __mergedStore = {};
  6015. var _copySource = function (creationFunction, source, instanciate) {
  6016. var destination = creationFunction();
  6017. // Tags
  6018. if (BABYLON.Tags) {
  6019. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6020. }
  6021. var classStore = getMergedStore(destination);
  6022. // Properties
  6023. for (var property in classStore) {
  6024. var propertyDescriptor = classStore[property];
  6025. var sourceProperty = source[property];
  6026. var propertyType = propertyDescriptor.type;
  6027. if (sourceProperty !== undefined && sourceProperty !== null) {
  6028. switch (propertyType) {
  6029. case 0: // Value
  6030. case 6:// Mesh reference
  6031. destination[property] = sourceProperty;
  6032. break;
  6033. case 1:// Texture
  6034. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6035. break;
  6036. case 2: // Color3
  6037. case 3: // FresnelParameters
  6038. case 4: // Vector2
  6039. case 5: // Vector3
  6040. case 7: // Color Curves
  6041. case 10:// Quaternion
  6042. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6043. break;
  6044. }
  6045. }
  6046. }
  6047. return destination;
  6048. };
  6049. function getDirectStore(target) {
  6050. var classKey = target.getClassName();
  6051. if (!__decoratorInitialStore[classKey]) {
  6052. __decoratorInitialStore[classKey] = {};
  6053. }
  6054. return __decoratorInitialStore[classKey];
  6055. }
  6056. /**
  6057. * Return the list of properties flagged as serializable
  6058. * @param target: host object
  6059. */
  6060. function getMergedStore(target) {
  6061. var classKey = target.getClassName();
  6062. if (__mergedStore[classKey]) {
  6063. return __mergedStore[classKey];
  6064. }
  6065. __mergedStore[classKey] = {};
  6066. var store = __mergedStore[classKey];
  6067. var currentTarget = target;
  6068. var currentKey = classKey;
  6069. while (currentKey) {
  6070. var initialStore = __decoratorInitialStore[currentKey];
  6071. for (var property in initialStore) {
  6072. store[property] = initialStore[property];
  6073. }
  6074. var parent_1 = void 0;
  6075. var done = false;
  6076. do {
  6077. parent_1 = Object.getPrototypeOf(currentTarget);
  6078. if (!parent_1.getClassName) {
  6079. done = true;
  6080. break;
  6081. }
  6082. if (parent_1.getClassName() !== currentKey) {
  6083. break;
  6084. }
  6085. currentTarget = parent_1;
  6086. } while (parent_1);
  6087. if (done) {
  6088. break;
  6089. }
  6090. currentKey = parent_1.getClassName();
  6091. currentTarget = parent_1;
  6092. }
  6093. return store;
  6094. }
  6095. function generateSerializableMember(type, sourceName) {
  6096. return function (target, propertyKey) {
  6097. var classStore = getDirectStore(target);
  6098. if (!classStore[propertyKey]) {
  6099. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6100. }
  6101. };
  6102. }
  6103. function generateExpandMember(setCallback, targetKey) {
  6104. if (targetKey === void 0) { targetKey = null; }
  6105. return function (target, propertyKey) {
  6106. var key = targetKey || ("_" + propertyKey);
  6107. Object.defineProperty(target, propertyKey, {
  6108. get: function () {
  6109. return this[key];
  6110. },
  6111. set: function (value) {
  6112. if (this[key] === value) {
  6113. return;
  6114. }
  6115. this[key] = value;
  6116. target[setCallback].apply(this);
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. };
  6122. }
  6123. function expandToProperty(callback, targetKey) {
  6124. if (targetKey === void 0) { targetKey = null; }
  6125. return generateExpandMember(callback, targetKey);
  6126. }
  6127. BABYLON.expandToProperty = expandToProperty;
  6128. function serialize(sourceName) {
  6129. return generateSerializableMember(0, sourceName); // value member
  6130. }
  6131. BABYLON.serialize = serialize;
  6132. function serializeAsTexture(sourceName) {
  6133. return generateSerializableMember(1, sourceName); // texture member
  6134. }
  6135. BABYLON.serializeAsTexture = serializeAsTexture;
  6136. function serializeAsColor3(sourceName) {
  6137. return generateSerializableMember(2, sourceName); // color3 member
  6138. }
  6139. BABYLON.serializeAsColor3 = serializeAsColor3;
  6140. function serializeAsFresnelParameters(sourceName) {
  6141. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6142. }
  6143. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6144. function serializeAsVector2(sourceName) {
  6145. return generateSerializableMember(4, sourceName); // vector2 member
  6146. }
  6147. BABYLON.serializeAsVector2 = serializeAsVector2;
  6148. function serializeAsVector3(sourceName) {
  6149. return generateSerializableMember(5, sourceName); // vector3 member
  6150. }
  6151. BABYLON.serializeAsVector3 = serializeAsVector3;
  6152. function serializeAsMeshReference(sourceName) {
  6153. return generateSerializableMember(6, sourceName); // mesh reference member
  6154. }
  6155. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6156. function serializeAsColorCurves(sourceName) {
  6157. return generateSerializableMember(7, sourceName); // color curves
  6158. }
  6159. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6160. function serializeAsColor4(sourceName) {
  6161. return generateSerializableMember(8, sourceName); // color 4
  6162. }
  6163. BABYLON.serializeAsColor4 = serializeAsColor4;
  6164. function serializeAsImageProcessingConfiguration(sourceName) {
  6165. return generateSerializableMember(9, sourceName); // image processing
  6166. }
  6167. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6168. function serializeAsQuaternion(sourceName) {
  6169. return generateSerializableMember(10, sourceName); // quaternion member
  6170. }
  6171. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6172. var SerializationHelper = /** @class */ (function () {
  6173. function SerializationHelper() {
  6174. }
  6175. SerializationHelper.Serialize = function (entity, serializationObject) {
  6176. if (!serializationObject) {
  6177. serializationObject = {};
  6178. }
  6179. // Tags
  6180. if (BABYLON.Tags) {
  6181. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6182. }
  6183. var serializedProperties = getMergedStore(entity);
  6184. // Properties
  6185. for (var property in serializedProperties) {
  6186. var propertyDescriptor = serializedProperties[property];
  6187. var targetPropertyName = propertyDescriptor.sourceName || property;
  6188. var propertyType = propertyDescriptor.type;
  6189. var sourceProperty = entity[property];
  6190. if (sourceProperty !== undefined && sourceProperty !== null) {
  6191. switch (propertyType) {
  6192. case 0:// Value
  6193. serializationObject[targetPropertyName] = sourceProperty;
  6194. break;
  6195. case 1:// Texture
  6196. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6197. break;
  6198. case 2:// Color3
  6199. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6200. break;
  6201. case 3:// FresnelParameters
  6202. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6203. break;
  6204. case 4:// Vector2
  6205. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6206. break;
  6207. case 5:// Vector3
  6208. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6209. break;
  6210. case 6:// Mesh reference
  6211. serializationObject[targetPropertyName] = sourceProperty.id;
  6212. break;
  6213. case 7:// Color Curves
  6214. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6215. break;
  6216. case 8:// Color 4
  6217. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6218. break;
  6219. case 9:// Image Processing
  6220. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6221. break;
  6222. }
  6223. }
  6224. }
  6225. return serializationObject;
  6226. };
  6227. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6228. if (rootUrl === void 0) { rootUrl = null; }
  6229. var destination = creationFunction();
  6230. if (!rootUrl) {
  6231. rootUrl = "";
  6232. }
  6233. // Tags
  6234. if (BABYLON.Tags) {
  6235. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6236. }
  6237. var classStore = getMergedStore(destination);
  6238. // Properties
  6239. for (var property in classStore) {
  6240. var propertyDescriptor = classStore[property];
  6241. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6242. var propertyType = propertyDescriptor.type;
  6243. if (sourceProperty !== undefined && sourceProperty !== null) {
  6244. var dest = destination;
  6245. switch (propertyType) {
  6246. case 0:// Value
  6247. dest[property] = sourceProperty;
  6248. break;
  6249. case 1:// Texture
  6250. if (scene) {
  6251. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6252. }
  6253. break;
  6254. case 2:// Color3
  6255. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6256. break;
  6257. case 3:// FresnelParameters
  6258. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6259. break;
  6260. case 4:// Vector2
  6261. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6262. break;
  6263. case 5:// Vector3
  6264. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6265. break;
  6266. case 6:// Mesh reference
  6267. if (scene) {
  6268. dest[property] = scene.getLastMeshByID(sourceProperty);
  6269. }
  6270. break;
  6271. case 7:// Color Curves
  6272. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6273. break;
  6274. case 8:// Color 4
  6275. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6276. break;
  6277. case 9:// Image Processing
  6278. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6279. break;
  6280. }
  6281. }
  6282. }
  6283. return destination;
  6284. };
  6285. SerializationHelper.Clone = function (creationFunction, source) {
  6286. return _copySource(creationFunction, source, false);
  6287. };
  6288. SerializationHelper.Instanciate = function (creationFunction, source) {
  6289. return _copySource(creationFunction, source, true);
  6290. };
  6291. return SerializationHelper;
  6292. }());
  6293. BABYLON.SerializationHelper = SerializationHelper;
  6294. })(BABYLON || (BABYLON = {}));
  6295. //# sourceMappingURL=babylon.decorators.js.map
  6296. var BABYLON;
  6297. (function (BABYLON) {
  6298. /**
  6299. * A class serves as a medium between the observable and its observers
  6300. */
  6301. var EventState = /** @class */ (function () {
  6302. /**
  6303. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6304. */
  6305. function EventState(mask, skipNextObservers, target, currentTarget) {
  6306. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6307. this.initalize(mask, skipNextObservers, target, currentTarget);
  6308. }
  6309. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6310. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6311. this.mask = mask;
  6312. this.skipNextObservers = skipNextObservers;
  6313. this.target = target;
  6314. this.currentTarget = currentTarget;
  6315. return this;
  6316. };
  6317. return EventState;
  6318. }());
  6319. BABYLON.EventState = EventState;
  6320. /**
  6321. * Represent an Observer registered to a given Observable object.
  6322. */
  6323. var Observer = /** @class */ (function () {
  6324. function Observer(callback, mask, scope) {
  6325. if (scope === void 0) { scope = null; }
  6326. this.callback = callback;
  6327. this.mask = mask;
  6328. this.scope = scope;
  6329. }
  6330. return Observer;
  6331. }());
  6332. BABYLON.Observer = Observer;
  6333. /**
  6334. * Represent a list of observers registered to multiple Observables object.
  6335. */
  6336. var MultiObserver = /** @class */ (function () {
  6337. function MultiObserver() {
  6338. }
  6339. MultiObserver.prototype.dispose = function () {
  6340. if (this._observers && this._observables) {
  6341. for (var index = 0; index < this._observers.length; index++) {
  6342. this._observables[index].remove(this._observers[index]);
  6343. }
  6344. }
  6345. this._observers = null;
  6346. this._observables = null;
  6347. };
  6348. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6349. if (mask === void 0) { mask = -1; }
  6350. if (scope === void 0) { scope = null; }
  6351. var result = new MultiObserver();
  6352. result._observers = new Array();
  6353. result._observables = observables;
  6354. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6355. var observable = observables_1[_i];
  6356. var observer = observable.add(callback, mask, false, scope);
  6357. if (observer) {
  6358. result._observers.push(observer);
  6359. }
  6360. }
  6361. return result;
  6362. };
  6363. return MultiObserver;
  6364. }());
  6365. BABYLON.MultiObserver = MultiObserver;
  6366. /**
  6367. * The Observable class is a simple implementation of the Observable pattern.
  6368. * 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.
  6369. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6370. * 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).
  6371. * 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.
  6372. */
  6373. var Observable = /** @class */ (function () {
  6374. function Observable(onObserverAdded) {
  6375. this._observers = new Array();
  6376. this._eventState = new EventState(0);
  6377. if (onObserverAdded) {
  6378. this._onObserverAdded = onObserverAdded;
  6379. }
  6380. }
  6381. /**
  6382. * Create a new Observer with the specified callback
  6383. * @param callback the callback that will be executed for that Observer
  6384. * @param mask the mask used to filter observers
  6385. * @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.
  6386. * @param scope optional scope for the callback to be called from
  6387. */
  6388. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6389. if (mask === void 0) { mask = -1; }
  6390. if (insertFirst === void 0) { insertFirst = false; }
  6391. if (scope === void 0) { scope = null; }
  6392. if (!callback) {
  6393. return null;
  6394. }
  6395. var observer = new Observer(callback, mask, scope);
  6396. if (insertFirst) {
  6397. this._observers.unshift(observer);
  6398. }
  6399. else {
  6400. this._observers.push(observer);
  6401. }
  6402. if (this._onObserverAdded) {
  6403. this._onObserverAdded(observer);
  6404. }
  6405. return observer;
  6406. };
  6407. /**
  6408. * Remove an Observer from the Observable object
  6409. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6410. */
  6411. Observable.prototype.remove = function (observer) {
  6412. if (!observer) {
  6413. return false;
  6414. }
  6415. var index = this._observers.indexOf(observer);
  6416. if (index !== -1) {
  6417. this._observers.splice(index, 1);
  6418. return true;
  6419. }
  6420. return false;
  6421. };
  6422. /**
  6423. * Remove a callback from the Observable object
  6424. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6425. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6426. */
  6427. Observable.prototype.removeCallback = function (callback, scope) {
  6428. for (var index = 0; index < this._observers.length; index++) {
  6429. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6430. this._observers.splice(index, 1);
  6431. return true;
  6432. }
  6433. }
  6434. return false;
  6435. };
  6436. /**
  6437. * Notify all Observers by calling their respective callback with the given data
  6438. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6439. * @param eventData
  6440. * @param mask
  6441. */
  6442. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6443. if (mask === void 0) { mask = -1; }
  6444. if (!this._observers.length) {
  6445. return true;
  6446. }
  6447. var state = this._eventState;
  6448. state.mask = mask;
  6449. state.target = target;
  6450. state.currentTarget = currentTarget;
  6451. state.skipNextObservers = false;
  6452. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6453. var obs = _a[_i];
  6454. if (obs.mask & mask) {
  6455. if (obs.scope) {
  6456. obs.callback.apply(obs.scope, [eventData, state]);
  6457. }
  6458. else {
  6459. obs.callback(eventData, state);
  6460. }
  6461. }
  6462. if (state.skipNextObservers) {
  6463. return false;
  6464. }
  6465. }
  6466. return true;
  6467. };
  6468. /**
  6469. * Notify a specific observer
  6470. * @param eventData
  6471. * @param mask
  6472. */
  6473. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6474. if (mask === void 0) { mask = -1; }
  6475. var state = this._eventState;
  6476. state.mask = mask;
  6477. state.skipNextObservers = false;
  6478. observer.callback(eventData, state);
  6479. };
  6480. /**
  6481. * return true is the Observable has at least one Observer registered
  6482. */
  6483. Observable.prototype.hasObservers = function () {
  6484. return this._observers.length > 0;
  6485. };
  6486. /**
  6487. * Clear the list of observers
  6488. */
  6489. Observable.prototype.clear = function () {
  6490. this._observers = new Array();
  6491. this._onObserverAdded = null;
  6492. };
  6493. /**
  6494. * Clone the current observable
  6495. */
  6496. Observable.prototype.clone = function () {
  6497. var result = new Observable();
  6498. result._observers = this._observers.slice(0);
  6499. return result;
  6500. };
  6501. /**
  6502. * Does this observable handles observer registered with a given mask
  6503. * @param {number} trigger - the mask to be tested
  6504. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6505. **/
  6506. Observable.prototype.hasSpecificMask = function (mask) {
  6507. if (mask === void 0) { mask = -1; }
  6508. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6509. var obs = _a[_i];
  6510. if (obs.mask & mask || obs.mask === mask) {
  6511. return true;
  6512. }
  6513. }
  6514. return false;
  6515. };
  6516. return Observable;
  6517. }());
  6518. BABYLON.Observable = Observable;
  6519. })(BABYLON || (BABYLON = {}));
  6520. //# sourceMappingURL=babylon.observable.js.map
  6521. var BABYLON;
  6522. (function (BABYLON) {
  6523. var SmartArray = /** @class */ (function () {
  6524. function SmartArray(capacity) {
  6525. this.length = 0;
  6526. this.data = new Array(capacity);
  6527. this._id = SmartArray._GlobalId++;
  6528. }
  6529. SmartArray.prototype.push = function (value) {
  6530. this.data[this.length++] = value;
  6531. if (this.length > this.data.length) {
  6532. this.data.length *= 2;
  6533. }
  6534. };
  6535. SmartArray.prototype.forEach = function (func) {
  6536. for (var index = 0; index < this.length; index++) {
  6537. func(this.data[index]);
  6538. }
  6539. };
  6540. SmartArray.prototype.sort = function (compareFn) {
  6541. this.data.sort(compareFn);
  6542. };
  6543. SmartArray.prototype.reset = function () {
  6544. this.length = 0;
  6545. };
  6546. SmartArray.prototype.dispose = function () {
  6547. this.reset();
  6548. if (this.data) {
  6549. this.data.length = 0;
  6550. this.data = [];
  6551. }
  6552. };
  6553. SmartArray.prototype.concat = function (array) {
  6554. if (array.length === 0) {
  6555. return;
  6556. }
  6557. if (this.length + array.length > this.data.length) {
  6558. this.data.length = (this.length + array.length) * 2;
  6559. }
  6560. for (var index = 0; index < array.length; index++) {
  6561. this.data[this.length++] = (array.data || array)[index];
  6562. }
  6563. };
  6564. SmartArray.prototype.indexOf = function (value) {
  6565. var position = this.data.indexOf(value);
  6566. if (position >= this.length) {
  6567. return -1;
  6568. }
  6569. return position;
  6570. };
  6571. SmartArray.prototype.contains = function (value) {
  6572. return this.data.indexOf(value) !== -1;
  6573. };
  6574. // Statics
  6575. SmartArray._GlobalId = 0;
  6576. return SmartArray;
  6577. }());
  6578. BABYLON.SmartArray = SmartArray;
  6579. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6580. __extends(SmartArrayNoDuplicate, _super);
  6581. function SmartArrayNoDuplicate() {
  6582. var _this = _super !== null && _super.apply(this, arguments) || this;
  6583. _this._duplicateId = 0;
  6584. return _this;
  6585. }
  6586. SmartArrayNoDuplicate.prototype.push = function (value) {
  6587. _super.prototype.push.call(this, value);
  6588. if (!value.__smartArrayFlags) {
  6589. value.__smartArrayFlags = {};
  6590. }
  6591. value.__smartArrayFlags[this._id] = this._duplicateId;
  6592. };
  6593. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6594. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6595. return false;
  6596. }
  6597. this.push(value);
  6598. return true;
  6599. };
  6600. SmartArrayNoDuplicate.prototype.reset = function () {
  6601. _super.prototype.reset.call(this);
  6602. this._duplicateId++;
  6603. };
  6604. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6605. if (array.length === 0) {
  6606. return;
  6607. }
  6608. if (this.length + array.length > this.data.length) {
  6609. this.data.length = (this.length + array.length) * 2;
  6610. }
  6611. for (var index = 0; index < array.length; index++) {
  6612. var item = (array.data || array)[index];
  6613. this.pushNoDuplicate(item);
  6614. }
  6615. };
  6616. return SmartArrayNoDuplicate;
  6617. }(SmartArray));
  6618. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6619. })(BABYLON || (BABYLON = {}));
  6620. //# sourceMappingURL=babylon.smartArray.js.map
  6621. var BABYLON;
  6622. (function (BABYLON) {
  6623. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6624. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6625. var LoadFileError = /** @class */ (function (_super) {
  6626. __extends(LoadFileError, _super);
  6627. function LoadFileError(message, request) {
  6628. var _this = _super.call(this, message) || this;
  6629. _this.request = request;
  6630. _this.name = "LoadFileError";
  6631. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6632. return _this;
  6633. }
  6634. // Polyfill for Object.setPrototypeOf if necessary.
  6635. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6636. return LoadFileError;
  6637. }(Error));
  6638. BABYLON.LoadFileError = LoadFileError;
  6639. var RetryStrategy = /** @class */ (function () {
  6640. function RetryStrategy() {
  6641. }
  6642. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6643. if (maxRetries === void 0) { maxRetries = 3; }
  6644. if (baseInterval === void 0) { baseInterval = 500; }
  6645. return function (url, request, retryIndex) {
  6646. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6647. return -1;
  6648. }
  6649. return Math.pow(2, retryIndex) * baseInterval;
  6650. };
  6651. };
  6652. return RetryStrategy;
  6653. }());
  6654. BABYLON.RetryStrategy = RetryStrategy;
  6655. // Screenshots
  6656. var screenshotCanvas;
  6657. var cloneValue = function (source, destinationObject) {
  6658. if (!source)
  6659. return null;
  6660. if (source instanceof BABYLON.Mesh) {
  6661. return null;
  6662. }
  6663. if (source instanceof BABYLON.SubMesh) {
  6664. return source.clone(destinationObject);
  6665. }
  6666. else if (source.clone) {
  6667. return source.clone();
  6668. }
  6669. return null;
  6670. };
  6671. var Tools = /** @class */ (function () {
  6672. function Tools() {
  6673. }
  6674. /**
  6675. * Interpolates between a and b via alpha
  6676. * @param a The lower value (returned when alpha = 0)
  6677. * @param b The upper value (returned when alpha = 1)
  6678. * @param alpha The interpolation-factor
  6679. * @return The mixed value
  6680. */
  6681. Tools.Mix = function (a, b, alpha) {
  6682. return a * (1 - alpha) + b * alpha;
  6683. };
  6684. Tools.Instantiate = function (className) {
  6685. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6686. return Tools.RegisteredExternalClasses[className];
  6687. }
  6688. var arr = className.split(".");
  6689. var fn = (window || this);
  6690. for (var i = 0, len = arr.length; i < len; i++) {
  6691. fn = fn[arr[i]];
  6692. }
  6693. if (typeof fn !== "function") {
  6694. return null;
  6695. }
  6696. return fn;
  6697. };
  6698. Tools.SetImmediate = function (action) {
  6699. if (window.setImmediate) {
  6700. window.setImmediate(action);
  6701. }
  6702. else {
  6703. setTimeout(action, 1);
  6704. }
  6705. };
  6706. Tools.IsExponentOfTwo = function (value) {
  6707. var count = 1;
  6708. do {
  6709. count *= 2;
  6710. } while (count < value);
  6711. return count === value;
  6712. };
  6713. /**
  6714. * Find the next highest power of two.
  6715. * @param x Number to start search from.
  6716. * @return Next highest power of two.
  6717. */
  6718. Tools.CeilingPOT = function (x) {
  6719. x--;
  6720. x |= x >> 1;
  6721. x |= x >> 2;
  6722. x |= x >> 4;
  6723. x |= x >> 8;
  6724. x |= x >> 16;
  6725. x++;
  6726. return x;
  6727. };
  6728. /**
  6729. * Find the next lowest power of two.
  6730. * @param x Number to start search from.
  6731. * @return Next lowest power of two.
  6732. */
  6733. Tools.FloorPOT = function (x) {
  6734. x = x | (x >> 1);
  6735. x = x | (x >> 2);
  6736. x = x | (x >> 4);
  6737. x = x | (x >> 8);
  6738. x = x | (x >> 16);
  6739. return x - (x >> 1);
  6740. };
  6741. /**
  6742. * Find the nearest power of two.
  6743. * @param x Number to start search from.
  6744. * @return Next nearest power of two.
  6745. */
  6746. Tools.NearestPOT = function (x) {
  6747. var c = Tools.CeilingPOT(x);
  6748. var f = Tools.FloorPOT(x);
  6749. return (c - x) > (x - f) ? f : c;
  6750. };
  6751. Tools.GetExponentOfTwo = function (value, max, mode) {
  6752. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6753. var pot;
  6754. switch (mode) {
  6755. case BABYLON.Engine.SCALEMODE_FLOOR:
  6756. pot = Tools.FloorPOT(value);
  6757. break;
  6758. case BABYLON.Engine.SCALEMODE_NEAREST:
  6759. pot = Tools.NearestPOT(value);
  6760. break;
  6761. case BABYLON.Engine.SCALEMODE_CEILING:
  6762. default:
  6763. pot = Tools.CeilingPOT(value);
  6764. break;
  6765. }
  6766. return Math.min(pot, max);
  6767. };
  6768. Tools.GetFilename = function (path) {
  6769. var index = path.lastIndexOf("/");
  6770. if (index < 0)
  6771. return path;
  6772. return path.substring(index + 1);
  6773. };
  6774. Tools.GetFolderPath = function (uri) {
  6775. var index = uri.lastIndexOf("/");
  6776. if (index < 0)
  6777. return "";
  6778. return uri.substring(0, index + 1);
  6779. };
  6780. Tools.GetDOMTextContent = function (element) {
  6781. var result = "";
  6782. var child = element.firstChild;
  6783. while (child) {
  6784. if (child.nodeType === 3) {
  6785. result += child.textContent;
  6786. }
  6787. child = child.nextSibling;
  6788. }
  6789. return result;
  6790. };
  6791. Tools.ToDegrees = function (angle) {
  6792. return angle * 180 / Math.PI;
  6793. };
  6794. Tools.ToRadians = function (angle) {
  6795. return angle * Math.PI / 180;
  6796. };
  6797. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6798. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6799. var output = "";
  6800. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6801. var i = 0;
  6802. var bytes = new Uint8Array(buffer);
  6803. while (i < bytes.length) {
  6804. chr1 = bytes[i++];
  6805. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6806. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6807. enc1 = chr1 >> 2;
  6808. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6809. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6810. enc4 = chr3 & 63;
  6811. if (isNaN(chr2)) {
  6812. enc3 = enc4 = 64;
  6813. }
  6814. else if (isNaN(chr3)) {
  6815. enc4 = 64;
  6816. }
  6817. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6818. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6819. }
  6820. return "data:image/png;base64," + output;
  6821. };
  6822. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6823. if (bias === void 0) { bias = null; }
  6824. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6825. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6826. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6827. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6828. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6829. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6830. }
  6831. if (bias) {
  6832. minimum.x -= minimum.x * bias.x + bias.y;
  6833. minimum.y -= minimum.y * bias.x + bias.y;
  6834. minimum.z -= minimum.z * bias.x + bias.y;
  6835. maximum.x += maximum.x * bias.x + bias.y;
  6836. maximum.y += maximum.y * bias.x + bias.y;
  6837. maximum.z += maximum.z * bias.x + bias.y;
  6838. }
  6839. return {
  6840. minimum: minimum,
  6841. maximum: maximum
  6842. };
  6843. };
  6844. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6845. if (bias === void 0) { bias = null; }
  6846. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6847. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6848. if (!stride) {
  6849. stride = 3;
  6850. }
  6851. for (var index = start; index < start + count; index++) {
  6852. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6853. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6854. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6855. }
  6856. if (bias) {
  6857. minimum.x -= minimum.x * bias.x + bias.y;
  6858. minimum.y -= minimum.y * bias.x + bias.y;
  6859. minimum.z -= minimum.z * bias.x + bias.y;
  6860. maximum.x += maximum.x * bias.x + bias.y;
  6861. maximum.y += maximum.y * bias.x + bias.y;
  6862. maximum.z += maximum.z * bias.x + bias.y;
  6863. }
  6864. return {
  6865. minimum: minimum,
  6866. maximum: maximum
  6867. };
  6868. };
  6869. Tools.Vector2ArrayFeeder = function (array) {
  6870. return function (index) {
  6871. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6872. var length = isFloatArray ? array.length / 2 : array.length;
  6873. if (index >= length) {
  6874. return null;
  6875. }
  6876. if (isFloatArray) {
  6877. var fa = array;
  6878. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6879. }
  6880. var a = array;
  6881. return a[index];
  6882. };
  6883. };
  6884. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6885. if (bias === void 0) { bias = null; }
  6886. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6887. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6888. var i = 0;
  6889. var cur = feeder(i++);
  6890. while (cur) {
  6891. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6892. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6893. cur = feeder(i++);
  6894. }
  6895. if (bias) {
  6896. minimum.x -= minimum.x * bias.x + bias.y;
  6897. minimum.y -= minimum.y * bias.x + bias.y;
  6898. maximum.x += maximum.x * bias.x + bias.y;
  6899. maximum.y += maximum.y * bias.x + bias.y;
  6900. }
  6901. return {
  6902. minimum: minimum,
  6903. maximum: maximum
  6904. };
  6905. };
  6906. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6907. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6908. return null;
  6909. return Array.isArray(obj) ? obj : [obj];
  6910. };
  6911. // Misc.
  6912. Tools.GetPointerPrefix = function () {
  6913. var eventPrefix = "pointer";
  6914. // Check if pointer events are supported
  6915. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6916. eventPrefix = "mouse";
  6917. }
  6918. return eventPrefix;
  6919. };
  6920. /**
  6921. * @param func - the function to be called
  6922. * @param requester - the object that will request the next frame. Falls back to window.
  6923. */
  6924. Tools.QueueNewFrame = function (func, requester) {
  6925. if (!Tools.IsWindowObjectExist()) {
  6926. return setTimeout(func, 16);
  6927. }
  6928. if (!requester) {
  6929. requester = window;
  6930. }
  6931. if (requester.requestAnimationFrame) {
  6932. return requester.requestAnimationFrame(func);
  6933. }
  6934. else if (requester.msRequestAnimationFrame) {
  6935. return requester.msRequestAnimationFrame(func);
  6936. }
  6937. else if (requester.webkitRequestAnimationFrame) {
  6938. return requester.webkitRequestAnimationFrame(func);
  6939. }
  6940. else if (requester.mozRequestAnimationFrame) {
  6941. return requester.mozRequestAnimationFrame(func);
  6942. }
  6943. else if (requester.oRequestAnimationFrame) {
  6944. return requester.oRequestAnimationFrame(func);
  6945. }
  6946. else {
  6947. return window.setTimeout(func, 16);
  6948. }
  6949. };
  6950. Tools.RequestFullscreen = function (element) {
  6951. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6952. if (!requestFunction)
  6953. return;
  6954. requestFunction.call(element);
  6955. };
  6956. Tools.ExitFullscreen = function () {
  6957. if (document.exitFullscreen) {
  6958. document.exitFullscreen();
  6959. }
  6960. else if (document.mozCancelFullScreen) {
  6961. document.mozCancelFullScreen();
  6962. }
  6963. else if (document.webkitCancelFullScreen) {
  6964. document.webkitCancelFullScreen();
  6965. }
  6966. else if (document.msCancelFullScreen) {
  6967. document.msCancelFullScreen();
  6968. }
  6969. };
  6970. Tools.SetCorsBehavior = function (url, element) {
  6971. if (url && url.indexOf("data:") === 0) {
  6972. return;
  6973. }
  6974. if (Tools.CorsBehavior) {
  6975. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6976. element.crossOrigin = Tools.CorsBehavior;
  6977. }
  6978. else {
  6979. var result = Tools.CorsBehavior(url);
  6980. if (result) {
  6981. element.crossOrigin = result;
  6982. }
  6983. }
  6984. }
  6985. };
  6986. // External files
  6987. Tools.CleanUrl = function (url) {
  6988. url = url.replace(/#/mg, "%23");
  6989. return url;
  6990. };
  6991. Tools.LoadImage = function (url, onLoad, onError, database) {
  6992. if (url instanceof ArrayBuffer) {
  6993. url = Tools.EncodeArrayBufferTobase64(url);
  6994. }
  6995. url = Tools.CleanUrl(url);
  6996. url = Tools.PreprocessUrl(url);
  6997. var img = new Image();
  6998. Tools.SetCorsBehavior(url, img);
  6999. img.onload = function () {
  7000. onLoad(img);
  7001. };
  7002. img.onerror = function (err) {
  7003. Tools.Error("Error while trying to load image: " + url);
  7004. if (onError) {
  7005. onError("Error while trying to load image: " + url, err);
  7006. }
  7007. };
  7008. var noIndexedDB = function () {
  7009. img.src = url;
  7010. };
  7011. var loadFromIndexedDB = function () {
  7012. if (database) {
  7013. database.loadImageFromDB(url, img);
  7014. }
  7015. };
  7016. //ANY database to do!
  7017. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7018. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7019. }
  7020. else {
  7021. if (url.indexOf("file:") !== -1) {
  7022. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7023. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7024. try {
  7025. var blobURL;
  7026. try {
  7027. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7028. }
  7029. catch (ex) {
  7030. // Chrome doesn't support oneTimeOnly parameter
  7031. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7032. }
  7033. img.src = blobURL;
  7034. }
  7035. catch (e) {
  7036. img.src = "";
  7037. }
  7038. return img;
  7039. }
  7040. }
  7041. noIndexedDB();
  7042. }
  7043. return img;
  7044. };
  7045. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7046. url = Tools.CleanUrl(url);
  7047. url = Tools.PreprocessUrl(url);
  7048. // If file and file input are set
  7049. if (url.indexOf("file:") !== -1) {
  7050. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7051. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7052. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7053. }
  7054. }
  7055. var loadUrl = Tools.BaseUrl + url;
  7056. var aborted = false;
  7057. var fileRequest = {
  7058. onCompleteObservable: new BABYLON.Observable(),
  7059. abort: function () { return aborted = true; },
  7060. };
  7061. var requestFile = function () {
  7062. var request = new XMLHttpRequest();
  7063. var retryHandle = null;
  7064. fileRequest.abort = function () {
  7065. aborted = true;
  7066. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7067. request.abort();
  7068. }
  7069. if (retryHandle !== null) {
  7070. clearTimeout(retryHandle);
  7071. retryHandle = null;
  7072. }
  7073. };
  7074. var retryLoop = function (retryIndex) {
  7075. request.open('GET', loadUrl, true);
  7076. if (useArrayBuffer) {
  7077. request.responseType = "arraybuffer";
  7078. }
  7079. if (onProgress) {
  7080. request.addEventListener("progress", onProgress);
  7081. }
  7082. var onLoadEnd = function () {
  7083. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7084. };
  7085. request.addEventListener("loadend", onLoadEnd);
  7086. var onReadyStateChange = function () {
  7087. if (aborted) {
  7088. return;
  7089. }
  7090. // In case of undefined state in some browsers.
  7091. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7092. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7093. request.removeEventListener("readystatechange", onReadyStateChange);
  7094. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7095. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7096. return;
  7097. }
  7098. var retryStrategy = Tools.DefaultRetryStrategy;
  7099. if (retryStrategy) {
  7100. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7101. if (waitTime !== -1) {
  7102. // Prevent the request from completing for retry.
  7103. request.removeEventListener("loadend", onLoadEnd);
  7104. request = new XMLHttpRequest();
  7105. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7106. return;
  7107. }
  7108. }
  7109. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7110. if (onError) {
  7111. onError(request, e);
  7112. }
  7113. else {
  7114. throw e;
  7115. }
  7116. }
  7117. };
  7118. request.addEventListener("readystatechange", onReadyStateChange);
  7119. request.send();
  7120. };
  7121. retryLoop(0);
  7122. };
  7123. // Caching all files
  7124. if (database && database.enableSceneOffline) {
  7125. var noIndexedDB_1 = function () {
  7126. if (!aborted) {
  7127. requestFile();
  7128. }
  7129. };
  7130. var loadFromIndexedDB = function () {
  7131. // TODO: database needs to support aborting and should return a IFileRequest
  7132. if (aborted) {
  7133. return;
  7134. }
  7135. if (database) {
  7136. database.loadFileFromDB(url, function (data) {
  7137. if (!aborted) {
  7138. onSuccess(data);
  7139. }
  7140. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7141. }, onProgress ? function (event) {
  7142. if (!aborted) {
  7143. onProgress(event);
  7144. }
  7145. } : undefined, noIndexedDB_1, useArrayBuffer);
  7146. }
  7147. };
  7148. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7149. }
  7150. else {
  7151. requestFile();
  7152. }
  7153. return fileRequest;
  7154. };
  7155. /**
  7156. * Load a script (identified by an url). When the url returns, the
  7157. * content of this file is added into a new script element, attached to the DOM (body element)
  7158. */
  7159. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7160. var head = document.getElementsByTagName('head')[0];
  7161. var script = document.createElement('script');
  7162. script.type = 'text/javascript';
  7163. script.src = scriptUrl;
  7164. script.onload = function () {
  7165. if (onSuccess) {
  7166. onSuccess();
  7167. }
  7168. };
  7169. script.onerror = function (e) {
  7170. if (onError) {
  7171. onError("Unable to load script", e);
  7172. }
  7173. };
  7174. head.appendChild(script);
  7175. };
  7176. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7177. var reader = new FileReader();
  7178. var request = {
  7179. onCompleteObservable: new BABYLON.Observable(),
  7180. abort: function () { return reader.abort(); },
  7181. };
  7182. reader.onloadend = function (e) {
  7183. request.onCompleteObservable.notifyObservers(request);
  7184. };
  7185. reader.onload = function (e) {
  7186. //target doesn't have result from ts 1.3
  7187. callback(e.target['result']);
  7188. };
  7189. reader.onprogress = progressCallback;
  7190. reader.readAsDataURL(fileToLoad);
  7191. return request;
  7192. };
  7193. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7194. var reader = new FileReader();
  7195. var request = {
  7196. onCompleteObservable: new BABYLON.Observable(),
  7197. abort: function () { return reader.abort(); },
  7198. };
  7199. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7200. reader.onerror = function (e) {
  7201. Tools.Log("Error while reading file: " + fileToLoad.name);
  7202. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7203. };
  7204. reader.onload = function (e) {
  7205. //target doesn't have result from ts 1.3
  7206. callback(e.target['result']);
  7207. };
  7208. if (progressCallBack) {
  7209. reader.onprogress = progressCallBack;
  7210. }
  7211. if (!useArrayBuffer) {
  7212. // Asynchronous read
  7213. reader.readAsText(fileToLoad);
  7214. }
  7215. else {
  7216. reader.readAsArrayBuffer(fileToLoad);
  7217. }
  7218. return request;
  7219. };
  7220. //returns a downloadable url to a file content.
  7221. Tools.FileAsURL = function (content) {
  7222. var fileBlob = new Blob([content]);
  7223. var url = window.URL || window.webkitURL;
  7224. var link = url.createObjectURL(fileBlob);
  7225. return link;
  7226. };
  7227. // Misc.
  7228. Tools.Format = function (value, decimals) {
  7229. if (decimals === void 0) { decimals = 2; }
  7230. return value.toFixed(decimals);
  7231. };
  7232. Tools.CheckExtends = function (v, min, max) {
  7233. if (v.x < min.x)
  7234. min.x = v.x;
  7235. if (v.y < min.y)
  7236. min.y = v.y;
  7237. if (v.z < min.z)
  7238. min.z = v.z;
  7239. if (v.x > max.x)
  7240. max.x = v.x;
  7241. if (v.y > max.y)
  7242. max.y = v.y;
  7243. if (v.z > max.z)
  7244. max.z = v.z;
  7245. };
  7246. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7247. for (var prop in source) {
  7248. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7249. continue;
  7250. }
  7251. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7252. continue;
  7253. }
  7254. var sourceValue = source[prop];
  7255. var typeOfSourceValue = typeof sourceValue;
  7256. if (typeOfSourceValue === "function") {
  7257. continue;
  7258. }
  7259. if (typeOfSourceValue === "object") {
  7260. if (sourceValue instanceof Array) {
  7261. destination[prop] = [];
  7262. if (sourceValue.length > 0) {
  7263. if (typeof sourceValue[0] == "object") {
  7264. for (var index = 0; index < sourceValue.length; index++) {
  7265. var clonedValue = cloneValue(sourceValue[index], destination);
  7266. if (destination[prop].indexOf(clonedValue) === -1) {
  7267. destination[prop].push(clonedValue);
  7268. }
  7269. }
  7270. }
  7271. else {
  7272. destination[prop] = sourceValue.slice(0);
  7273. }
  7274. }
  7275. }
  7276. else {
  7277. destination[prop] = cloneValue(sourceValue, destination);
  7278. }
  7279. }
  7280. else {
  7281. destination[prop] = sourceValue;
  7282. }
  7283. }
  7284. };
  7285. Tools.IsEmpty = function (obj) {
  7286. for (var i in obj) {
  7287. if (obj.hasOwnProperty(i)) {
  7288. return false;
  7289. }
  7290. }
  7291. return true;
  7292. };
  7293. Tools.RegisterTopRootEvents = function (events) {
  7294. for (var index = 0; index < events.length; index++) {
  7295. var event = events[index];
  7296. window.addEventListener(event.name, event.handler, false);
  7297. try {
  7298. if (window.parent) {
  7299. window.parent.addEventListener(event.name, event.handler, false);
  7300. }
  7301. }
  7302. catch (e) {
  7303. // Silently fails...
  7304. }
  7305. }
  7306. };
  7307. Tools.UnregisterTopRootEvents = function (events) {
  7308. for (var index = 0; index < events.length; index++) {
  7309. var event = events[index];
  7310. window.removeEventListener(event.name, event.handler);
  7311. try {
  7312. if (window.parent) {
  7313. window.parent.removeEventListener(event.name, event.handler);
  7314. }
  7315. }
  7316. catch (e) {
  7317. // Silently fails...
  7318. }
  7319. }
  7320. };
  7321. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7322. if (mimeType === void 0) { mimeType = "image/png"; }
  7323. // Read the contents of the framebuffer
  7324. var numberOfChannelsByLine = width * 4;
  7325. var halfHeight = height / 2;
  7326. //Reading datas from WebGL
  7327. var data = engine.readPixels(0, 0, width, height);
  7328. //To flip image on Y axis.
  7329. for (var i = 0; i < halfHeight; i++) {
  7330. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7331. var currentCell = j + i * numberOfChannelsByLine;
  7332. var targetLine = height - i - 1;
  7333. var targetCell = j + targetLine * numberOfChannelsByLine;
  7334. var temp = data[currentCell];
  7335. data[currentCell] = data[targetCell];
  7336. data[targetCell] = temp;
  7337. }
  7338. }
  7339. // Create a 2D canvas to store the result
  7340. if (!screenshotCanvas) {
  7341. screenshotCanvas = document.createElement('canvas');
  7342. }
  7343. screenshotCanvas.width = width;
  7344. screenshotCanvas.height = height;
  7345. var context = screenshotCanvas.getContext('2d');
  7346. if (context) {
  7347. // Copy the pixels to a 2D canvas
  7348. var imageData = context.createImageData(width, height);
  7349. var castData = (imageData.data);
  7350. castData.set(data);
  7351. context.putImageData(imageData, 0, 0);
  7352. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7353. }
  7354. };
  7355. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7356. if (mimeType === void 0) { mimeType = "image/png"; }
  7357. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7358. if (successCallback) {
  7359. successCallback(base64Image);
  7360. }
  7361. else {
  7362. // We need HTMLCanvasElement.toBlob for HD screenshots
  7363. if (!screenshotCanvas.toBlob) {
  7364. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7365. screenshotCanvas.toBlob = function (callback, type, quality) {
  7366. var _this = this;
  7367. setTimeout(function () {
  7368. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7369. for (var i = 0; i < len; i++) {
  7370. arr[i] = binStr.charCodeAt(i);
  7371. }
  7372. callback(new Blob([arr], { type: type || 'image/png' }));
  7373. });
  7374. };
  7375. }
  7376. screenshotCanvas.toBlob(function (blob) {
  7377. var url = URL.createObjectURL(blob);
  7378. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7379. if (("download" in document.createElement("a"))) {
  7380. var a = window.document.createElement("a");
  7381. a.href = url;
  7382. if (fileName) {
  7383. a.setAttribute("download", fileName);
  7384. }
  7385. else {
  7386. var date = new Date();
  7387. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7388. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7389. }
  7390. window.document.body.appendChild(a);
  7391. a.addEventListener("click", function () {
  7392. if (a.parentElement) {
  7393. a.parentElement.removeChild(a);
  7394. }
  7395. });
  7396. a.click();
  7397. }
  7398. else {
  7399. var newWindow = window.open("");
  7400. if (!newWindow)
  7401. return;
  7402. var img = newWindow.document.createElement("img");
  7403. img.onload = function () {
  7404. // no longer need to read the blob so it's revoked
  7405. URL.revokeObjectURL(url);
  7406. };
  7407. img.src = url;
  7408. newWindow.document.body.appendChild(img);
  7409. }
  7410. });
  7411. }
  7412. };
  7413. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7414. if (mimeType === void 0) { mimeType = "image/png"; }
  7415. var width;
  7416. var height;
  7417. // If a precision value is specified
  7418. if (size.precision) {
  7419. width = Math.round(engine.getRenderWidth() * size.precision);
  7420. height = Math.round(width / engine.getAspectRatio(camera));
  7421. }
  7422. else if (size.width && size.height) {
  7423. width = size.width;
  7424. height = size.height;
  7425. }
  7426. else if (size.width && !size.height) {
  7427. width = size.width;
  7428. height = Math.round(width / engine.getAspectRatio(camera));
  7429. }
  7430. else if (size.height && !size.width) {
  7431. height = size.height;
  7432. width = Math.round(height * engine.getAspectRatio(camera));
  7433. }
  7434. else if (!isNaN(size)) {
  7435. height = size;
  7436. width = size;
  7437. }
  7438. else {
  7439. Tools.Error("Invalid 'size' parameter !");
  7440. return;
  7441. }
  7442. if (!screenshotCanvas) {
  7443. screenshotCanvas = document.createElement('canvas');
  7444. }
  7445. screenshotCanvas.width = width;
  7446. screenshotCanvas.height = height;
  7447. var renderContext = screenshotCanvas.getContext("2d");
  7448. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7449. var newWidth = width;
  7450. var newHeight = newWidth / ratio;
  7451. if (newHeight > height) {
  7452. newHeight = height;
  7453. newWidth = newHeight * ratio;
  7454. }
  7455. var offsetX = Math.max(0, width - newWidth) / 2;
  7456. var offsetY = Math.max(0, height - newHeight) / 2;
  7457. var renderingCanvas = engine.getRenderingCanvas();
  7458. if (renderContext && renderingCanvas) {
  7459. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7460. }
  7461. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7462. };
  7463. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7464. if (mimeType === void 0) { mimeType = "image/png"; }
  7465. if (samples === void 0) { samples = 1; }
  7466. if (antialiasing === void 0) { antialiasing = false; }
  7467. var width;
  7468. var height;
  7469. //If a precision value is specified
  7470. if (size.precision) {
  7471. width = Math.round(engine.getRenderWidth() * size.precision);
  7472. height = Math.round(width / engine.getAspectRatio(camera));
  7473. size = { width: width, height: height };
  7474. }
  7475. else if (size.width && size.height) {
  7476. width = size.width;
  7477. height = size.height;
  7478. }
  7479. else if (size.width && !size.height) {
  7480. width = size.width;
  7481. height = Math.round(width / engine.getAspectRatio(camera));
  7482. size = { width: width, height: height };
  7483. }
  7484. else if (size.height && !size.width) {
  7485. height = size.height;
  7486. width = Math.round(height * engine.getAspectRatio(camera));
  7487. size = { width: width, height: height };
  7488. }
  7489. else if (!isNaN(size)) {
  7490. height = size;
  7491. width = size;
  7492. }
  7493. else {
  7494. Tools.Error("Invalid 'size' parameter !");
  7495. return;
  7496. }
  7497. var scene = camera.getScene();
  7498. var previousCamera = null;
  7499. if (scene.activeCamera !== camera) {
  7500. previousCamera = scene.activeCamera;
  7501. scene.activeCamera = camera;
  7502. }
  7503. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7504. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7505. texture.renderList = null;
  7506. texture.samples = samples;
  7507. if (antialiasing) {
  7508. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7509. }
  7510. texture.onAfterRenderObservable.add(function () {
  7511. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7512. });
  7513. scene.incrementRenderId();
  7514. scene.resetCachedMaterial();
  7515. texture.render(true);
  7516. texture.dispose();
  7517. if (previousCamera) {
  7518. scene.activeCamera = previousCamera;
  7519. }
  7520. camera.getProjectionMatrix(true); // Force cache refresh;
  7521. };
  7522. // XHR response validator for local file scenario
  7523. Tools.ValidateXHRData = function (xhr, dataType) {
  7524. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7525. if (dataType === void 0) { dataType = 7; }
  7526. try {
  7527. if (dataType & 1) {
  7528. if (xhr.responseText && xhr.responseText.length > 0) {
  7529. return true;
  7530. }
  7531. else if (dataType === 1) {
  7532. return false;
  7533. }
  7534. }
  7535. if (dataType & 2) {
  7536. // Check header width and height since there is no "TGA" magic number
  7537. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7538. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7539. return true;
  7540. }
  7541. else if (dataType === 2) {
  7542. return false;
  7543. }
  7544. }
  7545. if (dataType & 4) {
  7546. // Check for the "DDS" magic number
  7547. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7548. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7549. return true;
  7550. }
  7551. else {
  7552. return false;
  7553. }
  7554. }
  7555. }
  7556. catch (e) {
  7557. // Global protection
  7558. }
  7559. return false;
  7560. };
  7561. /**
  7562. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7563. * Be aware Math.random() could cause collisions, but:
  7564. * "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"
  7565. */
  7566. Tools.RandomId = function () {
  7567. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7568. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7569. return v.toString(16);
  7570. });
  7571. };
  7572. Object.defineProperty(Tools, "NoneLogLevel", {
  7573. get: function () {
  7574. return Tools._NoneLogLevel;
  7575. },
  7576. enumerable: true,
  7577. configurable: true
  7578. });
  7579. Object.defineProperty(Tools, "MessageLogLevel", {
  7580. get: function () {
  7581. return Tools._MessageLogLevel;
  7582. },
  7583. enumerable: true,
  7584. configurable: true
  7585. });
  7586. Object.defineProperty(Tools, "WarningLogLevel", {
  7587. get: function () {
  7588. return Tools._WarningLogLevel;
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. Object.defineProperty(Tools, "ErrorLogLevel", {
  7594. get: function () {
  7595. return Tools._ErrorLogLevel;
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(Tools, "AllLogLevel", {
  7601. get: function () {
  7602. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7603. },
  7604. enumerable: true,
  7605. configurable: true
  7606. });
  7607. Tools._AddLogEntry = function (entry) {
  7608. Tools._LogCache = entry + Tools._LogCache;
  7609. if (Tools.OnNewCacheEntry) {
  7610. Tools.OnNewCacheEntry(entry);
  7611. }
  7612. };
  7613. Tools._FormatMessage = function (message) {
  7614. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7615. var date = new Date();
  7616. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7617. };
  7618. Tools._LogDisabled = function (message) {
  7619. // nothing to do
  7620. };
  7621. Tools._LogEnabled = function (message) {
  7622. var formattedMessage = Tools._FormatMessage(message);
  7623. console.log("BJS - " + formattedMessage);
  7624. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7625. Tools._AddLogEntry(entry);
  7626. };
  7627. Tools._WarnDisabled = function (message) {
  7628. // nothing to do
  7629. };
  7630. Tools._WarnEnabled = function (message) {
  7631. var formattedMessage = Tools._FormatMessage(message);
  7632. console.warn("BJS - " + formattedMessage);
  7633. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7634. Tools._AddLogEntry(entry);
  7635. };
  7636. Tools._ErrorDisabled = function (message) {
  7637. // nothing to do
  7638. };
  7639. Tools._ErrorEnabled = function (message) {
  7640. Tools.errorsCount++;
  7641. var formattedMessage = Tools._FormatMessage(message);
  7642. console.error("BJS - " + formattedMessage);
  7643. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7644. Tools._AddLogEntry(entry);
  7645. };
  7646. Object.defineProperty(Tools, "LogCache", {
  7647. get: function () {
  7648. return Tools._LogCache;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Tools.ClearLogCache = function () {
  7654. Tools._LogCache = "";
  7655. Tools.errorsCount = 0;
  7656. };
  7657. Object.defineProperty(Tools, "LogLevels", {
  7658. set: function (level) {
  7659. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7660. Tools.Log = Tools._LogEnabled;
  7661. }
  7662. else {
  7663. Tools.Log = Tools._LogDisabled;
  7664. }
  7665. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7666. Tools.Warn = Tools._WarnEnabled;
  7667. }
  7668. else {
  7669. Tools.Warn = Tools._WarnDisabled;
  7670. }
  7671. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7672. Tools.Error = Tools._ErrorEnabled;
  7673. }
  7674. else {
  7675. Tools.Error = Tools._ErrorDisabled;
  7676. }
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. Tools.IsWindowObjectExist = function () {
  7682. return (typeof window) !== "undefined";
  7683. };
  7684. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7685. get: function () {
  7686. return Tools._PerformanceNoneLogLevel;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7692. get: function () {
  7693. return Tools._PerformanceUserMarkLogLevel;
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7699. get: function () {
  7700. return Tools._PerformanceConsoleLogLevel;
  7701. },
  7702. enumerable: true,
  7703. configurable: true
  7704. });
  7705. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7706. set: function (level) {
  7707. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7708. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7709. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7710. return;
  7711. }
  7712. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7713. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7714. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7715. return;
  7716. }
  7717. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7718. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7719. },
  7720. enumerable: true,
  7721. configurable: true
  7722. });
  7723. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7724. };
  7725. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7726. };
  7727. Tools._StartUserMark = function (counterName, condition) {
  7728. if (condition === void 0) { condition = true; }
  7729. if (!Tools._performance) {
  7730. if (!Tools.IsWindowObjectExist()) {
  7731. return;
  7732. }
  7733. Tools._performance = window.performance;
  7734. }
  7735. if (!condition || !Tools._performance.mark) {
  7736. return;
  7737. }
  7738. Tools._performance.mark(counterName + "-Begin");
  7739. };
  7740. Tools._EndUserMark = function (counterName, condition) {
  7741. if (condition === void 0) { condition = true; }
  7742. if (!condition || !Tools._performance.mark) {
  7743. return;
  7744. }
  7745. Tools._performance.mark(counterName + "-End");
  7746. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7747. };
  7748. Tools._StartPerformanceConsole = function (counterName, condition) {
  7749. if (condition === void 0) { condition = true; }
  7750. if (!condition) {
  7751. return;
  7752. }
  7753. Tools._StartUserMark(counterName, condition);
  7754. if (console.time) {
  7755. console.time(counterName);
  7756. }
  7757. };
  7758. Tools._EndPerformanceConsole = function (counterName, condition) {
  7759. if (condition === void 0) { condition = true; }
  7760. if (!condition) {
  7761. return;
  7762. }
  7763. Tools._EndUserMark(counterName, condition);
  7764. if (console.time) {
  7765. console.timeEnd(counterName);
  7766. }
  7767. };
  7768. Object.defineProperty(Tools, "Now", {
  7769. get: function () {
  7770. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7771. return window.performance.now();
  7772. }
  7773. return new Date().getTime();
  7774. },
  7775. enumerable: true,
  7776. configurable: true
  7777. });
  7778. /**
  7779. * This method will return the name of the class used to create the instance of the given object.
  7780. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7781. * @param object the object to get the class name from
  7782. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7783. */
  7784. Tools.GetClassName = function (object, isType) {
  7785. if (isType === void 0) { isType = false; }
  7786. var name = null;
  7787. if (!isType && object.getClassName) {
  7788. name = object.getClassName();
  7789. }
  7790. else {
  7791. if (object instanceof Object) {
  7792. var classObj = isType ? object : Object.getPrototypeOf(object);
  7793. name = classObj.constructor["__bjsclassName__"];
  7794. }
  7795. if (!name) {
  7796. name = typeof object;
  7797. }
  7798. }
  7799. return name;
  7800. };
  7801. Tools.First = function (array, predicate) {
  7802. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7803. var el = array_1[_i];
  7804. if (predicate(el)) {
  7805. return el;
  7806. }
  7807. }
  7808. return null;
  7809. };
  7810. /**
  7811. * This method will return the name of the full name of the class, including its owning module (if any).
  7812. * 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).
  7813. * @param object the object to get the class name from
  7814. * @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.
  7815. */
  7816. Tools.getFullClassName = function (object, isType) {
  7817. if (isType === void 0) { isType = false; }
  7818. var className = null;
  7819. var moduleName = null;
  7820. if (!isType && object.getClassName) {
  7821. className = object.getClassName();
  7822. }
  7823. else {
  7824. if (object instanceof Object) {
  7825. var classObj = isType ? object : Object.getPrototypeOf(object);
  7826. className = classObj.constructor["__bjsclassName__"];
  7827. moduleName = classObj.constructor["__bjsmoduleName__"];
  7828. }
  7829. if (!className) {
  7830. className = typeof object;
  7831. }
  7832. }
  7833. if (!className) {
  7834. return null;
  7835. }
  7836. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7837. };
  7838. /**
  7839. * 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.
  7840. * @param array
  7841. */
  7842. Tools.arrayOrStringFeeder = function (array) {
  7843. return function (index) {
  7844. if (index >= array.length) {
  7845. return null;
  7846. }
  7847. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7848. if (val && val.getHashCode) {
  7849. val = val.getHashCode();
  7850. }
  7851. if (typeof val === "string") {
  7852. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7853. }
  7854. return val;
  7855. };
  7856. };
  7857. /**
  7858. * Compute the hashCode of a stream of number
  7859. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7860. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7861. * @return the hash code computed
  7862. */
  7863. Tools.hashCodeFromStream = function (feeder) {
  7864. // Based from here: http://stackoverflow.com/a/7616484/802124
  7865. var hash = 0;
  7866. var index = 0;
  7867. var chr = feeder(index++);
  7868. while (chr != null) {
  7869. hash = ((hash << 5) - hash) + chr;
  7870. hash |= 0; // Convert to 32bit integer
  7871. chr = feeder(index++);
  7872. }
  7873. return hash;
  7874. };
  7875. Tools.BaseUrl = "";
  7876. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7877. /**
  7878. * Default behaviour for cors in the application.
  7879. * It can be a string if the expected behavior is identical in the entire app.
  7880. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7881. */
  7882. Tools.CorsBehavior = "anonymous";
  7883. Tools.UseFallbackTexture = true;
  7884. /**
  7885. * Use this object to register external classes like custom textures or material
  7886. * to allow the laoders to instantiate them
  7887. */
  7888. Tools.RegisteredExternalClasses = {};
  7889. // Used in case of a texture loading problem
  7890. 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";
  7891. Tools.PreprocessUrl = function (url) {
  7892. return url;
  7893. };
  7894. // Logs
  7895. Tools._NoneLogLevel = 0;
  7896. Tools._MessageLogLevel = 1;
  7897. Tools._WarningLogLevel = 2;
  7898. Tools._ErrorLogLevel = 4;
  7899. Tools._LogCache = "";
  7900. Tools.errorsCount = 0;
  7901. Tools.Log = Tools._LogEnabled;
  7902. Tools.Warn = Tools._WarnEnabled;
  7903. Tools.Error = Tools._ErrorEnabled;
  7904. // Performances
  7905. Tools._PerformanceNoneLogLevel = 0;
  7906. Tools._PerformanceUserMarkLogLevel = 1;
  7907. Tools._PerformanceConsoleLogLevel = 2;
  7908. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7909. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7910. return Tools;
  7911. }());
  7912. BABYLON.Tools = Tools;
  7913. /**
  7914. * This class is used to track a performance counter which is number based.
  7915. * The user has access to many properties which give statistics of different nature
  7916. *
  7917. * The implementer can track two kinds of Performance Counter: time and count
  7918. * 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.
  7919. * 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.
  7920. */
  7921. var PerfCounter = /** @class */ (function () {
  7922. function PerfCounter() {
  7923. this._startMonitoringTime = 0;
  7924. this._min = 0;
  7925. this._max = 0;
  7926. this._average = 0;
  7927. this._lastSecAverage = 0;
  7928. this._current = 0;
  7929. this._totalValueCount = 0;
  7930. this._totalAccumulated = 0;
  7931. this._lastSecAccumulated = 0;
  7932. this._lastSecTime = 0;
  7933. this._lastSecValueCount = 0;
  7934. }
  7935. Object.defineProperty(PerfCounter.prototype, "min", {
  7936. /**
  7937. * Returns the smallest value ever
  7938. */
  7939. get: function () {
  7940. return this._min;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. Object.defineProperty(PerfCounter.prototype, "max", {
  7946. /**
  7947. * Returns the biggest value ever
  7948. */
  7949. get: function () {
  7950. return this._max;
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(PerfCounter.prototype, "average", {
  7956. /**
  7957. * Returns the average value since the performance counter is running
  7958. */
  7959. get: function () {
  7960. return this._average;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7966. /**
  7967. * Returns the average value of the last second the counter was monitored
  7968. */
  7969. get: function () {
  7970. return this._lastSecAverage;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(PerfCounter.prototype, "current", {
  7976. /**
  7977. * Returns the current value
  7978. */
  7979. get: function () {
  7980. return this._current;
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(PerfCounter.prototype, "total", {
  7986. get: function () {
  7987. return this._totalAccumulated;
  7988. },
  7989. enumerable: true,
  7990. configurable: true
  7991. });
  7992. Object.defineProperty(PerfCounter.prototype, "count", {
  7993. get: function () {
  7994. return this._totalValueCount;
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. /**
  8000. * Call this method to start monitoring a new frame.
  8001. * 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.
  8002. */
  8003. PerfCounter.prototype.fetchNewFrame = function () {
  8004. this._totalValueCount++;
  8005. this._current = 0;
  8006. this._lastSecValueCount++;
  8007. };
  8008. /**
  8009. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8010. * @param newCount the count value to add to the monitored count
  8011. * @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.
  8012. */
  8013. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8014. if (!PerfCounter.Enabled) {
  8015. return;
  8016. }
  8017. this._current += newCount;
  8018. if (fetchResult) {
  8019. this._fetchResult();
  8020. }
  8021. };
  8022. /**
  8023. * Start monitoring this performance counter
  8024. */
  8025. PerfCounter.prototype.beginMonitoring = function () {
  8026. if (!PerfCounter.Enabled) {
  8027. return;
  8028. }
  8029. this._startMonitoringTime = Tools.Now;
  8030. };
  8031. /**
  8032. * Compute the time lapsed since the previous beginMonitoring() call.
  8033. * @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
  8034. */
  8035. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8036. if (newFrame === void 0) { newFrame = true; }
  8037. if (!PerfCounter.Enabled) {
  8038. return;
  8039. }
  8040. if (newFrame) {
  8041. this.fetchNewFrame();
  8042. }
  8043. var currentTime = Tools.Now;
  8044. this._current = currentTime - this._startMonitoringTime;
  8045. if (newFrame) {
  8046. this._fetchResult();
  8047. }
  8048. };
  8049. PerfCounter.prototype._fetchResult = function () {
  8050. this._totalAccumulated += this._current;
  8051. this._lastSecAccumulated += this._current;
  8052. // Min/Max update
  8053. this._min = Math.min(this._min, this._current);
  8054. this._max = Math.max(this._max, this._current);
  8055. this._average = this._totalAccumulated / this._totalValueCount;
  8056. // Reset last sec?
  8057. var now = Tools.Now;
  8058. if ((now - this._lastSecTime) > 1000) {
  8059. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8060. this._lastSecTime = now;
  8061. this._lastSecAccumulated = 0;
  8062. this._lastSecValueCount = 0;
  8063. }
  8064. };
  8065. PerfCounter.Enabled = true;
  8066. return PerfCounter;
  8067. }());
  8068. BABYLON.PerfCounter = PerfCounter;
  8069. /**
  8070. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8071. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8072. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8073. * @param name The name of the class, case should be preserved
  8074. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8075. */
  8076. function className(name, module) {
  8077. return function (target) {
  8078. target["__bjsclassName__"] = name;
  8079. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8080. };
  8081. }
  8082. BABYLON.className = className;
  8083. /**
  8084. * An implementation of a loop for asynchronous functions.
  8085. */
  8086. var AsyncLoop = /** @class */ (function () {
  8087. /**
  8088. * Constroctor.
  8089. * @param iterations the number of iterations.
  8090. * @param _fn the function to run each iteration
  8091. * @param _successCallback the callback that will be called upon succesful execution
  8092. * @param offset starting offset.
  8093. */
  8094. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8095. if (offset === void 0) { offset = 0; }
  8096. this.iterations = iterations;
  8097. this._fn = _fn;
  8098. this._successCallback = _successCallback;
  8099. this.index = offset - 1;
  8100. this._done = false;
  8101. }
  8102. /**
  8103. * Execute the next iteration. Must be called after the last iteration was finished.
  8104. */
  8105. AsyncLoop.prototype.executeNext = function () {
  8106. if (!this._done) {
  8107. if (this.index + 1 < this.iterations) {
  8108. ++this.index;
  8109. this._fn(this);
  8110. }
  8111. else {
  8112. this.breakLoop();
  8113. }
  8114. }
  8115. };
  8116. /**
  8117. * Break the loop and run the success callback.
  8118. */
  8119. AsyncLoop.prototype.breakLoop = function () {
  8120. this._done = true;
  8121. this._successCallback();
  8122. };
  8123. /**
  8124. * Helper function
  8125. */
  8126. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8127. if (offset === void 0) { offset = 0; }
  8128. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8129. loop.executeNext();
  8130. return loop;
  8131. };
  8132. /**
  8133. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8134. * @param iterations total number of iterations
  8135. * @param syncedIterations number of synchronous iterations in each async iteration.
  8136. * @param fn the function to call each iteration.
  8137. * @param callback a success call back that will be called when iterating stops.
  8138. * @param breakFunction a break condition (optional)
  8139. * @param timeout timeout settings for the setTimeout function. default - 0.
  8140. * @constructor
  8141. */
  8142. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8143. if (timeout === void 0) { timeout = 0; }
  8144. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8145. if (breakFunction && breakFunction())
  8146. loop.breakLoop();
  8147. else {
  8148. setTimeout(function () {
  8149. for (var i = 0; i < syncedIterations; ++i) {
  8150. var iteration = (loop.index * syncedIterations) + i;
  8151. if (iteration >= iterations)
  8152. break;
  8153. fn(iteration);
  8154. if (breakFunction && breakFunction()) {
  8155. loop.breakLoop();
  8156. break;
  8157. }
  8158. }
  8159. loop.executeNext();
  8160. }, timeout);
  8161. }
  8162. }, callback);
  8163. };
  8164. return AsyncLoop;
  8165. }());
  8166. BABYLON.AsyncLoop = AsyncLoop;
  8167. })(BABYLON || (BABYLON = {}));
  8168. //# sourceMappingURL=babylon.tools.js.map
  8169. var BABYLON;
  8170. (function (BABYLON) {
  8171. var _AlphaState = /** @class */ (function () {
  8172. /**
  8173. * Initializes the state.
  8174. */
  8175. function _AlphaState() {
  8176. this._isAlphaBlendDirty = false;
  8177. this._isBlendFunctionParametersDirty = false;
  8178. this._isBlendEquationParametersDirty = false;
  8179. this._isBlendConstantsDirty = false;
  8180. this._alphaBlend = false;
  8181. this._blendFunctionParameters = new Array(4);
  8182. this._blendEquationParameters = new Array(2);
  8183. this._blendConstants = new Array(4);
  8184. this.reset();
  8185. }
  8186. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8187. get: function () {
  8188. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8189. },
  8190. enumerable: true,
  8191. configurable: true
  8192. });
  8193. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8194. get: function () {
  8195. return this._alphaBlend;
  8196. },
  8197. set: function (value) {
  8198. if (this._alphaBlend === value) {
  8199. return;
  8200. }
  8201. this._alphaBlend = value;
  8202. this._isAlphaBlendDirty = true;
  8203. },
  8204. enumerable: true,
  8205. configurable: true
  8206. });
  8207. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8208. if (this._blendConstants[0] === r &&
  8209. this._blendConstants[1] === g &&
  8210. this._blendConstants[2] === b &&
  8211. this._blendConstants[3] === a) {
  8212. return;
  8213. }
  8214. this._blendConstants[0] = r;
  8215. this._blendConstants[1] = g;
  8216. this._blendConstants[2] = b;
  8217. this._blendConstants[3] = a;
  8218. this._isBlendConstantsDirty = true;
  8219. };
  8220. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8221. if (this._blendFunctionParameters[0] === value0 &&
  8222. this._blendFunctionParameters[1] === value1 &&
  8223. this._blendFunctionParameters[2] === value2 &&
  8224. this._blendFunctionParameters[3] === value3) {
  8225. return;
  8226. }
  8227. this._blendFunctionParameters[0] = value0;
  8228. this._blendFunctionParameters[1] = value1;
  8229. this._blendFunctionParameters[2] = value2;
  8230. this._blendFunctionParameters[3] = value3;
  8231. this._isBlendFunctionParametersDirty = true;
  8232. };
  8233. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8234. if (this._blendEquationParameters[0] === rgb &&
  8235. this._blendEquationParameters[1] === alpha) {
  8236. return;
  8237. }
  8238. this._blendEquationParameters[0] = rgb;
  8239. this._blendEquationParameters[1] = alpha;
  8240. this._isBlendEquationParametersDirty = true;
  8241. };
  8242. _AlphaState.prototype.reset = function () {
  8243. this._alphaBlend = false;
  8244. this._blendFunctionParameters[0] = null;
  8245. this._blendFunctionParameters[1] = null;
  8246. this._blendFunctionParameters[2] = null;
  8247. this._blendFunctionParameters[3] = null;
  8248. this._blendEquationParameters[0] = null;
  8249. this._blendEquationParameters[1] = null;
  8250. this._blendConstants[0] = null;
  8251. this._blendConstants[1] = null;
  8252. this._blendConstants[2] = null;
  8253. this._blendConstants[3] = null;
  8254. this._isAlphaBlendDirty = true;
  8255. this._isBlendFunctionParametersDirty = false;
  8256. this._isBlendEquationParametersDirty = false;
  8257. this._isBlendConstantsDirty = false;
  8258. };
  8259. _AlphaState.prototype.apply = function (gl) {
  8260. if (!this.isDirty) {
  8261. return;
  8262. }
  8263. // Alpha blend
  8264. if (this._isAlphaBlendDirty) {
  8265. if (this._alphaBlend) {
  8266. gl.enable(gl.BLEND);
  8267. }
  8268. else {
  8269. gl.disable(gl.BLEND);
  8270. }
  8271. this._isAlphaBlendDirty = false;
  8272. }
  8273. // Alpha function
  8274. if (this._isBlendFunctionParametersDirty) {
  8275. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8276. this._isBlendFunctionParametersDirty = false;
  8277. }
  8278. // Alpha equation
  8279. if (this._isBlendEquationParametersDirty) {
  8280. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8281. this._isBlendEquationParametersDirty = false;
  8282. }
  8283. // Constants
  8284. if (this._isBlendConstantsDirty) {
  8285. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8286. this._isBlendConstantsDirty = false;
  8287. }
  8288. };
  8289. return _AlphaState;
  8290. }());
  8291. BABYLON._AlphaState = _AlphaState;
  8292. })(BABYLON || (BABYLON = {}));
  8293. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8294. var BABYLON;
  8295. (function (BABYLON) {
  8296. var _DepthCullingState = /** @class */ (function () {
  8297. /**
  8298. * Initializes the state.
  8299. */
  8300. function _DepthCullingState() {
  8301. this._isDepthTestDirty = false;
  8302. this._isDepthMaskDirty = false;
  8303. this._isDepthFuncDirty = false;
  8304. this._isCullFaceDirty = false;
  8305. this._isCullDirty = false;
  8306. this._isZOffsetDirty = false;
  8307. this._isFrontFaceDirty = false;
  8308. this.reset();
  8309. }
  8310. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8311. get: function () {
  8312. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8318. get: function () {
  8319. return this._zOffset;
  8320. },
  8321. set: function (value) {
  8322. if (this._zOffset === value) {
  8323. return;
  8324. }
  8325. this._zOffset = value;
  8326. this._isZOffsetDirty = true;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8332. get: function () {
  8333. return this._cullFace;
  8334. },
  8335. set: function (value) {
  8336. if (this._cullFace === value) {
  8337. return;
  8338. }
  8339. this._cullFace = value;
  8340. this._isCullFaceDirty = true;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8346. get: function () {
  8347. return this._cull;
  8348. },
  8349. set: function (value) {
  8350. if (this._cull === value) {
  8351. return;
  8352. }
  8353. this._cull = value;
  8354. this._isCullDirty = true;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8360. get: function () {
  8361. return this._depthFunc;
  8362. },
  8363. set: function (value) {
  8364. if (this._depthFunc === value) {
  8365. return;
  8366. }
  8367. this._depthFunc = value;
  8368. this._isDepthFuncDirty = true;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8374. get: function () {
  8375. return this._depthMask;
  8376. },
  8377. set: function (value) {
  8378. if (this._depthMask === value) {
  8379. return;
  8380. }
  8381. this._depthMask = value;
  8382. this._isDepthMaskDirty = true;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8388. get: function () {
  8389. return this._depthTest;
  8390. },
  8391. set: function (value) {
  8392. if (this._depthTest === value) {
  8393. return;
  8394. }
  8395. this._depthTest = value;
  8396. this._isDepthTestDirty = true;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8402. get: function () {
  8403. return this._frontFace;
  8404. },
  8405. set: function (value) {
  8406. if (this._frontFace === value) {
  8407. return;
  8408. }
  8409. this._frontFace = value;
  8410. this._isFrontFaceDirty = true;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. _DepthCullingState.prototype.reset = function () {
  8416. this._depthMask = true;
  8417. this._depthTest = true;
  8418. this._depthFunc = null;
  8419. this._cullFace = null;
  8420. this._cull = null;
  8421. this._zOffset = 0;
  8422. this._frontFace = null;
  8423. this._isDepthTestDirty = true;
  8424. this._isDepthMaskDirty = true;
  8425. this._isDepthFuncDirty = false;
  8426. this._isCullFaceDirty = false;
  8427. this._isCullDirty = false;
  8428. this._isZOffsetDirty = false;
  8429. this._isFrontFaceDirty = false;
  8430. };
  8431. _DepthCullingState.prototype.apply = function (gl) {
  8432. if (!this.isDirty) {
  8433. return;
  8434. }
  8435. // Cull
  8436. if (this._isCullDirty) {
  8437. if (this.cull) {
  8438. gl.enable(gl.CULL_FACE);
  8439. }
  8440. else {
  8441. gl.disable(gl.CULL_FACE);
  8442. }
  8443. this._isCullDirty = false;
  8444. }
  8445. // Cull face
  8446. if (this._isCullFaceDirty) {
  8447. gl.cullFace(this.cullFace);
  8448. this._isCullFaceDirty = false;
  8449. }
  8450. // Depth mask
  8451. if (this._isDepthMaskDirty) {
  8452. gl.depthMask(this.depthMask);
  8453. this._isDepthMaskDirty = false;
  8454. }
  8455. // Depth test
  8456. if (this._isDepthTestDirty) {
  8457. if (this.depthTest) {
  8458. gl.enable(gl.DEPTH_TEST);
  8459. }
  8460. else {
  8461. gl.disable(gl.DEPTH_TEST);
  8462. }
  8463. this._isDepthTestDirty = false;
  8464. }
  8465. // Depth func
  8466. if (this._isDepthFuncDirty) {
  8467. gl.depthFunc(this.depthFunc);
  8468. this._isDepthFuncDirty = false;
  8469. }
  8470. // zOffset
  8471. if (this._isZOffsetDirty) {
  8472. if (this.zOffset) {
  8473. gl.enable(gl.POLYGON_OFFSET_FILL);
  8474. gl.polygonOffset(this.zOffset, 0);
  8475. }
  8476. else {
  8477. gl.disable(gl.POLYGON_OFFSET_FILL);
  8478. }
  8479. this._isZOffsetDirty = false;
  8480. }
  8481. // Front face
  8482. if (this._isFrontFaceDirty) {
  8483. gl.frontFace(this.frontFace);
  8484. this._isFrontFaceDirty = false;
  8485. }
  8486. };
  8487. return _DepthCullingState;
  8488. }());
  8489. BABYLON._DepthCullingState = _DepthCullingState;
  8490. })(BABYLON || (BABYLON = {}));
  8491. //# sourceMappingURL=babylon.depthCullingState.js.map
  8492. var BABYLON;
  8493. (function (BABYLON) {
  8494. var _StencilState = /** @class */ (function () {
  8495. function _StencilState() {
  8496. this._isStencilTestDirty = false;
  8497. this._isStencilMaskDirty = false;
  8498. this._isStencilFuncDirty = false;
  8499. this._isStencilOpDirty = false;
  8500. this.reset();
  8501. }
  8502. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8503. get: function () {
  8504. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8505. },
  8506. enumerable: true,
  8507. configurable: true
  8508. });
  8509. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8510. get: function () {
  8511. return this._stencilFunc;
  8512. },
  8513. set: function (value) {
  8514. if (this._stencilFunc === value) {
  8515. return;
  8516. }
  8517. this._stencilFunc = value;
  8518. this._isStencilFuncDirty = true;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8524. get: function () {
  8525. return this._stencilFuncRef;
  8526. },
  8527. set: function (value) {
  8528. if (this._stencilFuncRef === value) {
  8529. return;
  8530. }
  8531. this._stencilFuncRef = value;
  8532. this._isStencilFuncDirty = true;
  8533. },
  8534. enumerable: true,
  8535. configurable: true
  8536. });
  8537. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8538. get: function () {
  8539. return this._stencilFuncMask;
  8540. },
  8541. set: function (value) {
  8542. if (this._stencilFuncMask === value) {
  8543. return;
  8544. }
  8545. this._stencilFuncMask = value;
  8546. this._isStencilFuncDirty = true;
  8547. },
  8548. enumerable: true,
  8549. configurable: true
  8550. });
  8551. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8552. get: function () {
  8553. return this._stencilOpStencilFail;
  8554. },
  8555. set: function (value) {
  8556. if (this._stencilOpStencilFail === value) {
  8557. return;
  8558. }
  8559. this._stencilOpStencilFail = value;
  8560. this._isStencilOpDirty = true;
  8561. },
  8562. enumerable: true,
  8563. configurable: true
  8564. });
  8565. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8566. get: function () {
  8567. return this._stencilOpDepthFail;
  8568. },
  8569. set: function (value) {
  8570. if (this._stencilOpDepthFail === value) {
  8571. return;
  8572. }
  8573. this._stencilOpDepthFail = value;
  8574. this._isStencilOpDirty = true;
  8575. },
  8576. enumerable: true,
  8577. configurable: true
  8578. });
  8579. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8580. get: function () {
  8581. return this._stencilOpStencilDepthPass;
  8582. },
  8583. set: function (value) {
  8584. if (this._stencilOpStencilDepthPass === value) {
  8585. return;
  8586. }
  8587. this._stencilOpStencilDepthPass = value;
  8588. this._isStencilOpDirty = true;
  8589. },
  8590. enumerable: true,
  8591. configurable: true
  8592. });
  8593. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8594. get: function () {
  8595. return this._stencilMask;
  8596. },
  8597. set: function (value) {
  8598. if (this._stencilMask === value) {
  8599. return;
  8600. }
  8601. this._stencilMask = value;
  8602. this._isStencilMaskDirty = true;
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8608. get: function () {
  8609. return this._stencilTest;
  8610. },
  8611. set: function (value) {
  8612. if (this._stencilTest === value) {
  8613. return;
  8614. }
  8615. this._stencilTest = value;
  8616. this._isStencilTestDirty = true;
  8617. },
  8618. enumerable: true,
  8619. configurable: true
  8620. });
  8621. _StencilState.prototype.reset = function () {
  8622. this._stencilTest = false;
  8623. this._stencilMask = 0xFF;
  8624. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8625. this._stencilFuncRef = 1;
  8626. this._stencilFuncMask = 0xFF;
  8627. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8628. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8629. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8630. this._isStencilTestDirty = true;
  8631. this._isStencilMaskDirty = true;
  8632. this._isStencilFuncDirty = true;
  8633. this._isStencilOpDirty = true;
  8634. };
  8635. _StencilState.prototype.apply = function (gl) {
  8636. if (!this.isDirty) {
  8637. return;
  8638. }
  8639. // Stencil test
  8640. if (this._isStencilTestDirty) {
  8641. if (this.stencilTest) {
  8642. gl.enable(gl.STENCIL_TEST);
  8643. }
  8644. else {
  8645. gl.disable(gl.STENCIL_TEST);
  8646. }
  8647. this._isStencilTestDirty = false;
  8648. }
  8649. // Stencil mask
  8650. if (this._isStencilMaskDirty) {
  8651. gl.stencilMask(this.stencilMask);
  8652. this._isStencilMaskDirty = false;
  8653. }
  8654. // Stencil func
  8655. if (this._isStencilFuncDirty) {
  8656. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8657. this._isStencilFuncDirty = false;
  8658. }
  8659. // Stencil op
  8660. if (this._isStencilOpDirty) {
  8661. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8662. this._isStencilOpDirty = false;
  8663. }
  8664. };
  8665. return _StencilState;
  8666. }());
  8667. BABYLON._StencilState = _StencilState;
  8668. })(BABYLON || (BABYLON = {}));
  8669. //# sourceMappingURL=babylon.stencilState.js.map
  8670. var BABYLON;
  8671. (function (BABYLON) {
  8672. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8673. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8674. };
  8675. var compileRawShader = function (gl, source, type) {
  8676. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8677. gl.shaderSource(shader, source);
  8678. gl.compileShader(shader);
  8679. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8680. var log = gl.getShaderInfoLog(shader);
  8681. if (log) {
  8682. throw new Error(log);
  8683. }
  8684. }
  8685. if (!shader) {
  8686. throw new Error("Something went wrong while compile the shader.");
  8687. }
  8688. return shader;
  8689. };
  8690. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8691. var magFilter = gl.NEAREST;
  8692. var minFilter = gl.NEAREST;
  8693. switch (samplingMode) {
  8694. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8695. magFilter = gl.LINEAR;
  8696. if (generateMipMaps) {
  8697. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8698. }
  8699. else {
  8700. minFilter = gl.LINEAR;
  8701. }
  8702. break;
  8703. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8704. magFilter = gl.LINEAR;
  8705. if (generateMipMaps) {
  8706. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8707. }
  8708. else {
  8709. minFilter = gl.LINEAR;
  8710. }
  8711. break;
  8712. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8713. magFilter = gl.NEAREST;
  8714. if (generateMipMaps) {
  8715. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8716. }
  8717. else {
  8718. minFilter = gl.NEAREST;
  8719. }
  8720. break;
  8721. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8722. magFilter = gl.NEAREST;
  8723. if (generateMipMaps) {
  8724. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8725. }
  8726. else {
  8727. minFilter = gl.NEAREST;
  8728. }
  8729. break;
  8730. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8731. magFilter = gl.NEAREST;
  8732. if (generateMipMaps) {
  8733. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8734. }
  8735. else {
  8736. minFilter = gl.LINEAR;
  8737. }
  8738. break;
  8739. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8740. magFilter = gl.NEAREST;
  8741. if (generateMipMaps) {
  8742. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8743. }
  8744. else {
  8745. minFilter = gl.LINEAR;
  8746. }
  8747. break;
  8748. case BABYLON.Texture.NEAREST_LINEAR:
  8749. magFilter = gl.NEAREST;
  8750. minFilter = gl.LINEAR;
  8751. break;
  8752. case BABYLON.Texture.NEAREST_NEAREST:
  8753. magFilter = gl.NEAREST;
  8754. minFilter = gl.NEAREST;
  8755. break;
  8756. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8757. magFilter = gl.LINEAR;
  8758. if (generateMipMaps) {
  8759. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8760. }
  8761. else {
  8762. minFilter = gl.NEAREST;
  8763. }
  8764. break;
  8765. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8766. magFilter = gl.LINEAR;
  8767. if (generateMipMaps) {
  8768. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8769. }
  8770. else {
  8771. minFilter = gl.NEAREST;
  8772. }
  8773. break;
  8774. case BABYLON.Texture.LINEAR_LINEAR:
  8775. magFilter = gl.LINEAR;
  8776. minFilter = gl.LINEAR;
  8777. break;
  8778. case BABYLON.Texture.LINEAR_NEAREST:
  8779. magFilter = gl.LINEAR;
  8780. minFilter = gl.NEAREST;
  8781. break;
  8782. }
  8783. return {
  8784. min: minFilter,
  8785. mag: magFilter
  8786. };
  8787. };
  8788. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8789. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8790. var img;
  8791. var onload = function () {
  8792. loadedImages[index] = img;
  8793. loadedImages._internalCount++;
  8794. if (scene) {
  8795. scene._removePendingData(img);
  8796. }
  8797. if (loadedImages._internalCount === 6) {
  8798. onfinish(loadedImages);
  8799. }
  8800. };
  8801. var onerror = function (message, exception) {
  8802. if (scene) {
  8803. scene._removePendingData(img);
  8804. }
  8805. if (onErrorCallBack) {
  8806. onErrorCallBack(message, exception);
  8807. }
  8808. };
  8809. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8810. if (scene) {
  8811. scene._addPendingData(img);
  8812. }
  8813. };
  8814. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8815. if (onError === void 0) { onError = null; }
  8816. var loadedImages = [];
  8817. loadedImages._internalCount = 0;
  8818. for (var index = 0; index < 6; index++) {
  8819. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8820. }
  8821. };
  8822. var BufferPointer = /** @class */ (function () {
  8823. function BufferPointer() {
  8824. }
  8825. return BufferPointer;
  8826. }());
  8827. var InstancingAttributeInfo = /** @class */ (function () {
  8828. function InstancingAttributeInfo() {
  8829. }
  8830. return InstancingAttributeInfo;
  8831. }());
  8832. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8833. /**
  8834. * Define options used to create a render target texture
  8835. */
  8836. var RenderTargetCreationOptions = /** @class */ (function () {
  8837. function RenderTargetCreationOptions() {
  8838. }
  8839. return RenderTargetCreationOptions;
  8840. }());
  8841. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8842. /**
  8843. * Regroup several parameters relative to the browser in use
  8844. */
  8845. var EngineCapabilities = /** @class */ (function () {
  8846. function EngineCapabilities() {
  8847. }
  8848. return EngineCapabilities;
  8849. }());
  8850. BABYLON.EngineCapabilities = EngineCapabilities;
  8851. /**
  8852. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8853. */
  8854. var Engine = /** @class */ (function () {
  8855. /**
  8856. * @constructor
  8857. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8858. * @param {boolean} [antialias] - enable antialias
  8859. * @param options - further options to be sent to the getContext function
  8860. */
  8861. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8862. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8863. var _this = this;
  8864. // Public members
  8865. this.forcePOTTextures = false;
  8866. this.isFullscreen = false;
  8867. this.isPointerLock = false;
  8868. this.cullBackFaces = true;
  8869. this.renderEvenInBackground = true;
  8870. this.preventCacheWipeBetweenFrames = false;
  8871. // To enable/disable IDB support and avoid XHR on .manifest
  8872. this.enableOfflineSupport = false;
  8873. this.scenes = new Array();
  8874. this.postProcesses = new Array();
  8875. // Observables
  8876. /**
  8877. * Observable event triggered each time the rendering canvas is resized
  8878. */
  8879. this.onResizeObservable = new BABYLON.Observable();
  8880. /**
  8881. * Observable event triggered each time the canvas loses focus
  8882. */
  8883. this.onCanvasBlurObservable = new BABYLON.Observable();
  8884. /**
  8885. * Observable event triggered each time the canvas gains focus
  8886. */
  8887. this.onCanvasFocusObservable = new BABYLON.Observable();
  8888. /**
  8889. * Observable event triggered each time the canvas receives pointerout event
  8890. */
  8891. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8892. /**
  8893. * Observable event triggered before each texture is initialized
  8894. */
  8895. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8896. //WebVR
  8897. this._vrDisplay = undefined;
  8898. this._vrSupported = false;
  8899. this._vrExclusivePointerMode = false;
  8900. // Uniform buffers list
  8901. this.disableUniformBuffers = false;
  8902. this._uniformBuffers = new Array();
  8903. // Observables
  8904. /**
  8905. * Observable raised when the engine begins a new frame
  8906. */
  8907. this.onBeginFrameObservable = new BABYLON.Observable();
  8908. /**
  8909. * Observable raised when the engine ends the current frame
  8910. */
  8911. this.onEndFrameObservable = new BABYLON.Observable();
  8912. /**
  8913. * Observable raised when the engine is about to compile a shader
  8914. */
  8915. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8916. /**
  8917. * Observable raised when the engine has jsut compiled a shader
  8918. */
  8919. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8920. this._windowIsBackground = false;
  8921. this._webGLVersion = 1.0;
  8922. this._badOS = false;
  8923. this._badDesktopOS = false;
  8924. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8925. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8926. this.onVRRequestPresentStart = new BABYLON.Observable();
  8927. this._colorWrite = true;
  8928. this._drawCalls = new BABYLON.PerfCounter();
  8929. this._textureCollisions = new BABYLON.PerfCounter();
  8930. this._renderingQueueLaunched = false;
  8931. this._activeRenderLoops = new Array();
  8932. // Deterministic lockstepMaxSteps
  8933. this._deterministicLockstep = false;
  8934. this._lockstepMaxSteps = 4;
  8935. // Lost context
  8936. this.onContextLostObservable = new BABYLON.Observable();
  8937. this.onContextRestoredObservable = new BABYLON.Observable();
  8938. this._contextWasLost = false;
  8939. this._doNotHandleContextLost = false;
  8940. // FPS
  8941. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8942. this._fps = 60;
  8943. this._deltaTime = 0;
  8944. /**
  8945. * Turn this value on if you want to pause FPS computation when in background
  8946. */
  8947. this.disablePerformanceMonitorInBackground = false;
  8948. // States
  8949. this._depthCullingState = new BABYLON._DepthCullingState();
  8950. this._stencilState = new BABYLON._StencilState();
  8951. this._alphaState = new BABYLON._AlphaState();
  8952. this._alphaMode = Engine.ALPHA_DISABLE;
  8953. // Cache
  8954. this._internalTexturesCache = new Array();
  8955. this._boundTexturesCache = {};
  8956. this._boundTexturesStack = new Array();
  8957. this._compiledEffects = {};
  8958. this._vertexAttribArraysEnabled = [];
  8959. this._uintIndicesCurrentlySet = false;
  8960. this._currentBoundBuffer = new Array();
  8961. this._currentBufferPointers = new Array();
  8962. this._currentInstanceLocations = new Array();
  8963. this._currentInstanceBuffers = new Array();
  8964. this._vaoRecordInProgress = false;
  8965. this._mustWipeVertexAttributes = false;
  8966. this._nextFreeTextureSlots = new Array();
  8967. this._activeRequests = new Array();
  8968. // Hardware supported Compressed Textures
  8969. this._texturesSupported = new Array();
  8970. this._onVRFullScreenTriggered = function () {
  8971. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8972. //get the old size before we change
  8973. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8974. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8975. //get the width and height, change the render size
  8976. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8977. _this.setHardwareScalingLevel(1);
  8978. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8979. }
  8980. else {
  8981. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8982. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8983. }
  8984. };
  8985. this._boundUniforms = {};
  8986. var canvas = null;
  8987. Engine.Instances.push(this);
  8988. if (!canvasOrContext) {
  8989. return;
  8990. }
  8991. options = options || {};
  8992. if (canvasOrContext.getContext) {
  8993. canvas = canvasOrContext;
  8994. this._renderingCanvas = canvas;
  8995. if (antialias != null) {
  8996. options.antialias = antialias;
  8997. }
  8998. if (options.deterministicLockstep === undefined) {
  8999. options.deterministicLockstep = false;
  9000. }
  9001. if (options.lockstepMaxSteps === undefined) {
  9002. options.lockstepMaxSteps = 4;
  9003. }
  9004. if (options.preserveDrawingBuffer === undefined) {
  9005. options.preserveDrawingBuffer = false;
  9006. }
  9007. if (options.audioEngine === undefined) {
  9008. options.audioEngine = true;
  9009. }
  9010. if (options.stencil === undefined) {
  9011. options.stencil = true;
  9012. }
  9013. this._deterministicLockstep = options.deterministicLockstep;
  9014. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9015. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9016. // Exceptions
  9017. if (navigator && navigator.userAgent) {
  9018. var ua = navigator.userAgent;
  9019. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9020. var exception = _a[_i];
  9021. var key = exception.key;
  9022. var targets = exception.targets;
  9023. if (ua.indexOf(key) > -1) {
  9024. if (exception.capture && exception.captureConstraint) {
  9025. var capture = exception.capture;
  9026. var constraint = exception.captureConstraint;
  9027. var regex = new RegExp(capture);
  9028. var matches = regex.exec(ua);
  9029. if (matches && matches.length > 0) {
  9030. var capturedValue = parseInt(matches[matches.length - 1]);
  9031. if (capturedValue >= constraint) {
  9032. continue;
  9033. }
  9034. }
  9035. }
  9036. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9037. var target = targets_1[_b];
  9038. switch (target) {
  9039. case "uniformBuffer":
  9040. this.disableUniformBuffers = true;
  9041. break;
  9042. }
  9043. }
  9044. break;
  9045. }
  9046. }
  9047. }
  9048. // GL
  9049. if (!options.disableWebGL2Support) {
  9050. try {
  9051. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9052. if (this._gl) {
  9053. this._webGLVersion = 2.0;
  9054. }
  9055. }
  9056. catch (e) {
  9057. // Do nothing
  9058. }
  9059. }
  9060. if (!this._gl) {
  9061. if (!canvas) {
  9062. throw new Error("The provided canvas is null or undefined.");
  9063. }
  9064. try {
  9065. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9066. }
  9067. catch (e) {
  9068. throw new Error("WebGL not supported");
  9069. }
  9070. }
  9071. if (!this._gl) {
  9072. throw new Error("WebGL not supported");
  9073. }
  9074. this._onCanvasFocus = function () {
  9075. _this.onCanvasFocusObservable.notifyObservers(_this);
  9076. };
  9077. this._onCanvasBlur = function () {
  9078. _this.onCanvasBlurObservable.notifyObservers(_this);
  9079. };
  9080. canvas.addEventListener("focus", this._onCanvasFocus);
  9081. canvas.addEventListener("blur", this._onCanvasBlur);
  9082. this._onBlur = function () {
  9083. if (_this.disablePerformanceMonitorInBackground) {
  9084. _this._performanceMonitor.disable();
  9085. }
  9086. _this._windowIsBackground = true;
  9087. };
  9088. this._onFocus = function () {
  9089. if (_this.disablePerformanceMonitorInBackground) {
  9090. _this._performanceMonitor.enable();
  9091. }
  9092. _this._windowIsBackground = false;
  9093. };
  9094. this._onCanvasPointerOut = function () {
  9095. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9096. };
  9097. window.addEventListener("blur", this._onBlur);
  9098. window.addEventListener("focus", this._onFocus);
  9099. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9100. // Context lost
  9101. if (!this._doNotHandleContextLost) {
  9102. this._onContextLost = function (evt) {
  9103. evt.preventDefault();
  9104. _this._contextWasLost = true;
  9105. BABYLON.Tools.Warn("WebGL context lost.");
  9106. _this.onContextLostObservable.notifyObservers(_this);
  9107. };
  9108. this._onContextRestored = function (evt) {
  9109. // Adding a timeout to avoid race condition at browser level
  9110. setTimeout(function () {
  9111. // Rebuild gl context
  9112. _this._initGLContext();
  9113. // Rebuild effects
  9114. _this._rebuildEffects();
  9115. // Rebuild textures
  9116. _this._rebuildInternalTextures();
  9117. // Rebuild buffers
  9118. _this._rebuildBuffers();
  9119. // Cache
  9120. _this.wipeCaches(true);
  9121. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9122. _this.onContextRestoredObservable.notifyObservers(_this);
  9123. _this._contextWasLost = false;
  9124. }, 0);
  9125. };
  9126. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9127. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9128. }
  9129. }
  9130. else {
  9131. this._gl = canvasOrContext;
  9132. this._renderingCanvas = this._gl.canvas;
  9133. if (this._gl.renderbufferStorageMultisample) {
  9134. this._webGLVersion = 2.0;
  9135. }
  9136. options.stencil = this._gl.getContextAttributes().stencil;
  9137. }
  9138. // Viewport
  9139. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9140. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9141. this.resize();
  9142. this._isStencilEnable = options.stencil ? true : false;
  9143. this._initGLContext();
  9144. if (canvas) {
  9145. // Fullscreen
  9146. this._onFullscreenChange = function () {
  9147. if (document.fullscreen !== undefined) {
  9148. _this.isFullscreen = document.fullscreen;
  9149. }
  9150. else if (document.mozFullScreen !== undefined) {
  9151. _this.isFullscreen = document.mozFullScreen;
  9152. }
  9153. else if (document.webkitIsFullScreen !== undefined) {
  9154. _this.isFullscreen = document.webkitIsFullScreen;
  9155. }
  9156. else if (document.msIsFullScreen !== undefined) {
  9157. _this.isFullscreen = document.msIsFullScreen;
  9158. }
  9159. // Pointer lock
  9160. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9161. canvas.requestPointerLock = canvas.requestPointerLock ||
  9162. canvas.msRequestPointerLock ||
  9163. canvas.mozRequestPointerLock ||
  9164. canvas.webkitRequestPointerLock;
  9165. if (canvas.requestPointerLock) {
  9166. canvas.requestPointerLock();
  9167. }
  9168. }
  9169. };
  9170. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9171. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9172. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9173. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9174. // Pointer lock
  9175. this._onPointerLockChange = function () {
  9176. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9177. document.webkitPointerLockElement === canvas ||
  9178. document.msPointerLockElement === canvas ||
  9179. document.pointerLockElement === canvas);
  9180. };
  9181. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9182. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9183. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9184. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9185. this._onVRDisplayPointerRestricted = function () {
  9186. if (canvas) {
  9187. canvas.requestPointerLock();
  9188. }
  9189. };
  9190. this._onVRDisplayPointerUnrestricted = function () {
  9191. document.exitPointerLock();
  9192. };
  9193. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9194. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9195. }
  9196. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9197. Engine.audioEngine = new BABYLON.AudioEngine();
  9198. }
  9199. // Prepare buffer pointers
  9200. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9201. this._currentBufferPointers[i] = new BufferPointer();
  9202. }
  9203. // Load WebVR Devices
  9204. if (options.autoEnableWebVR) {
  9205. this.initWebVR();
  9206. }
  9207. // Detect if we are running on a faulty buggy OS.
  9208. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9209. // Detect if we are running on a faulty buggy desktop OS.
  9210. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9211. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9212. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9213. }
  9214. Object.defineProperty(Engine, "LastCreatedEngine", {
  9215. get: function () {
  9216. if (Engine.Instances.length === 0) {
  9217. return null;
  9218. }
  9219. return Engine.Instances[Engine.Instances.length - 1];
  9220. },
  9221. enumerable: true,
  9222. configurable: true
  9223. });
  9224. Object.defineProperty(Engine, "LastCreatedScene", {
  9225. get: function () {
  9226. var lastCreatedEngine = Engine.LastCreatedEngine;
  9227. if (!lastCreatedEngine) {
  9228. return null;
  9229. }
  9230. if (lastCreatedEngine.scenes.length === 0) {
  9231. return null;
  9232. }
  9233. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. /**
  9239. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9240. */
  9241. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9242. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9243. var engine = Engine.Instances[engineIndex];
  9244. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9245. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9246. }
  9247. }
  9248. };
  9249. Object.defineProperty(Engine, "NEVER", {
  9250. get: function () {
  9251. return Engine._NEVER;
  9252. },
  9253. enumerable: true,
  9254. configurable: true
  9255. });
  9256. Object.defineProperty(Engine, "ALWAYS", {
  9257. get: function () {
  9258. return Engine._ALWAYS;
  9259. },
  9260. enumerable: true,
  9261. configurable: true
  9262. });
  9263. Object.defineProperty(Engine, "LESS", {
  9264. get: function () {
  9265. return Engine._LESS;
  9266. },
  9267. enumerable: true,
  9268. configurable: true
  9269. });
  9270. Object.defineProperty(Engine, "EQUAL", {
  9271. get: function () {
  9272. return Engine._EQUAL;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. Object.defineProperty(Engine, "LEQUAL", {
  9278. get: function () {
  9279. return Engine._LEQUAL;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(Engine, "GREATER", {
  9285. get: function () {
  9286. return Engine._GREATER;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(Engine, "GEQUAL", {
  9292. get: function () {
  9293. return Engine._GEQUAL;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(Engine, "NOTEQUAL", {
  9299. get: function () {
  9300. return Engine._NOTEQUAL;
  9301. },
  9302. enumerable: true,
  9303. configurable: true
  9304. });
  9305. Object.defineProperty(Engine, "KEEP", {
  9306. get: function () {
  9307. return Engine._KEEP;
  9308. },
  9309. enumerable: true,
  9310. configurable: true
  9311. });
  9312. Object.defineProperty(Engine, "REPLACE", {
  9313. get: function () {
  9314. return Engine._REPLACE;
  9315. },
  9316. enumerable: true,
  9317. configurable: true
  9318. });
  9319. Object.defineProperty(Engine, "INCR", {
  9320. get: function () {
  9321. return Engine._INCR;
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(Engine, "DECR", {
  9327. get: function () {
  9328. return Engine._DECR;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(Engine, "INVERT", {
  9334. get: function () {
  9335. return Engine._INVERT;
  9336. },
  9337. enumerable: true,
  9338. configurable: true
  9339. });
  9340. Object.defineProperty(Engine, "INCR_WRAP", {
  9341. get: function () {
  9342. return Engine._INCR_WRAP;
  9343. },
  9344. enumerable: true,
  9345. configurable: true
  9346. });
  9347. Object.defineProperty(Engine, "DECR_WRAP", {
  9348. get: function () {
  9349. return Engine._DECR_WRAP;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9355. get: function () {
  9356. return Engine._ALPHA_DISABLE;
  9357. },
  9358. enumerable: true,
  9359. configurable: true
  9360. });
  9361. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9362. get: function () {
  9363. return Engine._ALPHA_ONEONE;
  9364. },
  9365. enumerable: true,
  9366. configurable: true
  9367. });
  9368. Object.defineProperty(Engine, "ALPHA_ADD", {
  9369. get: function () {
  9370. return Engine._ALPHA_ADD;
  9371. },
  9372. enumerable: true,
  9373. configurable: true
  9374. });
  9375. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9376. get: function () {
  9377. return Engine._ALPHA_COMBINE;
  9378. },
  9379. enumerable: true,
  9380. configurable: true
  9381. });
  9382. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9383. get: function () {
  9384. return Engine._ALPHA_SUBTRACT;
  9385. },
  9386. enumerable: true,
  9387. configurable: true
  9388. });
  9389. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9390. get: function () {
  9391. return Engine._ALPHA_MULTIPLY;
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9397. get: function () {
  9398. return Engine._ALPHA_MAXIMIZED;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9404. get: function () {
  9405. return Engine._ALPHA_PREMULTIPLIED;
  9406. },
  9407. enumerable: true,
  9408. configurable: true
  9409. });
  9410. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9411. get: function () {
  9412. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9413. },
  9414. enumerable: true,
  9415. configurable: true
  9416. });
  9417. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9418. get: function () {
  9419. return Engine._ALPHA_INTERPOLATE;
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9425. get: function () {
  9426. return Engine._ALPHA_SCREENMODE;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9432. get: function () {
  9433. return Engine._DELAYLOADSTATE_NONE;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9439. get: function () {
  9440. return Engine._DELAYLOADSTATE_LOADED;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9446. get: function () {
  9447. return Engine._DELAYLOADSTATE_LOADING;
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9453. get: function () {
  9454. return Engine._DELAYLOADSTATE_NOTLOADED;
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9460. get: function () {
  9461. return Engine._TEXTUREFORMAT_ALPHA;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9467. get: function () {
  9468. return Engine._TEXTUREFORMAT_LUMINANCE;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9474. get: function () {
  9475. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9476. },
  9477. enumerable: true,
  9478. configurable: true
  9479. });
  9480. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9481. get: function () {
  9482. return Engine._TEXTUREFORMAT_RGB;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9488. get: function () {
  9489. return Engine._TEXTUREFORMAT_RGBA;
  9490. },
  9491. enumerable: true,
  9492. configurable: true
  9493. });
  9494. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9495. get: function () {
  9496. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9502. get: function () {
  9503. return Engine._TEXTURETYPE_FLOAT;
  9504. },
  9505. enumerable: true,
  9506. configurable: true
  9507. });
  9508. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9509. get: function () {
  9510. return Engine._TEXTURETYPE_HALF_FLOAT;
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9516. get: function () {
  9517. return Engine._SCALEMODE_FLOOR;
  9518. },
  9519. enumerable: true,
  9520. configurable: true
  9521. });
  9522. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9523. get: function () {
  9524. return Engine._SCALEMODE_NEAREST;
  9525. },
  9526. enumerable: true,
  9527. configurable: true
  9528. });
  9529. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9530. get: function () {
  9531. return Engine._SCALEMODE_CEILING;
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(Engine, "Version", {
  9537. get: function () {
  9538. return "3.2.0-alpha2";
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9544. get: function () {
  9545. return this._vrExclusivePointerMode;
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9551. get: function () {
  9552. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9558. get: function () {
  9559. return this._webGLVersion < 2 || this.forcePOTTextures;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Object.defineProperty(Engine.prototype, "badOS", {
  9565. get: function () {
  9566. return this._badOS;
  9567. },
  9568. enumerable: true,
  9569. configurable: true
  9570. });
  9571. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9572. get: function () {
  9573. return this._badDesktopOS;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9579. get: function () {
  9580. return this._performanceMonitor;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9586. get: function () {
  9587. return this._texturesSupported;
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9593. get: function () {
  9594. return this._textureFormatInUse;
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. Object.defineProperty(Engine.prototype, "currentViewport", {
  9600. get: function () {
  9601. return this._cachedViewport;
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9607. // Empty texture
  9608. get: function () {
  9609. if (!this._emptyTexture) {
  9610. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9611. }
  9612. return this._emptyTexture;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9618. get: function () {
  9619. if (!this._emptyTexture3D) {
  9620. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9621. }
  9622. return this._emptyTexture3D;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9628. get: function () {
  9629. if (!this._emptyCubeTexture) {
  9630. var faceData = new Uint8Array(4);
  9631. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9632. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9633. }
  9634. return this._emptyCubeTexture;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Engine.prototype._rebuildInternalTextures = function () {
  9640. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9641. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9642. var internalTexture = currentState_1[_i];
  9643. internalTexture._rebuild();
  9644. }
  9645. };
  9646. Engine.prototype._rebuildEffects = function () {
  9647. for (var key in this._compiledEffects) {
  9648. var effect = this._compiledEffects[key];
  9649. effect._prepareEffect();
  9650. }
  9651. BABYLON.Effect.ResetCache();
  9652. };
  9653. Engine.prototype._rebuildBuffers = function () {
  9654. // Index / Vertex
  9655. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9656. var scene = _a[_i];
  9657. scene.resetCachedMaterial();
  9658. scene._rebuildGeometries();
  9659. scene._rebuildTextures();
  9660. }
  9661. // Uniforms
  9662. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9663. var uniformBuffer = _c[_b];
  9664. uniformBuffer._rebuild();
  9665. }
  9666. };
  9667. Engine.prototype._initGLContext = function () {
  9668. // Caps
  9669. this._caps = new EngineCapabilities();
  9670. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9671. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9672. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9673. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9674. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9675. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9676. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9677. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9678. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9679. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9680. // Infos
  9681. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9682. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9683. if (rendererInfo != null) {
  9684. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9685. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9686. }
  9687. if (!this._glVendor) {
  9688. this._glVendor = "Unknown vendor";
  9689. }
  9690. if (!this._glRenderer) {
  9691. this._glRenderer = "Unknown renderer";
  9692. }
  9693. // Constants
  9694. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9695. if (this._gl.RGBA16F !== 0x881A) {
  9696. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9697. }
  9698. if (this._gl.RGBA32F !== 0x8814) {
  9699. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9700. }
  9701. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9702. this._gl.DEPTH24_STENCIL8 = 35056;
  9703. }
  9704. // Extensions
  9705. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9706. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9707. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9708. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9709. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9710. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9711. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9712. 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');
  9713. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9714. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9715. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9716. this._caps.highPrecisionShaderSupported = true;
  9717. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9718. if (this._caps.timerQuery) {
  9719. if (this._webGLVersion === 1) {
  9720. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9721. }
  9722. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9723. }
  9724. // Checks if some of the format renders first to allow the use of webgl inspector.
  9725. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9726. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9727. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9728. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9729. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9730. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9731. if (this._webGLVersion > 1) {
  9732. this._gl.HALF_FLOAT_OES = 0x140B;
  9733. }
  9734. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9735. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9736. // Draw buffers
  9737. if (this._webGLVersion > 1) {
  9738. this._caps.drawBuffersExtension = true;
  9739. }
  9740. else {
  9741. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9742. if (drawBuffersExtension !== null) {
  9743. this._caps.drawBuffersExtension = true;
  9744. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9745. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9746. for (var i = 0; i < 16; i++) {
  9747. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9748. }
  9749. }
  9750. else {
  9751. this._caps.drawBuffersExtension = false;
  9752. }
  9753. }
  9754. // Depth Texture
  9755. if (this._webGLVersion > 1) {
  9756. this._caps.depthTextureExtension = true;
  9757. }
  9758. else {
  9759. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9760. if (depthTextureExtension != null) {
  9761. this._caps.depthTextureExtension = true;
  9762. }
  9763. }
  9764. // Vertex array object
  9765. if (this._webGLVersion > 1) {
  9766. this._caps.vertexArrayObject = true;
  9767. }
  9768. else {
  9769. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9770. if (vertexArrayObjectExtension != null) {
  9771. this._caps.vertexArrayObject = true;
  9772. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9773. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9774. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9775. }
  9776. else {
  9777. this._caps.vertexArrayObject = false;
  9778. }
  9779. }
  9780. // Instances count
  9781. if (this._webGLVersion > 1) {
  9782. this._caps.instancedArrays = true;
  9783. }
  9784. else {
  9785. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9786. if (instanceExtension != null) {
  9787. this._caps.instancedArrays = true;
  9788. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9789. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9790. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9791. }
  9792. else {
  9793. this._caps.instancedArrays = false;
  9794. }
  9795. }
  9796. // Intelligently add supported compressed formats in order to check for.
  9797. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9798. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9799. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9800. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9801. if (this._caps.astc)
  9802. this.texturesSupported.push('-astc.ktx');
  9803. if (this._caps.s3tc)
  9804. this.texturesSupported.push('-dxt.ktx');
  9805. if (this._caps.pvrtc)
  9806. this.texturesSupported.push('-pvrtc.ktx');
  9807. if (this._caps.etc2)
  9808. this.texturesSupported.push('-etc2.ktx');
  9809. if (this._caps.etc1)
  9810. this.texturesSupported.push('-etc1.ktx');
  9811. if (this._gl.getShaderPrecisionFormat) {
  9812. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9813. if (highp) {
  9814. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9815. }
  9816. }
  9817. // Depth buffer
  9818. this.setDepthBuffer(true);
  9819. this.setDepthFunctionToLessOrEqual();
  9820. this.setDepthWrite(true);
  9821. // Texture maps
  9822. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9823. this._nextFreeTextureSlots.push(slot);
  9824. }
  9825. };
  9826. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9827. get: function () {
  9828. return this._webGLVersion;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9834. /**
  9835. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9836. */
  9837. get: function () {
  9838. return this._isStencilEnable;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Engine.prototype._prepareWorkingCanvas = function () {
  9844. if (this._workingCanvas) {
  9845. return;
  9846. }
  9847. this._workingCanvas = document.createElement("canvas");
  9848. var context = this._workingCanvas.getContext("2d");
  9849. if (context) {
  9850. this._workingContext = context;
  9851. }
  9852. };
  9853. Engine.prototype.resetTextureCache = function () {
  9854. for (var key in this._boundTexturesCache) {
  9855. var boundTexture = this._boundTexturesCache[key];
  9856. if (boundTexture) {
  9857. this._removeDesignatedSlot(boundTexture);
  9858. }
  9859. this._boundTexturesCache[key] = null;
  9860. }
  9861. this._nextFreeTextureSlots = [];
  9862. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9863. this._nextFreeTextureSlots.push(slot);
  9864. }
  9865. this._activeChannel = -1;
  9866. };
  9867. Engine.prototype.isDeterministicLockStep = function () {
  9868. return this._deterministicLockstep;
  9869. };
  9870. Engine.prototype.getLockstepMaxSteps = function () {
  9871. return this._lockstepMaxSteps;
  9872. };
  9873. Engine.prototype.getGlInfo = function () {
  9874. return {
  9875. vendor: this._glVendor,
  9876. renderer: this._glRenderer,
  9877. version: this._glVersion
  9878. };
  9879. };
  9880. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9881. if (useScreen === void 0) { useScreen = false; }
  9882. var viewport = camera.viewport;
  9883. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9884. };
  9885. Engine.prototype.getRenderWidth = function (useScreen) {
  9886. if (useScreen === void 0) { useScreen = false; }
  9887. if (!useScreen && this._currentRenderTarget) {
  9888. return this._currentRenderTarget.width;
  9889. }
  9890. return this._gl.drawingBufferWidth;
  9891. };
  9892. Engine.prototype.getRenderHeight = function (useScreen) {
  9893. if (useScreen === void 0) { useScreen = false; }
  9894. if (!useScreen && this._currentRenderTarget) {
  9895. return this._currentRenderTarget.height;
  9896. }
  9897. return this._gl.drawingBufferHeight;
  9898. };
  9899. Engine.prototype.getRenderingCanvas = function () {
  9900. return this._renderingCanvas;
  9901. };
  9902. Engine.prototype.getRenderingCanvasClientRect = function () {
  9903. if (!this._renderingCanvas) {
  9904. return null;
  9905. }
  9906. return this._renderingCanvas.getBoundingClientRect();
  9907. };
  9908. Engine.prototype.setHardwareScalingLevel = function (level) {
  9909. this._hardwareScalingLevel = level;
  9910. this.resize();
  9911. };
  9912. Engine.prototype.getHardwareScalingLevel = function () {
  9913. return this._hardwareScalingLevel;
  9914. };
  9915. Engine.prototype.getLoadedTexturesCache = function () {
  9916. return this._internalTexturesCache;
  9917. };
  9918. Engine.prototype.getCaps = function () {
  9919. return this._caps;
  9920. };
  9921. Object.defineProperty(Engine.prototype, "drawCalls", {
  9922. /** The number of draw calls submitted last frame */
  9923. get: function () {
  9924. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9925. return 0;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9931. get: function () {
  9932. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9933. return null;
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Engine.prototype.getDepthFunction = function () {
  9939. return this._depthCullingState.depthFunc;
  9940. };
  9941. Engine.prototype.setDepthFunction = function (depthFunc) {
  9942. this._depthCullingState.depthFunc = depthFunc;
  9943. };
  9944. Engine.prototype.setDepthFunctionToGreater = function () {
  9945. this._depthCullingState.depthFunc = this._gl.GREATER;
  9946. };
  9947. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9948. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9949. };
  9950. Engine.prototype.setDepthFunctionToLess = function () {
  9951. this._depthCullingState.depthFunc = this._gl.LESS;
  9952. };
  9953. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9954. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9955. };
  9956. Engine.prototype.getStencilBuffer = function () {
  9957. return this._stencilState.stencilTest;
  9958. };
  9959. Engine.prototype.setStencilBuffer = function (enable) {
  9960. this._stencilState.stencilTest = enable;
  9961. };
  9962. Engine.prototype.getStencilMask = function () {
  9963. return this._stencilState.stencilMask;
  9964. };
  9965. Engine.prototype.setStencilMask = function (mask) {
  9966. this._stencilState.stencilMask = mask;
  9967. };
  9968. Engine.prototype.getStencilFunction = function () {
  9969. return this._stencilState.stencilFunc;
  9970. };
  9971. Engine.prototype.getStencilFunctionReference = function () {
  9972. return this._stencilState.stencilFuncRef;
  9973. };
  9974. Engine.prototype.getStencilFunctionMask = function () {
  9975. return this._stencilState.stencilFuncMask;
  9976. };
  9977. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9978. this._stencilState.stencilFunc = stencilFunc;
  9979. };
  9980. Engine.prototype.setStencilFunctionReference = function (reference) {
  9981. this._stencilState.stencilFuncRef = reference;
  9982. };
  9983. Engine.prototype.setStencilFunctionMask = function (mask) {
  9984. this._stencilState.stencilFuncMask = mask;
  9985. };
  9986. Engine.prototype.getStencilOperationFail = function () {
  9987. return this._stencilState.stencilOpStencilFail;
  9988. };
  9989. Engine.prototype.getStencilOperationDepthFail = function () {
  9990. return this._stencilState.stencilOpDepthFail;
  9991. };
  9992. Engine.prototype.getStencilOperationPass = function () {
  9993. return this._stencilState.stencilOpStencilDepthPass;
  9994. };
  9995. Engine.prototype.setStencilOperationFail = function (operation) {
  9996. this._stencilState.stencilOpStencilFail = operation;
  9997. };
  9998. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9999. this._stencilState.stencilOpDepthFail = operation;
  10000. };
  10001. Engine.prototype.setStencilOperationPass = function (operation) {
  10002. this._stencilState.stencilOpStencilDepthPass = operation;
  10003. };
  10004. Engine.prototype.setDitheringState = function (value) {
  10005. if (value) {
  10006. this._gl.enable(this._gl.DITHER);
  10007. }
  10008. else {
  10009. this._gl.disable(this._gl.DITHER);
  10010. }
  10011. };
  10012. Engine.prototype.setRasterizerState = function (value) {
  10013. if (value) {
  10014. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10015. }
  10016. else {
  10017. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10018. }
  10019. };
  10020. /**
  10021. * stop executing a render loop function and remove it from the execution array
  10022. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10023. */
  10024. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10025. if (!renderFunction) {
  10026. this._activeRenderLoops = [];
  10027. return;
  10028. }
  10029. var index = this._activeRenderLoops.indexOf(renderFunction);
  10030. if (index >= 0) {
  10031. this._activeRenderLoops.splice(index, 1);
  10032. }
  10033. };
  10034. Engine.prototype._renderLoop = function () {
  10035. if (!this._contextWasLost) {
  10036. var shouldRender = true;
  10037. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10038. shouldRender = false;
  10039. }
  10040. if (shouldRender) {
  10041. // Start new frame
  10042. this.beginFrame();
  10043. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10044. var renderFunction = this._activeRenderLoops[index];
  10045. renderFunction();
  10046. }
  10047. // Present
  10048. this.endFrame();
  10049. }
  10050. }
  10051. if (this._activeRenderLoops.length > 0) {
  10052. // Register new frame
  10053. var requester = null;
  10054. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10055. requester = this._vrDisplay;
  10056. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10057. }
  10058. else {
  10059. this._renderingQueueLaunched = false;
  10060. }
  10061. };
  10062. /**
  10063. * Register and execute a render loop. The engine can have more than one render function.
  10064. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10065. * @example
  10066. * engine.runRenderLoop(function () {
  10067. * scene.render()
  10068. * })
  10069. */
  10070. Engine.prototype.runRenderLoop = function (renderFunction) {
  10071. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10072. return;
  10073. }
  10074. this._activeRenderLoops.push(renderFunction);
  10075. if (!this._renderingQueueLaunched) {
  10076. this._renderingQueueLaunched = true;
  10077. this._bindedRenderFunction = this._renderLoop.bind(this);
  10078. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10079. }
  10080. };
  10081. /**
  10082. * Toggle full screen mode.
  10083. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10084. * @param {any} options - an options object to be sent to the requestFullscreen function
  10085. */
  10086. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10087. if (this.isFullscreen) {
  10088. BABYLON.Tools.ExitFullscreen();
  10089. }
  10090. else {
  10091. this._pointerLockRequested = requestPointerLock;
  10092. if (this._renderingCanvas) {
  10093. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10094. }
  10095. }
  10096. };
  10097. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10098. if (stencil === void 0) { stencil = false; }
  10099. this.applyStates();
  10100. var mode = 0;
  10101. if (backBuffer && color) {
  10102. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10103. mode |= this._gl.COLOR_BUFFER_BIT;
  10104. }
  10105. if (depth) {
  10106. this._gl.clearDepth(1.0);
  10107. mode |= this._gl.DEPTH_BUFFER_BIT;
  10108. }
  10109. if (stencil) {
  10110. this._gl.clearStencil(0);
  10111. mode |= this._gl.STENCIL_BUFFER_BIT;
  10112. }
  10113. this._gl.clear(mode);
  10114. };
  10115. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10116. var gl = this._gl;
  10117. // Save state
  10118. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10119. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10120. // Change state
  10121. gl.enable(gl.SCISSOR_TEST);
  10122. gl.scissor(x, y, width, height);
  10123. // Clear
  10124. this.clear(clearColor, true, true, true);
  10125. // Restore state
  10126. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10127. if (curScissor === true) {
  10128. gl.enable(gl.SCISSOR_TEST);
  10129. }
  10130. else {
  10131. gl.disable(gl.SCISSOR_TEST);
  10132. }
  10133. };
  10134. /**
  10135. * Set the WebGL's viewport
  10136. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10137. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10138. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10139. */
  10140. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10141. var width = requiredWidth || this.getRenderWidth();
  10142. var height = requiredHeight || this.getRenderHeight();
  10143. var x = viewport.x || 0;
  10144. var y = viewport.y || 0;
  10145. this._cachedViewport = viewport;
  10146. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10147. };
  10148. /**
  10149. * Directly set the WebGL Viewport
  10150. * The x, y, width & height are directly passed to the WebGL call
  10151. * @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.
  10152. */
  10153. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10154. var currentViewport = this._cachedViewport;
  10155. this._cachedViewport = null;
  10156. this._gl.viewport(x, y, width, height);
  10157. return currentViewport;
  10158. };
  10159. Engine.prototype.beginFrame = function () {
  10160. this.onBeginFrameObservable.notifyObservers(this);
  10161. this._measureFps();
  10162. };
  10163. Engine.prototype.endFrame = function () {
  10164. //force a flush in case we are using a bad OS.
  10165. if (this._badOS) {
  10166. this.flushFramebuffer();
  10167. }
  10168. //submit frame to the vr device, if enabled
  10169. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10170. // TODO: We should only submit the frame if we read frameData successfully.
  10171. this._vrDisplay.submitFrame();
  10172. }
  10173. this.onEndFrameObservable.notifyObservers(this);
  10174. };
  10175. /**
  10176. * resize the view according to the canvas' size.
  10177. * @example
  10178. * window.addEventListener("resize", function () {
  10179. * engine.resize();
  10180. * });
  10181. */
  10182. Engine.prototype.resize = function () {
  10183. // We're not resizing the size of the canvas while in VR mode & presenting
  10184. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10185. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10186. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10187. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10188. }
  10189. };
  10190. /**
  10191. * force a specific size of the canvas
  10192. * @param {number} width - the new canvas' width
  10193. * @param {number} height - the new canvas' height
  10194. */
  10195. Engine.prototype.setSize = function (width, height) {
  10196. if (!this._renderingCanvas) {
  10197. return;
  10198. }
  10199. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10200. return;
  10201. }
  10202. this._renderingCanvas.width = width;
  10203. this._renderingCanvas.height = height;
  10204. for (var index = 0; index < this.scenes.length; index++) {
  10205. var scene = this.scenes[index];
  10206. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10207. var cam = scene.cameras[camIndex];
  10208. cam._currentRenderId = 0;
  10209. }
  10210. }
  10211. if (this.onResizeObservable.hasObservers) {
  10212. this.onResizeObservable.notifyObservers(this);
  10213. }
  10214. };
  10215. // WebVR functions
  10216. Engine.prototype.isVRDevicePresent = function () {
  10217. return !!this._vrDisplay;
  10218. };
  10219. Engine.prototype.getVRDevice = function () {
  10220. return this._vrDisplay;
  10221. };
  10222. Engine.prototype.initWebVR = function () {
  10223. var _this = this;
  10224. var notifyObservers = function () {
  10225. var eventArgs = {
  10226. vrDisplay: _this._vrDisplay,
  10227. vrSupported: _this._vrSupported
  10228. };
  10229. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10230. };
  10231. if (!this._onVrDisplayConnect) {
  10232. this._onVrDisplayConnect = function (event) {
  10233. _this._vrDisplay = event.display;
  10234. notifyObservers();
  10235. };
  10236. this._onVrDisplayDisconnect = function () {
  10237. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10238. _this._vrDisplay = undefined;
  10239. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10240. notifyObservers();
  10241. };
  10242. this._onVrDisplayPresentChange = function () {
  10243. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10244. };
  10245. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10246. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10247. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10248. }
  10249. this._getVRDisplays(notifyObservers);
  10250. return this.onVRDisplayChangedObservable;
  10251. };
  10252. Engine.prototype.enableVR = function () {
  10253. var _this = this;
  10254. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10255. var onResolved = function () {
  10256. _this.onVRRequestPresentComplete.notifyObservers(true);
  10257. _this._onVRFullScreenTriggered();
  10258. };
  10259. var onRejected = function () {
  10260. _this.onVRRequestPresentComplete.notifyObservers(false);
  10261. };
  10262. this.onVRRequestPresentStart.notifyObservers(this);
  10263. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10264. }
  10265. };
  10266. Engine.prototype.disableVR = function () {
  10267. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10268. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10269. }
  10270. };
  10271. Engine.prototype._getVRDisplays = function (callback) {
  10272. var _this = this;
  10273. var getWebVRDevices = function (devices) {
  10274. _this._vrSupported = true;
  10275. // note that devices may actually be an empty array. This is fine;
  10276. // we expect this._vrDisplay to be undefined in this case.
  10277. return _this._vrDisplay = devices[0];
  10278. };
  10279. if (navigator.getVRDisplays) {
  10280. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10281. // TODO: System CANNOT support WebVR, despite API presence.
  10282. _this._vrSupported = false;
  10283. callback();
  10284. });
  10285. }
  10286. else {
  10287. // TODO: Browser does not support WebVR
  10288. this._vrDisplay = undefined;
  10289. this._vrSupported = false;
  10290. callback();
  10291. }
  10292. };
  10293. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10294. if (this._currentRenderTarget) {
  10295. this.unBindFramebuffer(this._currentRenderTarget);
  10296. }
  10297. this._currentRenderTarget = texture;
  10298. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10299. var gl = this._gl;
  10300. if (texture.isCube) {
  10301. if (faceIndex === undefined) {
  10302. faceIndex = 0;
  10303. }
  10304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10305. }
  10306. if (this._cachedViewport && !forceFullscreenViewport) {
  10307. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10308. }
  10309. else {
  10310. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10311. }
  10312. this.wipeCaches();
  10313. };
  10314. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10315. if (this._currentFramebuffer !== framebuffer) {
  10316. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10317. this._currentFramebuffer = framebuffer;
  10318. }
  10319. };
  10320. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10321. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10322. this._currentRenderTarget = null;
  10323. // If MSAA, we need to bitblt back to main texture
  10324. var gl = this._gl;
  10325. if (texture._MSAAFramebuffer) {
  10326. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10327. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10328. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10329. }
  10330. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10331. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10332. gl.generateMipmap(gl.TEXTURE_2D);
  10333. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10334. }
  10335. if (onBeforeUnbind) {
  10336. if (texture._MSAAFramebuffer) {
  10337. // Bind the correct framebuffer
  10338. this.bindUnboundFramebuffer(texture._framebuffer);
  10339. }
  10340. onBeforeUnbind();
  10341. }
  10342. this.bindUnboundFramebuffer(null);
  10343. };
  10344. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10345. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10346. this._currentRenderTarget = null;
  10347. // If MSAA, we need to bitblt back to main texture
  10348. var gl = this._gl;
  10349. if (textures[0]._MSAAFramebuffer) {
  10350. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10351. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10352. var attachments = textures[0]._attachments;
  10353. if (!attachments) {
  10354. attachments = new Array(textures.length);
  10355. textures[0]._attachments = attachments;
  10356. }
  10357. for (var i = 0; i < textures.length; i++) {
  10358. var texture = textures[i];
  10359. for (var j = 0; j < attachments.length; j++) {
  10360. attachments[j] = gl.NONE;
  10361. }
  10362. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10363. gl.readBuffer(attachments[i]);
  10364. gl.drawBuffers(attachments);
  10365. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10366. }
  10367. for (var i = 0; i < attachments.length; i++) {
  10368. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10369. }
  10370. gl.drawBuffers(attachments);
  10371. }
  10372. for (var i = 0; i < textures.length; i++) {
  10373. var texture = textures[i];
  10374. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10375. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10376. gl.generateMipmap(gl.TEXTURE_2D);
  10377. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10378. }
  10379. }
  10380. if (onBeforeUnbind) {
  10381. if (textures[0]._MSAAFramebuffer) {
  10382. // Bind the correct framebuffer
  10383. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10384. }
  10385. onBeforeUnbind();
  10386. }
  10387. this.bindUnboundFramebuffer(null);
  10388. };
  10389. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10390. if (texture.generateMipMaps) {
  10391. var gl = this._gl;
  10392. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10393. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10394. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10395. }
  10396. };
  10397. Engine.prototype.flushFramebuffer = function () {
  10398. this._gl.flush();
  10399. };
  10400. Engine.prototype.restoreDefaultFramebuffer = function () {
  10401. if (this._currentRenderTarget) {
  10402. this.unBindFramebuffer(this._currentRenderTarget);
  10403. }
  10404. else {
  10405. this.bindUnboundFramebuffer(null);
  10406. }
  10407. if (this._cachedViewport) {
  10408. this.setViewport(this._cachedViewport);
  10409. }
  10410. this.wipeCaches();
  10411. };
  10412. // UBOs
  10413. Engine.prototype.createUniformBuffer = function (elements) {
  10414. var ubo = this._gl.createBuffer();
  10415. if (!ubo) {
  10416. throw new Error("Unable to create uniform buffer");
  10417. }
  10418. this.bindUniformBuffer(ubo);
  10419. if (elements instanceof Float32Array) {
  10420. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10421. }
  10422. else {
  10423. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10424. }
  10425. this.bindUniformBuffer(null);
  10426. ubo.references = 1;
  10427. return ubo;
  10428. };
  10429. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10430. var ubo = this._gl.createBuffer();
  10431. if (!ubo) {
  10432. throw new Error("Unable to create dynamic uniform buffer");
  10433. }
  10434. this.bindUniformBuffer(ubo);
  10435. if (elements instanceof Float32Array) {
  10436. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10437. }
  10438. else {
  10439. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10440. }
  10441. this.bindUniformBuffer(null);
  10442. ubo.references = 1;
  10443. return ubo;
  10444. };
  10445. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10446. this.bindUniformBuffer(uniformBuffer);
  10447. if (offset === undefined) {
  10448. offset = 0;
  10449. }
  10450. if (count === undefined) {
  10451. if (elements instanceof Float32Array) {
  10452. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10453. }
  10454. else {
  10455. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10456. }
  10457. }
  10458. else {
  10459. if (elements instanceof Float32Array) {
  10460. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10461. }
  10462. else {
  10463. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10464. }
  10465. }
  10466. this.bindUniformBuffer(null);
  10467. };
  10468. // VBOs
  10469. Engine.prototype._resetVertexBufferBinding = function () {
  10470. this.bindArrayBuffer(null);
  10471. this._cachedVertexBuffers = null;
  10472. };
  10473. Engine.prototype.createVertexBuffer = function (vertices) {
  10474. var vbo = this._gl.createBuffer();
  10475. if (!vbo) {
  10476. throw new Error("Unable to create vertex buffer");
  10477. }
  10478. this.bindArrayBuffer(vbo);
  10479. if (vertices instanceof Float32Array) {
  10480. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10481. }
  10482. else {
  10483. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10484. }
  10485. this._resetVertexBufferBinding();
  10486. vbo.references = 1;
  10487. return vbo;
  10488. };
  10489. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10490. var vbo = this._gl.createBuffer();
  10491. if (!vbo) {
  10492. throw new Error("Unable to create dynamic vertex buffer");
  10493. }
  10494. this.bindArrayBuffer(vbo);
  10495. if (vertices instanceof Float32Array) {
  10496. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10497. }
  10498. else {
  10499. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10500. }
  10501. this._resetVertexBufferBinding();
  10502. vbo.references = 1;
  10503. return vbo;
  10504. };
  10505. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10506. if (offset === void 0) { offset = 0; }
  10507. // Force cache update
  10508. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10509. this.bindIndexBuffer(indexBuffer);
  10510. var arrayBuffer;
  10511. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10512. arrayBuffer = indices;
  10513. }
  10514. else {
  10515. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10516. }
  10517. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10518. this._resetIndexBufferBinding();
  10519. };
  10520. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10521. this.bindArrayBuffer(vertexBuffer);
  10522. if (offset === undefined) {
  10523. offset = 0;
  10524. }
  10525. if (count === undefined) {
  10526. if (vertices instanceof Float32Array) {
  10527. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10528. }
  10529. else {
  10530. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10531. }
  10532. }
  10533. else {
  10534. if (vertices instanceof Float32Array) {
  10535. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10536. }
  10537. else {
  10538. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10539. }
  10540. }
  10541. this._resetVertexBufferBinding();
  10542. };
  10543. Engine.prototype._resetIndexBufferBinding = function () {
  10544. this.bindIndexBuffer(null);
  10545. this._cachedIndexBuffer = null;
  10546. };
  10547. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10548. var vbo = this._gl.createBuffer();
  10549. if (!vbo) {
  10550. throw new Error("Unable to create index buffer");
  10551. }
  10552. this.bindIndexBuffer(vbo);
  10553. // Check for 32 bits indices
  10554. var arrayBuffer;
  10555. var need32Bits = false;
  10556. if (indices instanceof Uint16Array) {
  10557. arrayBuffer = indices;
  10558. }
  10559. else {
  10560. //check 32 bit support
  10561. if (this._caps.uintIndices) {
  10562. if (indices instanceof Uint32Array) {
  10563. arrayBuffer = indices;
  10564. need32Bits = true;
  10565. }
  10566. else {
  10567. //number[] or Int32Array, check if 32 bit is necessary
  10568. for (var index = 0; index < indices.length; index++) {
  10569. if (indices[index] > 65535) {
  10570. need32Bits = true;
  10571. break;
  10572. }
  10573. }
  10574. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10575. }
  10576. }
  10577. else {
  10578. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10579. arrayBuffer = new Uint16Array(indices);
  10580. }
  10581. }
  10582. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10583. this._resetIndexBufferBinding();
  10584. vbo.references = 1;
  10585. vbo.is32Bits = need32Bits;
  10586. return vbo;
  10587. };
  10588. Engine.prototype.bindArrayBuffer = function (buffer) {
  10589. if (!this._vaoRecordInProgress) {
  10590. this._unbindVertexArrayObject();
  10591. }
  10592. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10593. };
  10594. Engine.prototype.bindUniformBuffer = function (buffer) {
  10595. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10596. };
  10597. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10598. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10599. };
  10600. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10601. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10602. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10603. };
  10604. ;
  10605. Engine.prototype.bindIndexBuffer = function (buffer) {
  10606. if (!this._vaoRecordInProgress) {
  10607. this._unbindVertexArrayObject();
  10608. }
  10609. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10610. };
  10611. Engine.prototype.bindBuffer = function (buffer, target) {
  10612. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10613. this._gl.bindBuffer(target, buffer);
  10614. this._currentBoundBuffer[target] = buffer;
  10615. }
  10616. };
  10617. Engine.prototype.updateArrayBuffer = function (data) {
  10618. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10619. };
  10620. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10621. var pointer = this._currentBufferPointers[indx];
  10622. var changed = false;
  10623. if (!pointer.active) {
  10624. changed = true;
  10625. pointer.active = true;
  10626. pointer.index = indx;
  10627. pointer.size = size;
  10628. pointer.type = type;
  10629. pointer.normalized = normalized;
  10630. pointer.stride = stride;
  10631. pointer.offset = offset;
  10632. pointer.buffer = buffer;
  10633. }
  10634. else {
  10635. if (pointer.buffer !== buffer) {
  10636. pointer.buffer = buffer;
  10637. changed = true;
  10638. }
  10639. if (pointer.size !== size) {
  10640. pointer.size = size;
  10641. changed = true;
  10642. }
  10643. if (pointer.type !== type) {
  10644. pointer.type = type;
  10645. changed = true;
  10646. }
  10647. if (pointer.normalized !== normalized) {
  10648. pointer.normalized = normalized;
  10649. changed = true;
  10650. }
  10651. if (pointer.stride !== stride) {
  10652. pointer.stride = stride;
  10653. changed = true;
  10654. }
  10655. if (pointer.offset !== offset) {
  10656. pointer.offset = offset;
  10657. changed = true;
  10658. }
  10659. }
  10660. if (changed || this._vaoRecordInProgress) {
  10661. this.bindArrayBuffer(buffer);
  10662. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10663. }
  10664. };
  10665. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10666. if (indexBuffer == null) {
  10667. return;
  10668. }
  10669. if (this._cachedIndexBuffer !== indexBuffer) {
  10670. this._cachedIndexBuffer = indexBuffer;
  10671. this.bindIndexBuffer(indexBuffer);
  10672. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10673. }
  10674. };
  10675. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10676. var attributes = effect.getAttributesNames();
  10677. if (!this._vaoRecordInProgress) {
  10678. this._unbindVertexArrayObject();
  10679. }
  10680. this.unbindAllAttributes();
  10681. for (var index = 0; index < attributes.length; index++) {
  10682. var order = effect.getAttributeLocation(index);
  10683. if (order >= 0) {
  10684. var vertexBuffer = vertexBuffers[attributes[index]];
  10685. if (!vertexBuffer) {
  10686. continue;
  10687. }
  10688. this._gl.enableVertexAttribArray(order);
  10689. if (!this._vaoRecordInProgress) {
  10690. this._vertexAttribArraysEnabled[order] = true;
  10691. }
  10692. var buffer = vertexBuffer.getBuffer();
  10693. if (buffer) {
  10694. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10695. if (vertexBuffer.getIsInstanced()) {
  10696. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10697. if (!this._vaoRecordInProgress) {
  10698. this._currentInstanceLocations.push(order);
  10699. this._currentInstanceBuffers.push(buffer);
  10700. }
  10701. }
  10702. }
  10703. }
  10704. }
  10705. };
  10706. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10707. var vao = this._gl.createVertexArray();
  10708. this._vaoRecordInProgress = true;
  10709. this._gl.bindVertexArray(vao);
  10710. this._mustWipeVertexAttributes = true;
  10711. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10712. this.bindIndexBuffer(indexBuffer);
  10713. this._vaoRecordInProgress = false;
  10714. this._gl.bindVertexArray(null);
  10715. return vao;
  10716. };
  10717. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10718. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10719. this._cachedVertexArrayObject = vertexArrayObject;
  10720. this._gl.bindVertexArray(vertexArrayObject);
  10721. this._cachedVertexBuffers = null;
  10722. this._cachedIndexBuffer = null;
  10723. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10724. this._mustWipeVertexAttributes = true;
  10725. }
  10726. };
  10727. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10728. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10729. this._cachedVertexBuffers = vertexBuffer;
  10730. this._cachedEffectForVertexBuffers = effect;
  10731. var attributesCount = effect.getAttributesCount();
  10732. this._unbindVertexArrayObject();
  10733. this.unbindAllAttributes();
  10734. var offset = 0;
  10735. for (var index = 0; index < attributesCount; index++) {
  10736. if (index < vertexDeclaration.length) {
  10737. var order = effect.getAttributeLocation(index);
  10738. if (order >= 0) {
  10739. this._gl.enableVertexAttribArray(order);
  10740. this._vertexAttribArraysEnabled[order] = true;
  10741. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10742. }
  10743. offset += vertexDeclaration[index] * 4;
  10744. }
  10745. }
  10746. }
  10747. this._bindIndexBufferWithCache(indexBuffer);
  10748. };
  10749. Engine.prototype._unbindVertexArrayObject = function () {
  10750. if (!this._cachedVertexArrayObject) {
  10751. return;
  10752. }
  10753. this._cachedVertexArrayObject = null;
  10754. this._gl.bindVertexArray(null);
  10755. };
  10756. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10757. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10758. this._cachedVertexBuffers = vertexBuffers;
  10759. this._cachedEffectForVertexBuffers = effect;
  10760. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10761. }
  10762. this._bindIndexBufferWithCache(indexBuffer);
  10763. };
  10764. Engine.prototype.unbindInstanceAttributes = function () {
  10765. var boundBuffer;
  10766. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10767. var instancesBuffer = this._currentInstanceBuffers[i];
  10768. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10769. boundBuffer = instancesBuffer;
  10770. this.bindArrayBuffer(instancesBuffer);
  10771. }
  10772. var offsetLocation = this._currentInstanceLocations[i];
  10773. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10774. }
  10775. this._currentInstanceBuffers.length = 0;
  10776. this._currentInstanceLocations.length = 0;
  10777. };
  10778. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10779. this._gl.deleteVertexArray(vao);
  10780. };
  10781. Engine.prototype._releaseBuffer = function (buffer) {
  10782. buffer.references--;
  10783. if (buffer.references === 0) {
  10784. this._gl.deleteBuffer(buffer);
  10785. return true;
  10786. }
  10787. return false;
  10788. };
  10789. Engine.prototype.createInstancesBuffer = function (capacity) {
  10790. var buffer = this._gl.createBuffer();
  10791. if (!buffer) {
  10792. throw new Error("Unable to create instance buffer");
  10793. }
  10794. buffer.capacity = capacity;
  10795. this.bindArrayBuffer(buffer);
  10796. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10797. return buffer;
  10798. };
  10799. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10800. this._gl.deleteBuffer(buffer);
  10801. };
  10802. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10803. this.bindArrayBuffer(instancesBuffer);
  10804. if (data) {
  10805. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10806. }
  10807. if (offsetLocations[0].index !== undefined) {
  10808. var stride = 0;
  10809. for (var i = 0; i < offsetLocations.length; i++) {
  10810. var ai = offsetLocations[i];
  10811. stride += ai.attributeSize * 4;
  10812. }
  10813. for (var i = 0; i < offsetLocations.length; i++) {
  10814. var ai = offsetLocations[i];
  10815. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10816. this._gl.enableVertexAttribArray(ai.index);
  10817. this._vertexAttribArraysEnabled[ai.index] = true;
  10818. }
  10819. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10820. this._gl.vertexAttribDivisor(ai.index, 1);
  10821. this._currentInstanceLocations.push(ai.index);
  10822. this._currentInstanceBuffers.push(instancesBuffer);
  10823. }
  10824. }
  10825. else {
  10826. for (var index = 0; index < 4; index++) {
  10827. var offsetLocation = offsetLocations[index];
  10828. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10829. this._gl.enableVertexAttribArray(offsetLocation);
  10830. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10831. }
  10832. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10833. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10834. this._currentInstanceLocations.push(offsetLocation);
  10835. this._currentInstanceBuffers.push(instancesBuffer);
  10836. }
  10837. }
  10838. };
  10839. Engine.prototype.applyStates = function () {
  10840. this._depthCullingState.apply(this._gl);
  10841. this._stencilState.apply(this._gl);
  10842. this._alphaState.apply(this._gl);
  10843. };
  10844. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10845. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10846. };
  10847. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10848. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10849. };
  10850. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10851. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10852. };
  10853. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10854. // Apply states
  10855. this.applyStates();
  10856. this._drawCalls.addCount(1, false);
  10857. // Render
  10858. var drawMode = this.DrawMode(fillMode);
  10859. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10860. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10861. if (instancesCount) {
  10862. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10863. }
  10864. else {
  10865. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10866. }
  10867. };
  10868. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10869. // Apply states
  10870. this.applyStates();
  10871. this._drawCalls.addCount(1, false);
  10872. var drawMode = this.DrawMode(fillMode);
  10873. if (instancesCount) {
  10874. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10875. }
  10876. else {
  10877. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10878. }
  10879. };
  10880. Engine.prototype.DrawMode = function (fillMode) {
  10881. switch (fillMode) {
  10882. // Triangle views
  10883. case BABYLON.Material.TriangleFillMode:
  10884. return this._gl.TRIANGLES;
  10885. case BABYLON.Material.PointFillMode:
  10886. return this._gl.POINTS;
  10887. case BABYLON.Material.WireFrameFillMode:
  10888. return this._gl.LINES;
  10889. // Draw modes
  10890. case BABYLON.Material.PointListDrawMode:
  10891. return this._gl.POINTS;
  10892. case BABYLON.Material.LineListDrawMode:
  10893. return this._gl.LINES;
  10894. case BABYLON.Material.LineLoopDrawMode:
  10895. return this._gl.LINE_LOOP;
  10896. case BABYLON.Material.LineStripDrawMode:
  10897. return this._gl.LINE_STRIP;
  10898. case BABYLON.Material.TriangleStripDrawMode:
  10899. return this._gl.TRIANGLE_STRIP;
  10900. case BABYLON.Material.TriangleFanDrawMode:
  10901. return this._gl.TRIANGLE_FAN;
  10902. default:
  10903. return this._gl.TRIANGLES;
  10904. }
  10905. };
  10906. // Shaders
  10907. Engine.prototype._releaseEffect = function (effect) {
  10908. if (this._compiledEffects[effect._key]) {
  10909. delete this._compiledEffects[effect._key];
  10910. this._deleteProgram(effect.getProgram());
  10911. }
  10912. };
  10913. Engine.prototype._deleteProgram = function (program) {
  10914. if (program) {
  10915. program.__SPECTOR_rebuildProgram = null;
  10916. if (program.transformFeedback) {
  10917. this.deleteTransformFeedback(program.transformFeedback);
  10918. program.transformFeedback = null;
  10919. }
  10920. this._gl.deleteProgram(program);
  10921. }
  10922. };
  10923. /**
  10924. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10925. * @param samplers An array of string used to represent textures
  10926. */
  10927. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10928. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10929. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10930. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10931. if (this._compiledEffects[name]) {
  10932. var compiledEffect = this._compiledEffects[name];
  10933. if (onCompiled && compiledEffect.isReady()) {
  10934. onCompiled(compiledEffect);
  10935. }
  10936. return compiledEffect;
  10937. }
  10938. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10939. effect._key = name;
  10940. this._compiledEffects[name] = effect;
  10941. return effect;
  10942. };
  10943. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10944. if (uniformsNames === void 0) { uniformsNames = []; }
  10945. if (samplers === void 0) { samplers = []; }
  10946. if (defines === void 0) { defines = ""; }
  10947. return this.createEffect({
  10948. vertex: "particles",
  10949. fragmentElement: fragmentName
  10950. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10951. };
  10952. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10953. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10954. context = context || this._gl;
  10955. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10956. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10957. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10958. };
  10959. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10960. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10961. context = context || this._gl;
  10962. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10963. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10964. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10965. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10966. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10967. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10968. return program;
  10969. };
  10970. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10971. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10972. var shaderProgram = context.createProgram();
  10973. if (!shaderProgram) {
  10974. throw new Error("Unable to create program");
  10975. }
  10976. context.attachShader(shaderProgram, vertexShader);
  10977. context.attachShader(shaderProgram, fragmentShader);
  10978. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10979. var transformFeedback = this.createTransformFeedback();
  10980. this.bindTransformFeedback(transformFeedback);
  10981. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10982. shaderProgram.transformFeedback = transformFeedback;
  10983. }
  10984. context.linkProgram(shaderProgram);
  10985. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10986. this.bindTransformFeedback(null);
  10987. }
  10988. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10989. if (!linked) {
  10990. context.validateProgram(shaderProgram);
  10991. var error = context.getProgramInfoLog(shaderProgram);
  10992. if (error) {
  10993. throw new Error(error);
  10994. }
  10995. }
  10996. context.deleteShader(vertexShader);
  10997. context.deleteShader(fragmentShader);
  10998. return shaderProgram;
  10999. };
  11000. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11001. var results = new Array();
  11002. for (var index = 0; index < uniformsNames.length; index++) {
  11003. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11004. }
  11005. return results;
  11006. };
  11007. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11008. var results = [];
  11009. for (var index = 0; index < attributesNames.length; index++) {
  11010. try {
  11011. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11012. }
  11013. catch (e) {
  11014. results.push(-1);
  11015. }
  11016. }
  11017. return results;
  11018. };
  11019. Engine.prototype.enableEffect = function (effect) {
  11020. if (!effect) {
  11021. return;
  11022. }
  11023. // Use program
  11024. this.bindSamplers(effect);
  11025. this._currentEffect = effect;
  11026. if (effect.onBind) {
  11027. effect.onBind(effect);
  11028. }
  11029. effect.onBindObservable.notifyObservers(effect);
  11030. };
  11031. Engine.prototype.setIntArray = function (uniform, array) {
  11032. if (!uniform)
  11033. return;
  11034. this._gl.uniform1iv(uniform, array);
  11035. };
  11036. Engine.prototype.setIntArray2 = function (uniform, array) {
  11037. if (!uniform || array.length % 2 !== 0)
  11038. return;
  11039. this._gl.uniform2iv(uniform, array);
  11040. };
  11041. Engine.prototype.setIntArray3 = function (uniform, array) {
  11042. if (!uniform || array.length % 3 !== 0)
  11043. return;
  11044. this._gl.uniform3iv(uniform, array);
  11045. };
  11046. Engine.prototype.setIntArray4 = function (uniform, array) {
  11047. if (!uniform || array.length % 4 !== 0)
  11048. return;
  11049. this._gl.uniform4iv(uniform, array);
  11050. };
  11051. Engine.prototype.setFloatArray = function (uniform, array) {
  11052. if (!uniform)
  11053. return;
  11054. this._gl.uniform1fv(uniform, array);
  11055. };
  11056. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11057. if (!uniform || array.length % 2 !== 0)
  11058. return;
  11059. this._gl.uniform2fv(uniform, array);
  11060. };
  11061. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11062. if (!uniform || array.length % 3 !== 0)
  11063. return;
  11064. this._gl.uniform3fv(uniform, array);
  11065. };
  11066. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11067. if (!uniform || array.length % 4 !== 0)
  11068. return;
  11069. this._gl.uniform4fv(uniform, array);
  11070. };
  11071. Engine.prototype.setArray = function (uniform, array) {
  11072. if (!uniform)
  11073. return;
  11074. this._gl.uniform1fv(uniform, array);
  11075. };
  11076. Engine.prototype.setArray2 = function (uniform, array) {
  11077. if (!uniform || array.length % 2 !== 0)
  11078. return;
  11079. this._gl.uniform2fv(uniform, array);
  11080. };
  11081. Engine.prototype.setArray3 = function (uniform, array) {
  11082. if (!uniform || array.length % 3 !== 0)
  11083. return;
  11084. this._gl.uniform3fv(uniform, array);
  11085. };
  11086. Engine.prototype.setArray4 = function (uniform, array) {
  11087. if (!uniform || array.length % 4 !== 0)
  11088. return;
  11089. this._gl.uniform4fv(uniform, array);
  11090. };
  11091. Engine.prototype.setMatrices = function (uniform, matrices) {
  11092. if (!uniform)
  11093. return;
  11094. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11095. };
  11096. Engine.prototype.setMatrix = function (uniform, matrix) {
  11097. if (!uniform)
  11098. return;
  11099. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11100. };
  11101. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11102. if (!uniform)
  11103. return;
  11104. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11105. };
  11106. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11107. if (!uniform)
  11108. return;
  11109. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11110. };
  11111. Engine.prototype.setInt = function (uniform, value) {
  11112. if (!uniform)
  11113. return;
  11114. this._gl.uniform1i(uniform, value);
  11115. };
  11116. Engine.prototype.setFloat = function (uniform, value) {
  11117. if (!uniform)
  11118. return;
  11119. this._gl.uniform1f(uniform, value);
  11120. };
  11121. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11122. if (!uniform)
  11123. return;
  11124. this._gl.uniform2f(uniform, x, y);
  11125. };
  11126. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11127. if (!uniform)
  11128. return;
  11129. this._gl.uniform3f(uniform, x, y, z);
  11130. };
  11131. Engine.prototype.setBool = function (uniform, bool) {
  11132. if (!uniform)
  11133. return;
  11134. this._gl.uniform1i(uniform, bool);
  11135. };
  11136. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11137. if (!uniform)
  11138. return;
  11139. this._gl.uniform4f(uniform, x, y, z, w);
  11140. };
  11141. Engine.prototype.setColor3 = function (uniform, color3) {
  11142. if (!uniform)
  11143. return;
  11144. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11145. };
  11146. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11147. if (!uniform)
  11148. return;
  11149. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11150. };
  11151. // States
  11152. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11153. if (zOffset === void 0) { zOffset = 0; }
  11154. if (reverseSide === void 0) { reverseSide = false; }
  11155. // Culling
  11156. if (this._depthCullingState.cull !== culling || force) {
  11157. this._depthCullingState.cull = culling;
  11158. }
  11159. // Cull face
  11160. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11161. if (this._depthCullingState.cullFace !== cullFace || force) {
  11162. this._depthCullingState.cullFace = cullFace;
  11163. }
  11164. // Z offset
  11165. this.setZOffset(zOffset);
  11166. // Front face
  11167. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11168. if (this._depthCullingState.frontFace !== frontFace || force) {
  11169. this._depthCullingState.frontFace = frontFace;
  11170. }
  11171. };
  11172. Engine.prototype.setZOffset = function (value) {
  11173. this._depthCullingState.zOffset = value;
  11174. };
  11175. Engine.prototype.getZOffset = function () {
  11176. return this._depthCullingState.zOffset;
  11177. };
  11178. Engine.prototype.setDepthBuffer = function (enable) {
  11179. this._depthCullingState.depthTest = enable;
  11180. };
  11181. Engine.prototype.getDepthWrite = function () {
  11182. return this._depthCullingState.depthMask;
  11183. };
  11184. Engine.prototype.setDepthWrite = function (enable) {
  11185. this._depthCullingState.depthMask = enable;
  11186. };
  11187. Engine.prototype.setColorWrite = function (enable) {
  11188. this._gl.colorMask(enable, enable, enable, enable);
  11189. this._colorWrite = enable;
  11190. };
  11191. Engine.prototype.getColorWrite = function () {
  11192. return this._colorWrite;
  11193. };
  11194. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11195. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11196. };
  11197. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11198. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11199. if (this._alphaMode === mode) {
  11200. return;
  11201. }
  11202. switch (mode) {
  11203. case Engine.ALPHA_DISABLE:
  11204. this._alphaState.alphaBlend = false;
  11205. break;
  11206. case Engine.ALPHA_PREMULTIPLIED:
  11207. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11208. this._alphaState.alphaBlend = true;
  11209. break;
  11210. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11211. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11212. this._alphaState.alphaBlend = true;
  11213. break;
  11214. case Engine.ALPHA_COMBINE:
  11215. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11216. this._alphaState.alphaBlend = true;
  11217. break;
  11218. case Engine.ALPHA_ONEONE:
  11219. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11220. this._alphaState.alphaBlend = true;
  11221. break;
  11222. case Engine.ALPHA_ADD:
  11223. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11224. this._alphaState.alphaBlend = true;
  11225. break;
  11226. case Engine.ALPHA_SUBTRACT:
  11227. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11228. this._alphaState.alphaBlend = true;
  11229. break;
  11230. case Engine.ALPHA_MULTIPLY:
  11231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11232. this._alphaState.alphaBlend = true;
  11233. break;
  11234. case Engine.ALPHA_MAXIMIZED:
  11235. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11236. this._alphaState.alphaBlend = true;
  11237. break;
  11238. case Engine.ALPHA_INTERPOLATE:
  11239. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11240. this._alphaState.alphaBlend = true;
  11241. break;
  11242. case Engine.ALPHA_SCREENMODE:
  11243. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11244. this._alphaState.alphaBlend = true;
  11245. break;
  11246. }
  11247. if (!noDepthWriteChange) {
  11248. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11249. }
  11250. this._alphaMode = mode;
  11251. };
  11252. Engine.prototype.getAlphaMode = function () {
  11253. return this._alphaMode;
  11254. };
  11255. Engine.prototype.setAlphaTesting = function (enable) {
  11256. this._alphaTest = enable;
  11257. };
  11258. Engine.prototype.getAlphaTesting = function () {
  11259. return !!this._alphaTest;
  11260. };
  11261. // Textures
  11262. Engine.prototype.wipeCaches = function (bruteForce) {
  11263. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11264. return;
  11265. }
  11266. this._currentEffect = null;
  11267. // 6/8/2017: deltakosh: Should not be required anymore.
  11268. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11269. if (bruteForce) {
  11270. this.resetTextureCache();
  11271. this._currentProgram = null;
  11272. this._stencilState.reset();
  11273. this._depthCullingState.reset();
  11274. this.setDepthFunctionToLessOrEqual();
  11275. this._alphaState.reset();
  11276. }
  11277. this._resetVertexBufferBinding();
  11278. this._cachedIndexBuffer = null;
  11279. this._cachedEffectForVertexBuffers = null;
  11280. this._unbindVertexArrayObject();
  11281. this.bindIndexBuffer(null);
  11282. };
  11283. /**
  11284. * Set the compressed texture format to use, based on the formats you have, and the formats
  11285. * supported by the hardware / browser.
  11286. *
  11287. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11288. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11289. * to API arguments needed to compressed textures. This puts the burden on the container
  11290. * generator to house the arcane code for determining these for current & future formats.
  11291. *
  11292. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11293. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11294. *
  11295. * Note: The result of this call is not taken into account when a texture is base64.
  11296. *
  11297. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11298. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11299. *
  11300. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11301. * @returns The extension selected.
  11302. */
  11303. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11304. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11305. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11306. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11307. return this._textureFormatInUse = this._texturesSupported[i];
  11308. }
  11309. }
  11310. }
  11311. // actively set format to nothing, to allow this to be called more than once
  11312. // and possibly fail the 2nd time
  11313. this._textureFormatInUse = null;
  11314. return null;
  11315. };
  11316. Engine.prototype._createTexture = function () {
  11317. var texture = this._gl.createTexture();
  11318. if (!texture) {
  11319. throw new Error("Unable to create texture");
  11320. }
  11321. return texture;
  11322. };
  11323. /**
  11324. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11325. * @param {string} urlArg- This contains one of the following:
  11326. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11327. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11328. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11329. *
  11330. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11331. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11332. * @param {Scene} scene- Needed for loading to the correct scene.
  11333. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11334. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11335. * @param {callback} onError- Optional callback to be called upon failure.
  11336. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11337. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11338. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11339. *
  11340. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11341. */
  11342. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11343. var _this = this;
  11344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11345. if (onLoad === void 0) { onLoad = null; }
  11346. if (onError === void 0) { onError = null; }
  11347. if (buffer === void 0) { buffer = null; }
  11348. if (fallBack === void 0) { fallBack = null; }
  11349. if (format === void 0) { format = null; }
  11350. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11351. var fromData = url.substr(0, 5) === "data:";
  11352. var fromBlob = url.substr(0, 5) === "blob:";
  11353. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11354. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11355. // establish the file extension, if possible
  11356. var lastDot = url.lastIndexOf('.');
  11357. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11358. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11359. var isTGA = (extension === ".tga");
  11360. // determine if a ktx file should be substituted
  11361. var isKTX = false;
  11362. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11363. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11364. isKTX = true;
  11365. }
  11366. if (scene) {
  11367. scene._addPendingData(texture);
  11368. }
  11369. texture.url = url;
  11370. texture.generateMipMaps = !noMipmap;
  11371. texture.samplingMode = samplingMode;
  11372. texture.invertY = invertY;
  11373. if (!this._doNotHandleContextLost) {
  11374. // Keep a link to the buffer only if we plan to handle context lost
  11375. texture._buffer = buffer;
  11376. }
  11377. var onLoadObserver = null;
  11378. if (onLoad && !fallBack) {
  11379. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11380. }
  11381. if (!fallBack)
  11382. this._internalTexturesCache.push(texture);
  11383. var onerror = function (message, exception) {
  11384. if (scene) {
  11385. scene._removePendingData(texture);
  11386. }
  11387. if (onLoadObserver) {
  11388. texture.onLoadedObservable.remove(onLoadObserver);
  11389. }
  11390. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11391. if (isKTX) {
  11392. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11393. }
  11394. else if (BABYLON.Tools.UseFallbackTexture) {
  11395. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11396. }
  11397. if (onError) {
  11398. onError(message || "Unknown error", exception);
  11399. }
  11400. };
  11401. var callback = null;
  11402. // processing for non-image formats
  11403. if (isKTX || isTGA || isDDS) {
  11404. if (isKTX) {
  11405. callback = function (data) {
  11406. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11407. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11408. ktx.uploadLevels(_this._gl, !noMipmap);
  11409. return false;
  11410. }, samplingMode);
  11411. };
  11412. }
  11413. else if (isTGA) {
  11414. callback = function (arrayBuffer) {
  11415. var data = new Uint8Array(arrayBuffer);
  11416. var header = BABYLON.TGATools.GetTGAHeader(data);
  11417. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11418. BABYLON.TGATools.UploadContent(_this._gl, data);
  11419. return false;
  11420. }, samplingMode);
  11421. };
  11422. }
  11423. else if (isDDS) {
  11424. callback = function (data) {
  11425. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11426. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11427. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11428. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11429. return false;
  11430. }, samplingMode);
  11431. };
  11432. }
  11433. if (!buffer) {
  11434. this._loadFile(url, function (data) {
  11435. if (callback) {
  11436. callback(data);
  11437. }
  11438. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11439. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11440. });
  11441. }
  11442. else {
  11443. if (callback) {
  11444. callback(buffer);
  11445. }
  11446. }
  11447. // image format processing
  11448. }
  11449. else {
  11450. var onload = function (img) {
  11451. if (fromBlob && !_this._doNotHandleContextLost) {
  11452. // We need to store the image if we need to rebuild the texture
  11453. // in case of a webgl context lost
  11454. texture._buffer = img;
  11455. }
  11456. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11457. var gl = _this._gl;
  11458. var isPot = (img.width === potWidth && img.height === potHeight);
  11459. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11460. if (isPot) {
  11461. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11462. return false;
  11463. }
  11464. // Using shaders to rescale because canvas.drawImage is lossy
  11465. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11466. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11467. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11470. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11471. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11472. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11473. _this._releaseTexture(source);
  11474. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11475. continuationCallback();
  11476. });
  11477. return true;
  11478. }, samplingMode);
  11479. };
  11480. if (!fromData || isBase64)
  11481. if (buffer instanceof HTMLImageElement) {
  11482. onload(buffer);
  11483. }
  11484. else {
  11485. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11486. }
  11487. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11488. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11489. else
  11490. onload(buffer);
  11491. }
  11492. return texture;
  11493. };
  11494. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11495. var _this = this;
  11496. var rtt = this.createRenderTargetTexture({
  11497. width: destination.width,
  11498. height: destination.height,
  11499. }, {
  11500. generateMipMaps: false,
  11501. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11502. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11503. generateDepthBuffer: false,
  11504. generateStencilBuffer: false
  11505. });
  11506. if (!this._rescalePostProcess) {
  11507. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11508. }
  11509. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11510. _this._rescalePostProcess.onApply = function (effect) {
  11511. effect._bindTexture("textureSampler", source);
  11512. };
  11513. var hostingScene = scene;
  11514. if (!hostingScene) {
  11515. hostingScene = _this.scenes[_this.scenes.length - 1];
  11516. }
  11517. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11518. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11519. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11520. _this.unBindFramebuffer(rtt);
  11521. _this._releaseTexture(rtt);
  11522. if (onComplete) {
  11523. onComplete();
  11524. }
  11525. });
  11526. };
  11527. Engine.prototype._getInternalFormat = function (format) {
  11528. var internalFormat = this._gl.RGBA;
  11529. switch (format) {
  11530. case Engine.TEXTUREFORMAT_ALPHA:
  11531. internalFormat = this._gl.ALPHA;
  11532. break;
  11533. case Engine.TEXTUREFORMAT_LUMINANCE:
  11534. internalFormat = this._gl.LUMINANCE;
  11535. break;
  11536. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11537. internalFormat = this._gl.LUMINANCE_ALPHA;
  11538. break;
  11539. case Engine.TEXTUREFORMAT_RGB:
  11540. internalFormat = this._gl.RGB;
  11541. break;
  11542. case Engine.TEXTUREFORMAT_RGBA:
  11543. internalFormat = this._gl.RGBA;
  11544. break;
  11545. }
  11546. return internalFormat;
  11547. };
  11548. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11549. if (compression === void 0) { compression = null; }
  11550. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11551. if (!texture) {
  11552. return;
  11553. }
  11554. var internalFormat = this._getInternalFormat(format);
  11555. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11556. var textureType = this._getWebGLTextureType(type);
  11557. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11558. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11559. if (!this._doNotHandleContextLost) {
  11560. texture._bufferView = data;
  11561. texture.format = format;
  11562. texture.type = type;
  11563. texture.invertY = invertY;
  11564. texture._compression = compression;
  11565. }
  11566. if (texture.width % 4 !== 0) {
  11567. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11568. }
  11569. if (compression && data) {
  11570. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11571. }
  11572. else {
  11573. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11574. }
  11575. if (texture.generateMipMaps) {
  11576. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11577. }
  11578. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11579. // this.resetTextureCache();
  11580. texture.isReady = true;
  11581. };
  11582. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11583. if (compression === void 0) { compression = null; }
  11584. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11585. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11586. texture.baseWidth = width;
  11587. texture.baseHeight = height;
  11588. texture.width = width;
  11589. texture.height = height;
  11590. texture.format = format;
  11591. texture.generateMipMaps = generateMipMaps;
  11592. texture.samplingMode = samplingMode;
  11593. texture.invertY = invertY;
  11594. texture._compression = compression;
  11595. texture.type = type;
  11596. if (!this._doNotHandleContextLost) {
  11597. texture._bufferView = data;
  11598. }
  11599. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11600. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11601. // Filters
  11602. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11604. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11605. if (generateMipMaps) {
  11606. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11607. }
  11608. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11609. this._internalTexturesCache.push(texture);
  11610. return texture;
  11611. };
  11612. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11613. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11614. texture.baseWidth = width;
  11615. texture.baseHeight = height;
  11616. if (generateMipMaps) {
  11617. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11618. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11619. }
  11620. // this.resetTextureCache();
  11621. texture.width = width;
  11622. texture.height = height;
  11623. texture.isReady = false;
  11624. texture.generateMipMaps = generateMipMaps;
  11625. texture.samplingMode = samplingMode;
  11626. this.updateTextureSamplingMode(samplingMode, texture);
  11627. this._internalTexturesCache.push(texture);
  11628. return texture;
  11629. };
  11630. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11631. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11632. if (texture.isCube) {
  11633. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11634. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11635. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11636. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11637. }
  11638. else if (texture.is3D) {
  11639. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11640. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11641. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11642. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11643. }
  11644. else {
  11645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11647. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11648. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11649. }
  11650. texture.samplingMode = samplingMode;
  11651. };
  11652. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11653. if (premulAlpha === void 0) { premulAlpha = false; }
  11654. if (!texture) {
  11655. return;
  11656. }
  11657. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11658. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11659. if (premulAlpha) {
  11660. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11661. }
  11662. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11663. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11664. if (texture.generateMipMaps) {
  11665. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11666. }
  11667. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11668. if (premulAlpha) {
  11669. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11670. }
  11671. texture.isReady = true;
  11672. };
  11673. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11674. if (!texture || texture._isDisabled) {
  11675. return;
  11676. }
  11677. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11678. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11679. try {
  11680. // Testing video texture support
  11681. if (this._videoTextureSupported === undefined) {
  11682. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11683. if (this._gl.getError() !== 0) {
  11684. this._videoTextureSupported = false;
  11685. }
  11686. else {
  11687. this._videoTextureSupported = true;
  11688. }
  11689. }
  11690. // Copy video through the current working canvas if video texture is not supported
  11691. if (!this._videoTextureSupported) {
  11692. if (!texture._workingCanvas) {
  11693. texture._workingCanvas = document.createElement("canvas");
  11694. var context = texture._workingCanvas.getContext("2d");
  11695. if (!context) {
  11696. throw new Error("Unable to get 2d context");
  11697. }
  11698. texture._workingContext = context;
  11699. texture._workingCanvas.width = texture.width;
  11700. texture._workingCanvas.height = texture.height;
  11701. }
  11702. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11703. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11704. }
  11705. else {
  11706. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11707. }
  11708. if (texture.generateMipMaps) {
  11709. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11710. }
  11711. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11712. // this.resetTextureCache();
  11713. texture.isReady = true;
  11714. }
  11715. catch (ex) {
  11716. // Something unexpected
  11717. // Let's disable the texture
  11718. texture._isDisabled = true;
  11719. }
  11720. };
  11721. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11722. var fullOptions = new RenderTargetCreationOptions();
  11723. if (options !== undefined && typeof options === "object") {
  11724. fullOptions.generateMipMaps = options.generateMipMaps;
  11725. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11726. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11727. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11728. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11729. }
  11730. else {
  11731. fullOptions.generateMipMaps = options;
  11732. fullOptions.generateDepthBuffer = true;
  11733. fullOptions.generateStencilBuffer = false;
  11734. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11735. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11736. }
  11737. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11738. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11739. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11740. }
  11741. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11742. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11743. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11744. }
  11745. var gl = this._gl;
  11746. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11747. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11748. var width = size.width || size;
  11749. var height = size.height || size;
  11750. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11751. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11752. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11753. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11754. }
  11755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11759. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11760. // Create the framebuffer
  11761. var framebuffer = gl.createFramebuffer();
  11762. this.bindUnboundFramebuffer(framebuffer);
  11763. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11764. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11765. if (fullOptions.generateMipMaps) {
  11766. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11767. }
  11768. // Unbind
  11769. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11770. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11771. this.bindUnboundFramebuffer(null);
  11772. texture._framebuffer = framebuffer;
  11773. texture.baseWidth = width;
  11774. texture.baseHeight = height;
  11775. texture.width = width;
  11776. texture.height = height;
  11777. texture.isReady = true;
  11778. texture.samples = 1;
  11779. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11780. texture.samplingMode = fullOptions.samplingMode;
  11781. texture.type = fullOptions.type;
  11782. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11783. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11784. // this.resetTextureCache();
  11785. this._internalTexturesCache.push(texture);
  11786. return texture;
  11787. };
  11788. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11789. var generateMipMaps = false;
  11790. var generateDepthBuffer = true;
  11791. var generateStencilBuffer = false;
  11792. var generateDepthTexture = false;
  11793. var textureCount = 1;
  11794. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11795. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11796. var types = [], samplingModes = [];
  11797. if (options !== undefined) {
  11798. generateMipMaps = options.generateMipMaps;
  11799. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11800. generateStencilBuffer = options.generateStencilBuffer;
  11801. generateDepthTexture = options.generateDepthTexture;
  11802. textureCount = options.textureCount || 1;
  11803. if (options.types) {
  11804. types = options.types;
  11805. }
  11806. if (options.samplingModes) {
  11807. samplingModes = options.samplingModes;
  11808. }
  11809. }
  11810. var gl = this._gl;
  11811. // Create the framebuffer
  11812. var framebuffer = gl.createFramebuffer();
  11813. this.bindUnboundFramebuffer(framebuffer);
  11814. var width = size.width || size;
  11815. var height = size.height || size;
  11816. var textures = [];
  11817. var attachments = [];
  11818. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11819. for (var i = 0; i < textureCount; i++) {
  11820. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11821. var type = types[i] || defaultType;
  11822. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11823. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11824. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11825. }
  11826. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11827. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11828. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11829. }
  11830. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11831. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11832. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11833. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11834. }
  11835. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11836. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11837. textures.push(texture);
  11838. attachments.push(attachment);
  11839. gl.activeTexture(gl["TEXTURE" + i]);
  11840. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11841. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11842. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11843. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11845. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11846. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11847. if (generateMipMaps) {
  11848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11849. }
  11850. // Unbind
  11851. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11852. texture._framebuffer = framebuffer;
  11853. texture._depthStencilBuffer = depthStencilBuffer;
  11854. texture.baseWidth = width;
  11855. texture.baseHeight = height;
  11856. texture.width = width;
  11857. texture.height = height;
  11858. texture.isReady = true;
  11859. texture.samples = 1;
  11860. texture.generateMipMaps = generateMipMaps;
  11861. texture.samplingMode = samplingMode;
  11862. texture.type = type;
  11863. texture._generateDepthBuffer = generateDepthBuffer;
  11864. texture._generateStencilBuffer = generateStencilBuffer;
  11865. texture._attachments = attachments;
  11866. this._internalTexturesCache.push(texture);
  11867. }
  11868. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11869. // Depth texture
  11870. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11871. gl.activeTexture(gl.TEXTURE0);
  11872. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11875. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11877. 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);
  11878. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11879. depthTexture._framebuffer = framebuffer;
  11880. depthTexture.baseWidth = width;
  11881. depthTexture.baseHeight = height;
  11882. depthTexture.width = width;
  11883. depthTexture.height = height;
  11884. depthTexture.isReady = true;
  11885. depthTexture.samples = 1;
  11886. depthTexture.generateMipMaps = generateMipMaps;
  11887. depthTexture.samplingMode = gl.NEAREST;
  11888. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11889. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11890. textures.push(depthTexture);
  11891. this._internalTexturesCache.push(depthTexture);
  11892. }
  11893. gl.drawBuffers(attachments);
  11894. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11895. this.bindUnboundFramebuffer(null);
  11896. this.resetTextureCache();
  11897. return textures;
  11898. };
  11899. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11900. if (samples === void 0) { samples = 1; }
  11901. var depthStencilBuffer = null;
  11902. var gl = this._gl;
  11903. // Create the depth/stencil buffer
  11904. if (generateStencilBuffer) {
  11905. depthStencilBuffer = gl.createRenderbuffer();
  11906. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11907. if (samples > 1) {
  11908. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11909. }
  11910. else {
  11911. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11912. }
  11913. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11914. }
  11915. else if (generateDepthBuffer) {
  11916. depthStencilBuffer = gl.createRenderbuffer();
  11917. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11918. if (samples > 1) {
  11919. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11920. }
  11921. else {
  11922. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11923. }
  11924. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11925. }
  11926. return depthStencilBuffer;
  11927. };
  11928. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11929. if (this.webGLVersion < 2 || !texture) {
  11930. return 1;
  11931. }
  11932. if (texture.samples === samples) {
  11933. return samples;
  11934. }
  11935. var gl = this._gl;
  11936. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11937. // Dispose previous render buffers
  11938. if (texture._depthStencilBuffer) {
  11939. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11940. texture._depthStencilBuffer = null;
  11941. }
  11942. if (texture._MSAAFramebuffer) {
  11943. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11944. texture._MSAAFramebuffer = null;
  11945. }
  11946. if (texture._MSAARenderBuffer) {
  11947. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11948. texture._MSAARenderBuffer = null;
  11949. }
  11950. if (samples > 1) {
  11951. var framebuffer = gl.createFramebuffer();
  11952. if (!framebuffer) {
  11953. throw new Error("Unable to create multi sampled framebuffer");
  11954. }
  11955. texture._MSAAFramebuffer = framebuffer;
  11956. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11957. var colorRenderbuffer = gl.createRenderbuffer();
  11958. if (!colorRenderbuffer) {
  11959. throw new Error("Unable to create multi sampled framebuffer");
  11960. }
  11961. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11962. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11963. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11964. texture._MSAARenderBuffer = colorRenderbuffer;
  11965. }
  11966. else {
  11967. this.bindUnboundFramebuffer(texture._framebuffer);
  11968. }
  11969. texture.samples = samples;
  11970. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11971. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11972. this.bindUnboundFramebuffer(null);
  11973. return samples;
  11974. };
  11975. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11976. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11977. return 1;
  11978. }
  11979. if (textures[0].samples === samples) {
  11980. return samples;
  11981. }
  11982. var gl = this._gl;
  11983. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11984. // Dispose previous render buffers
  11985. if (textures[0]._depthStencilBuffer) {
  11986. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11987. textures[0]._depthStencilBuffer = null;
  11988. }
  11989. if (textures[0]._MSAAFramebuffer) {
  11990. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11991. textures[0]._MSAAFramebuffer = null;
  11992. }
  11993. for (var i = 0; i < textures.length; i++) {
  11994. if (textures[i]._MSAARenderBuffer) {
  11995. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11996. textures[i]._MSAARenderBuffer = null;
  11997. }
  11998. }
  11999. if (samples > 1) {
  12000. var framebuffer = gl.createFramebuffer();
  12001. if (!framebuffer) {
  12002. throw new Error("Unable to create multi sampled framebuffer");
  12003. }
  12004. this.bindUnboundFramebuffer(framebuffer);
  12005. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12006. var attachments = [];
  12007. for (var i = 0; i < textures.length; i++) {
  12008. var texture = textures[i];
  12009. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12010. var colorRenderbuffer = gl.createRenderbuffer();
  12011. if (!colorRenderbuffer) {
  12012. throw new Error("Unable to create multi sampled framebuffer");
  12013. }
  12014. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12015. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12016. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12017. texture._MSAAFramebuffer = framebuffer;
  12018. texture._MSAARenderBuffer = colorRenderbuffer;
  12019. texture.samples = samples;
  12020. texture._depthStencilBuffer = depthStencilBuffer;
  12021. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12022. attachments.push(attachment);
  12023. }
  12024. gl.drawBuffers(attachments);
  12025. }
  12026. else {
  12027. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12028. }
  12029. this.bindUnboundFramebuffer(null);
  12030. return samples;
  12031. };
  12032. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12033. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12034. };
  12035. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12036. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12037. };
  12038. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12039. var gl = this._gl;
  12040. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12041. var generateMipMaps = true;
  12042. var generateDepthBuffer = true;
  12043. var generateStencilBuffer = false;
  12044. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12045. if (options !== undefined) {
  12046. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12047. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12048. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12049. if (options.samplingMode !== undefined) {
  12050. samplingMode = options.samplingMode;
  12051. }
  12052. }
  12053. texture.isCube = true;
  12054. texture.generateMipMaps = generateMipMaps;
  12055. texture.samples = 1;
  12056. texture.samplingMode = samplingMode;
  12057. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12058. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12059. for (var face = 0; face < 6; face++) {
  12060. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12061. }
  12062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12066. // Create the framebuffer
  12067. var framebuffer = gl.createFramebuffer();
  12068. this.bindUnboundFramebuffer(framebuffer);
  12069. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12070. // Mipmaps
  12071. if (texture.generateMipMaps) {
  12072. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12073. }
  12074. // Unbind
  12075. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12076. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12077. this.bindUnboundFramebuffer(null);
  12078. texture._framebuffer = framebuffer;
  12079. texture.width = size;
  12080. texture.height = size;
  12081. texture.isReady = true;
  12082. //this.resetTextureCache();
  12083. this._internalTexturesCache.push(texture);
  12084. return texture;
  12085. };
  12086. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12087. var _this = this;
  12088. if (onLoad === void 0) { onLoad = null; }
  12089. if (onError === void 0) { onError = null; }
  12090. if (forcedExtension === void 0) { forcedExtension = null; }
  12091. var callback = function (loadData) {
  12092. if (!loadData) {
  12093. if (onLoad) {
  12094. onLoad(null);
  12095. }
  12096. return;
  12097. }
  12098. var texture = loadData.texture;
  12099. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12100. texture._lodGenerationScale = scale;
  12101. texture._lodGenerationOffset = offset;
  12102. if (_this._caps.textureLOD) {
  12103. // Do not add extra process if texture lod is supported.
  12104. if (onLoad) {
  12105. onLoad(texture);
  12106. }
  12107. return;
  12108. }
  12109. var mipSlices = 3;
  12110. var gl = _this._gl;
  12111. var width = loadData.width;
  12112. if (!width) {
  12113. return;
  12114. }
  12115. var textures = [];
  12116. for (var i = 0; i < mipSlices; i++) {
  12117. //compute LOD from even spacing in smoothness (matching shader calculation)
  12118. var smoothness = i / (mipSlices - 1);
  12119. var roughness = 1 - smoothness;
  12120. var minLODIndex = offset; // roughness = 0
  12121. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12122. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12123. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12124. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12125. glTextureFromLod.isCube = true;
  12126. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12128. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12131. if (loadData.isDDS) {
  12132. var info = loadData.info;
  12133. var data = loadData.data;
  12134. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12135. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12136. }
  12137. else {
  12138. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12139. }
  12140. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12141. // Wrap in a base texture for easy binding.
  12142. var lodTexture = new BABYLON.BaseTexture(scene);
  12143. lodTexture.isCube = true;
  12144. lodTexture._texture = glTextureFromLod;
  12145. glTextureFromLod.isReady = true;
  12146. textures.push(lodTexture);
  12147. }
  12148. texture._lodTextureHigh = textures[2];
  12149. texture._lodTextureMid = textures[1];
  12150. texture._lodTextureLow = textures[0];
  12151. if (onLoad) {
  12152. onLoad(texture);
  12153. }
  12154. };
  12155. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12156. };
  12157. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12158. var _this = this;
  12159. if (onLoad === void 0) { onLoad = null; }
  12160. if (onError === void 0) { onError = null; }
  12161. if (forcedExtension === void 0) { forcedExtension = null; }
  12162. var gl = this._gl;
  12163. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12164. texture.isCube = true;
  12165. texture.url = rootUrl;
  12166. texture.generateMipMaps = !noMipmap;
  12167. if (!this._doNotHandleContextLost) {
  12168. texture._extension = forcedExtension;
  12169. texture._files = files;
  12170. }
  12171. var isKTX = false;
  12172. var isDDS = false;
  12173. var lastDot = rootUrl.lastIndexOf('.');
  12174. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12175. if (this._textureFormatInUse) {
  12176. extension = this._textureFormatInUse;
  12177. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12178. isKTX = true;
  12179. }
  12180. else {
  12181. isDDS = (extension === ".dds");
  12182. }
  12183. var onerror = function (request, exception) {
  12184. if (onError && request) {
  12185. onError(request.status + " " + request.statusText, exception);
  12186. }
  12187. };
  12188. if (isKTX) {
  12189. this._loadFile(rootUrl, function (data) {
  12190. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12191. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12192. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12193. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12194. ktx.uploadLevels(_this._gl, !noMipmap);
  12195. _this.setCubeMapTextureParams(gl, loadMipmap);
  12196. texture.width = ktx.pixelWidth;
  12197. texture.height = ktx.pixelHeight;
  12198. texture.isReady = true;
  12199. }, undefined, undefined, true, onerror);
  12200. }
  12201. else if (isDDS) {
  12202. if (files && files.length === 6) {
  12203. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12204. var info;
  12205. var loadMipmap = false;
  12206. var width = 0;
  12207. for (var index = 0; index < imgs.length; index++) {
  12208. var data = imgs[index];
  12209. info = BABYLON.DDSTools.GetDDSInfo(data);
  12210. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12211. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12212. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12213. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12214. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12215. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12216. }
  12217. texture.width = info.width;
  12218. texture.height = info.height;
  12219. texture.type = info.textureType;
  12220. width = info.width;
  12221. }
  12222. _this.setCubeMapTextureParams(gl, loadMipmap);
  12223. texture.isReady = true;
  12224. if (onLoad) {
  12225. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12226. }
  12227. }, files, onError);
  12228. }
  12229. else {
  12230. this._loadFile(rootUrl, function (data) {
  12231. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12232. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12233. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12234. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12235. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12236. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12237. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12238. }
  12239. _this.setCubeMapTextureParams(gl, loadMipmap);
  12240. texture.width = info.width;
  12241. texture.height = info.height;
  12242. texture.isReady = true;
  12243. texture.type = info.textureType;
  12244. if (onLoad) {
  12245. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12246. }
  12247. }, undefined, undefined, true, onerror);
  12248. }
  12249. }
  12250. else {
  12251. if (!files) {
  12252. throw new Error("Cannot load cubemap because files were not defined");
  12253. }
  12254. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12255. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12256. var height = width;
  12257. _this._prepareWorkingCanvas();
  12258. if (!_this._workingCanvas || !_this._workingContext) {
  12259. return;
  12260. }
  12261. _this._workingCanvas.width = width;
  12262. _this._workingCanvas.height = height;
  12263. var faces = [
  12264. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12265. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12266. ];
  12267. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12268. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12269. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12270. for (var index = 0; index < faces.length; index++) {
  12271. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12272. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12273. }
  12274. if (!noMipmap) {
  12275. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12276. }
  12277. _this.setCubeMapTextureParams(gl, !noMipmap);
  12278. texture.width = width;
  12279. texture.height = height;
  12280. texture.isReady = true;
  12281. if (format) {
  12282. texture.format = format;
  12283. }
  12284. texture.onLoadedObservable.notifyObservers(texture);
  12285. texture.onLoadedObservable.clear();
  12286. if (onLoad) {
  12287. onLoad();
  12288. }
  12289. }, files, onError);
  12290. }
  12291. this._internalTexturesCache.push(texture);
  12292. return texture;
  12293. };
  12294. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12295. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12299. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12300. // this.resetTextureCache();
  12301. };
  12302. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12303. if (compression === void 0) { compression = null; }
  12304. if (level === void 0) { level = 0; }
  12305. texture._bufferViewArray = data;
  12306. texture.format = format;
  12307. texture.type = type;
  12308. texture.invertY = invertY;
  12309. texture._compression = compression;
  12310. var gl = this._gl;
  12311. var textureType = this._getWebGLTextureType(type);
  12312. var internalFormat = this._getInternalFormat(format);
  12313. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12314. var needConversion = false;
  12315. if (internalFormat === gl.RGB) {
  12316. internalFormat = gl.RGBA;
  12317. needConversion = true;
  12318. }
  12319. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12320. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12321. if (texture.width % 4 !== 0) {
  12322. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12323. }
  12324. // Data are known to be in +X +Y +Z -X -Y -Z
  12325. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12326. var faceData = data[faceIndex];
  12327. if (compression) {
  12328. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12329. }
  12330. else {
  12331. if (needConversion) {
  12332. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12333. }
  12334. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12335. }
  12336. }
  12337. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12338. if (isPot && texture.generateMipMaps && level === 0) {
  12339. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12340. }
  12341. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12342. // this.resetTextureCache();
  12343. texture.isReady = true;
  12344. };
  12345. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12346. if (compression === void 0) { compression = null; }
  12347. var gl = this._gl;
  12348. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12349. texture.isCube = true;
  12350. texture.generateMipMaps = generateMipMaps;
  12351. texture.format = format;
  12352. texture.type = type;
  12353. if (!this._doNotHandleContextLost) {
  12354. texture._bufferViewArray = data;
  12355. }
  12356. var textureType = this._getWebGLTextureType(type);
  12357. var internalFormat = this._getInternalFormat(format);
  12358. if (internalFormat === gl.RGB) {
  12359. internalFormat = gl.RGBA;
  12360. }
  12361. var width = size;
  12362. var height = width;
  12363. texture.width = width;
  12364. texture.height = height;
  12365. // Double check on POT to generate Mips.
  12366. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12367. if (!isPot) {
  12368. generateMipMaps = false;
  12369. }
  12370. // Upload data if needed. The texture won't be ready until then.
  12371. if (data) {
  12372. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12373. }
  12374. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12375. // Filters
  12376. if (data && generateMipMaps) {
  12377. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12378. }
  12379. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12382. }
  12383. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12386. }
  12387. else {
  12388. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12391. }
  12392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12394. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12395. return texture;
  12396. };
  12397. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12398. var _this = this;
  12399. if (onLoad === void 0) { onLoad = null; }
  12400. if (onError === void 0) { onError = null; }
  12401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12402. if (invertY === void 0) { invertY = false; }
  12403. var gl = this._gl;
  12404. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12405. scene._addPendingData(texture);
  12406. texture.url = url;
  12407. this._internalTexturesCache.push(texture);
  12408. var onerror = function (request, exception) {
  12409. scene._removePendingData(texture);
  12410. if (onError && request) {
  12411. onError(request.status + " " + request.statusText, exception);
  12412. }
  12413. };
  12414. var internalCallback = function (data) {
  12415. var width = texture.width;
  12416. var faceDataArrays = callback(data);
  12417. if (!faceDataArrays) {
  12418. return;
  12419. }
  12420. if (mipmmapGenerator) {
  12421. var textureType = _this._getWebGLTextureType(type);
  12422. var internalFormat = _this._getInternalFormat(format);
  12423. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12424. var needConversion = false;
  12425. if (internalFormat === gl.RGB) {
  12426. internalFormat = gl.RGBA;
  12427. needConversion = true;
  12428. }
  12429. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12430. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12431. var mipData = mipmmapGenerator(faceDataArrays);
  12432. for (var level = 0; level < mipData.length; level++) {
  12433. var mipSize = width >> level;
  12434. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12435. var mipFaceData = mipData[level][faceIndex];
  12436. if (needConversion) {
  12437. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12438. }
  12439. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12440. }
  12441. }
  12442. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12443. }
  12444. else {
  12445. texture.generateMipMaps = !noMipmap;
  12446. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12447. }
  12448. texture.isReady = true;
  12449. // this.resetTextureCache();
  12450. scene._removePendingData(texture);
  12451. if (onLoad) {
  12452. onLoad();
  12453. }
  12454. };
  12455. this._loadFile(url, function (data) {
  12456. internalCallback(data);
  12457. }, undefined, scene.database, true, onerror);
  12458. return texture;
  12459. };
  12460. ;
  12461. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12462. if (compression === void 0) { compression = null; }
  12463. var internalFormat = this._getInternalFormat(format);
  12464. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12465. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12466. if (!this._doNotHandleContextLost) {
  12467. texture._bufferView = data;
  12468. texture.format = format;
  12469. texture.invertY = invertY;
  12470. texture._compression = compression;
  12471. }
  12472. if (texture.width % 4 !== 0) {
  12473. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12474. }
  12475. if (compression && data) {
  12476. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12477. }
  12478. else {
  12479. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12480. }
  12481. if (texture.generateMipMaps) {
  12482. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12483. }
  12484. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12485. // this.resetTextureCache();
  12486. texture.isReady = true;
  12487. };
  12488. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12489. if (compression === void 0) { compression = null; }
  12490. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12491. texture.baseWidth = width;
  12492. texture.baseHeight = height;
  12493. texture.baseDepth = depth;
  12494. texture.width = width;
  12495. texture.height = height;
  12496. texture.depth = depth;
  12497. texture.format = format;
  12498. texture.generateMipMaps = generateMipMaps;
  12499. texture.samplingMode = samplingMode;
  12500. texture.is3D = true;
  12501. if (!this._doNotHandleContextLost) {
  12502. texture._bufferView = data;
  12503. }
  12504. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12505. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12506. // Filters
  12507. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12508. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12509. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12510. if (generateMipMaps) {
  12511. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12512. }
  12513. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12514. this._internalTexturesCache.push(texture);
  12515. return texture;
  12516. };
  12517. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12518. var gl = this._gl;
  12519. if (!gl) {
  12520. return;
  12521. }
  12522. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12525. if (!noMipmap && !isCompressed) {
  12526. gl.generateMipmap(gl.TEXTURE_2D);
  12527. }
  12528. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12529. // this.resetTextureCache();
  12530. if (scene) {
  12531. scene._removePendingData(texture);
  12532. }
  12533. texture.onLoadedObservable.notifyObservers(texture);
  12534. texture.onLoadedObservable.clear();
  12535. };
  12536. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12537. var _this = this;
  12538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12539. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12540. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12541. var gl = this._gl;
  12542. if (!gl) {
  12543. return;
  12544. }
  12545. if (!texture._webGLTexture) {
  12546. // this.resetTextureCache();
  12547. if (scene) {
  12548. scene._removePendingData(texture);
  12549. }
  12550. return;
  12551. }
  12552. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12553. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12554. texture.baseWidth = width;
  12555. texture.baseHeight = height;
  12556. texture.width = potWidth;
  12557. texture.height = potHeight;
  12558. texture.isReady = true;
  12559. if (processFunction(potWidth, potHeight, function () {
  12560. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12561. })) {
  12562. // Returning as texture needs extra async steps
  12563. return;
  12564. }
  12565. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12566. };
  12567. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12568. // Create new RGBA data container.
  12569. var rgbaData;
  12570. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12571. rgbaData = new Float32Array(width * height * 4);
  12572. }
  12573. else {
  12574. rgbaData = new Uint32Array(width * height * 4);
  12575. }
  12576. // Convert each pixel.
  12577. for (var x = 0; x < width; x++) {
  12578. for (var y = 0; y < height; y++) {
  12579. var index = (y * width + x) * 3;
  12580. var newIndex = (y * width + x) * 4;
  12581. // Map Old Value to new value.
  12582. rgbaData[newIndex + 0] = rgbData[index + 0];
  12583. rgbaData[newIndex + 1] = rgbData[index + 1];
  12584. rgbaData[newIndex + 2] = rgbData[index + 2];
  12585. // Add fully opaque alpha channel.
  12586. rgbaData[newIndex + 3] = 1;
  12587. }
  12588. }
  12589. return rgbaData;
  12590. };
  12591. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12592. var gl = this._gl;
  12593. if (texture._framebuffer) {
  12594. gl.deleteFramebuffer(texture._framebuffer);
  12595. texture._framebuffer = null;
  12596. }
  12597. if (texture._depthStencilBuffer) {
  12598. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12599. texture._depthStencilBuffer = null;
  12600. }
  12601. if (texture._MSAAFramebuffer) {
  12602. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12603. texture._MSAAFramebuffer = null;
  12604. }
  12605. if (texture._MSAARenderBuffer) {
  12606. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12607. texture._MSAARenderBuffer = null;
  12608. }
  12609. };
  12610. Engine.prototype._releaseTexture = function (texture) {
  12611. var gl = this._gl;
  12612. this._releaseFramebufferObjects(texture);
  12613. gl.deleteTexture(texture._webGLTexture);
  12614. // Unbind channels
  12615. this.unbindAllTextures();
  12616. var index = this._internalTexturesCache.indexOf(texture);
  12617. if (index !== -1) {
  12618. this._internalTexturesCache.splice(index, 1);
  12619. }
  12620. // Integrated fixed lod samplers.
  12621. if (texture._lodTextureHigh) {
  12622. texture._lodTextureHigh.dispose();
  12623. }
  12624. if (texture._lodTextureMid) {
  12625. texture._lodTextureMid.dispose();
  12626. }
  12627. if (texture._lodTextureLow) {
  12628. texture._lodTextureLow.dispose();
  12629. }
  12630. };
  12631. Engine.prototype.setProgram = function (program) {
  12632. if (this._currentProgram !== program) {
  12633. this._gl.useProgram(program);
  12634. this._currentProgram = program;
  12635. }
  12636. };
  12637. Engine.prototype.bindSamplers = function (effect) {
  12638. this.setProgram(effect.getProgram());
  12639. var samplers = effect.getSamplers();
  12640. for (var index = 0; index < samplers.length; index++) {
  12641. var uniform = effect.getUniform(samplers[index]);
  12642. if (uniform) {
  12643. this._boundUniforms[index] = uniform;
  12644. }
  12645. }
  12646. this._currentEffect = null;
  12647. };
  12648. Engine.prototype._activateTextureChannel = function (channel) {
  12649. if (this._activeChannel !== channel && channel > -1) {
  12650. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  12651. this._activeChannel = channel;
  12652. }
  12653. };
  12654. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12655. var index = this._boundTexturesStack.indexOf(internalTexture);
  12656. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12657. this._boundTexturesStack.splice(index, 1);
  12658. this._boundTexturesStack.push(internalTexture);
  12659. }
  12660. };
  12661. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12662. var currentSlot = internalTexture._designatedSlot;
  12663. internalTexture._designatedSlot = -1;
  12664. var index = this._boundTexturesStack.indexOf(internalTexture);
  12665. if (index > -1) {
  12666. this._boundTexturesStack.splice(index, 1);
  12667. if (currentSlot > -1) {
  12668. this._boundTexturesCache[currentSlot] = null;
  12669. this._nextFreeTextureSlots.push(currentSlot);
  12670. }
  12671. }
  12672. return currentSlot;
  12673. };
  12674. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  12675. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  12676. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12677. var isTextureForRendering = texture && texture._initialSlot > -1;
  12678. if (currentTextureBound !== texture) {
  12679. if (currentTextureBound) {
  12680. this._removeDesignatedSlot(currentTextureBound);
  12681. }
  12682. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12683. if (this._activeChannel >= 0) {
  12684. this._boundTexturesCache[this._activeChannel] = texture;
  12685. if (isTextureForRendering) {
  12686. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12687. if (slotIndex > -1) {
  12688. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12689. }
  12690. this._boundTexturesStack.push(texture);
  12691. }
  12692. }
  12693. }
  12694. if (isTextureForRendering && this._activeChannel > -1) {
  12695. texture._designatedSlot = this._activeChannel;
  12696. if (!doNotBindUniformToTextureChannel) {
  12697. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12698. }
  12699. }
  12700. };
  12701. Engine.prototype._bindTexture = function (channel, texture) {
  12702. if (channel < 0) {
  12703. return;
  12704. }
  12705. if (texture) {
  12706. channel = this._getCorrectTextureChannel(channel, texture);
  12707. }
  12708. this._activateTextureChannel(channel);
  12709. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12710. };
  12711. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12712. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12713. };
  12714. Engine.prototype.unbindAllTextures = function () {
  12715. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  12716. this._activateTextureChannel(channel);
  12717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12718. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12719. if (this.webGLVersion > 1) {
  12720. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12721. }
  12722. }
  12723. };
  12724. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12725. if (channel < 0) {
  12726. return;
  12727. }
  12728. if (uniform) {
  12729. this._boundUniforms[channel] = uniform;
  12730. }
  12731. this._setTexture(channel, texture);
  12732. };
  12733. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12734. if (!internalTexture) {
  12735. return -1;
  12736. }
  12737. internalTexture._initialSlot = channel;
  12738. if (channel !== internalTexture._designatedSlot) {
  12739. if (internalTexture._designatedSlot > -1) {
  12740. return internalTexture._designatedSlot;
  12741. }
  12742. else {
  12743. // No slot for this texture, let's pick a new one (if we find a free slot)
  12744. if (this._nextFreeTextureSlots.length) {
  12745. return this._nextFreeTextureSlots[0];
  12746. }
  12747. // We need to recycle the oldest bound texture, sorry.
  12748. this._textureCollisions.addCount(1, false);
  12749. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12750. }
  12751. }
  12752. return channel;
  12753. };
  12754. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12755. var uniform = this._boundUniforms[sourceSlot];
  12756. this._gl.uniform1i(uniform, destination);
  12757. };
  12758. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12759. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12760. // Not ready?
  12761. if (!texture) {
  12762. if (this._boundTexturesCache[channel] != null) {
  12763. this._activateTextureChannel(channel);
  12764. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12765. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12766. if (this.webGLVersion > 1) {
  12767. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12768. }
  12769. }
  12770. return false;
  12771. }
  12772. // Video
  12773. var alreadyActivated = false;
  12774. if (texture.video) {
  12775. this._activateTextureChannel(channel);
  12776. alreadyActivated = true;
  12777. texture.update();
  12778. }
  12779. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12780. texture.delayLoad();
  12781. return false;
  12782. }
  12783. var internalTexture;
  12784. if (texture.isReady()) {
  12785. internalTexture = texture.getInternalTexture();
  12786. }
  12787. else if (texture.isCube) {
  12788. internalTexture = this.emptyCubeTexture;
  12789. }
  12790. else if (texture.is3D) {
  12791. internalTexture = this.emptyTexture3D;
  12792. }
  12793. else {
  12794. internalTexture = this.emptyTexture;
  12795. }
  12796. if (!isPartOfTextureArray) {
  12797. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12798. }
  12799. if (this._boundTexturesCache[channel] === internalTexture) {
  12800. this._moveBoundTextureOnTop(internalTexture);
  12801. if (!isPartOfTextureArray) {
  12802. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12803. }
  12804. return false;
  12805. }
  12806. if (!alreadyActivated) {
  12807. this._activateTextureChannel(channel);
  12808. }
  12809. if (internalTexture && internalTexture.is3D) {
  12810. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12811. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12812. internalTexture._cachedWrapU = texture.wrapU;
  12813. switch (texture.wrapU) {
  12814. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12815. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12816. break;
  12817. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12818. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12819. break;
  12820. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12821. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12822. break;
  12823. }
  12824. }
  12825. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12826. internalTexture._cachedWrapV = texture.wrapV;
  12827. switch (texture.wrapV) {
  12828. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12829. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12830. break;
  12831. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12832. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12833. break;
  12834. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12835. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12836. break;
  12837. }
  12838. }
  12839. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12840. internalTexture._cachedWrapR = texture.wrapR;
  12841. switch (texture.wrapV) {
  12842. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12843. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12844. break;
  12845. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12846. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12847. break;
  12848. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12849. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12850. break;
  12851. }
  12852. }
  12853. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12854. }
  12855. else if (internalTexture && internalTexture.isCube) {
  12856. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12857. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12858. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12859. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12860. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12861. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12862. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12863. }
  12864. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12865. }
  12866. else {
  12867. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12868. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12869. internalTexture._cachedWrapU = texture.wrapU;
  12870. switch (texture.wrapU) {
  12871. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12872. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12873. break;
  12874. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12876. break;
  12877. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12878. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12879. break;
  12880. }
  12881. }
  12882. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12883. internalTexture._cachedWrapV = texture.wrapV;
  12884. switch (texture.wrapV) {
  12885. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12886. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12887. break;
  12888. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12889. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12890. break;
  12891. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12892. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12893. break;
  12894. }
  12895. }
  12896. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12897. }
  12898. return true;
  12899. };
  12900. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12901. if (channel < 0 || !uniform) {
  12902. return;
  12903. }
  12904. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12905. this._textureUnits = new Int32Array(textures.length);
  12906. }
  12907. for (var i = 0; i < textures.length; i++) {
  12908. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12909. }
  12910. this._gl.uniform1iv(uniform, this._textureUnits);
  12911. for (var index = 0; index < textures.length; index++) {
  12912. this._setTexture(this._textureUnits[index], textures[index], true);
  12913. }
  12914. };
  12915. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12916. var internalTexture = texture.getInternalTexture();
  12917. if (!internalTexture) {
  12918. return;
  12919. }
  12920. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12921. var value = texture.anisotropicFilteringLevel;
  12922. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12923. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12924. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12925. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12926. }
  12927. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12928. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12929. internalTexture._cachedAnisotropicFilteringLevel = value;
  12930. }
  12931. };
  12932. Engine.prototype.readPixels = function (x, y, width, height) {
  12933. var data = new Uint8Array(height * width * 4);
  12934. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12935. return data;
  12936. };
  12937. /**
  12938. * Add an externaly attached data from its key.
  12939. * This method call will fail and return false, if such key already exists.
  12940. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12941. * @param key the unique key that identifies the data
  12942. * @param data the data object to associate to the key for this Engine instance
  12943. * @return true if no such key were already present and the data was added successfully, false otherwise
  12944. */
  12945. Engine.prototype.addExternalData = function (key, data) {
  12946. if (!this._externalData) {
  12947. this._externalData = new BABYLON.StringDictionary();
  12948. }
  12949. return this._externalData.add(key, data);
  12950. };
  12951. /**
  12952. * Get an externaly attached data from its key
  12953. * @param key the unique key that identifies the data
  12954. * @return the associated data, if present (can be null), or undefined if not present
  12955. */
  12956. Engine.prototype.getExternalData = function (key) {
  12957. if (!this._externalData) {
  12958. this._externalData = new BABYLON.StringDictionary();
  12959. }
  12960. return this._externalData.get(key);
  12961. };
  12962. /**
  12963. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12964. * @param key the unique key that identifies the data
  12965. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12966. * @return the associated data, can be null if the factory returned null.
  12967. */
  12968. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12969. if (!this._externalData) {
  12970. this._externalData = new BABYLON.StringDictionary();
  12971. }
  12972. return this._externalData.getOrAddWithFactory(key, factory);
  12973. };
  12974. /**
  12975. * Remove an externaly attached data from the Engine instance
  12976. * @param key the unique key that identifies the data
  12977. * @return true if the data was successfully removed, false if it doesn't exist
  12978. */
  12979. Engine.prototype.removeExternalData = function (key) {
  12980. if (!this._externalData) {
  12981. this._externalData = new BABYLON.StringDictionary();
  12982. }
  12983. return this._externalData.remove(key);
  12984. };
  12985. Engine.prototype.unbindAllAttributes = function () {
  12986. if (this._mustWipeVertexAttributes) {
  12987. this._mustWipeVertexAttributes = false;
  12988. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12989. this._gl.disableVertexAttribArray(i);
  12990. this._vertexAttribArraysEnabled[i] = false;
  12991. this._currentBufferPointers[i].active = false;
  12992. }
  12993. return;
  12994. }
  12995. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12996. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12997. continue;
  12998. }
  12999. this._gl.disableVertexAttribArray(i);
  13000. this._vertexAttribArraysEnabled[i] = false;
  13001. this._currentBufferPointers[i].active = false;
  13002. }
  13003. };
  13004. Engine.prototype.releaseEffects = function () {
  13005. for (var name in this._compiledEffects) {
  13006. this._deleteProgram(this._compiledEffects[name]._program);
  13007. }
  13008. this._compiledEffects = {};
  13009. };
  13010. // Dispose
  13011. Engine.prototype.dispose = function () {
  13012. this.hideLoadingUI();
  13013. this.stopRenderLoop();
  13014. // Release postProcesses
  13015. while (this.postProcesses.length) {
  13016. this.postProcesses[0].dispose();
  13017. }
  13018. // Empty texture
  13019. if (this._emptyTexture) {
  13020. this._releaseTexture(this._emptyTexture);
  13021. this._emptyTexture = null;
  13022. }
  13023. if (this._emptyCubeTexture) {
  13024. this._releaseTexture(this._emptyCubeTexture);
  13025. this._emptyCubeTexture = null;
  13026. }
  13027. // Rescale PP
  13028. if (this._rescalePostProcess) {
  13029. this._rescalePostProcess.dispose();
  13030. }
  13031. // Release scenes
  13032. while (this.scenes.length) {
  13033. this.scenes[0].dispose();
  13034. }
  13035. // Release audio engine
  13036. if (Engine.audioEngine) {
  13037. Engine.audioEngine.dispose();
  13038. }
  13039. // Release effects
  13040. this.releaseEffects();
  13041. // Unbind
  13042. this.unbindAllAttributes();
  13043. if (this._dummyFramebuffer) {
  13044. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13045. }
  13046. //WebVR
  13047. this.disableVR();
  13048. // Events
  13049. if (BABYLON.Tools.IsWindowObjectExist()) {
  13050. window.removeEventListener("blur", this._onBlur);
  13051. window.removeEventListener("focus", this._onFocus);
  13052. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13053. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13054. if (this._renderingCanvas) {
  13055. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13056. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13057. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13058. if (!this._doNotHandleContextLost) {
  13059. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13060. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13061. }
  13062. }
  13063. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13064. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13065. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13066. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13067. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13068. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13069. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13070. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13071. if (this._onVrDisplayConnect) {
  13072. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13073. if (this._onVrDisplayDisconnect) {
  13074. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13075. }
  13076. if (this._onVrDisplayPresentChange) {
  13077. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13078. }
  13079. this._onVrDisplayConnect = null;
  13080. this._onVrDisplayDisconnect = null;
  13081. }
  13082. }
  13083. // Remove from Instances
  13084. var index = Engine.Instances.indexOf(this);
  13085. if (index >= 0) {
  13086. Engine.Instances.splice(index, 1);
  13087. }
  13088. this._workingCanvas = null;
  13089. this._workingContext = null;
  13090. this._currentBufferPointers = [];
  13091. this._renderingCanvas = null;
  13092. this._currentProgram = null;
  13093. this.onResizeObservable.clear();
  13094. this.onCanvasBlurObservable.clear();
  13095. this.onCanvasFocusObservable.clear();
  13096. this.onCanvasPointerOutObservable.clear();
  13097. this.onBeginFrameObservable.clear();
  13098. this.onEndFrameObservable.clear();
  13099. BABYLON.Effect.ResetCache();
  13100. // Abort active requests
  13101. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13102. var request = _a[_i];
  13103. request.abort();
  13104. }
  13105. };
  13106. // Loading screen
  13107. Engine.prototype.displayLoadingUI = function () {
  13108. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13109. return;
  13110. }
  13111. var loadingScreen = this.loadingScreen;
  13112. if (loadingScreen) {
  13113. loadingScreen.displayLoadingUI();
  13114. }
  13115. };
  13116. Engine.prototype.hideLoadingUI = function () {
  13117. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13118. return;
  13119. }
  13120. var loadingScreen = this.loadingScreen;
  13121. if (loadingScreen) {
  13122. loadingScreen.hideLoadingUI();
  13123. }
  13124. };
  13125. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13126. get: function () {
  13127. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13128. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13129. return this._loadingScreen;
  13130. },
  13131. set: function (loadingScreen) {
  13132. this._loadingScreen = loadingScreen;
  13133. },
  13134. enumerable: true,
  13135. configurable: true
  13136. });
  13137. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13138. set: function (text) {
  13139. this.loadingScreen.loadingUIText = text;
  13140. },
  13141. enumerable: true,
  13142. configurable: true
  13143. });
  13144. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13145. set: function (color) {
  13146. this.loadingScreen.loadingUIBackgroundColor = color;
  13147. },
  13148. enumerable: true,
  13149. configurable: true
  13150. });
  13151. Engine.prototype.attachContextLostEvent = function (callback) {
  13152. if (this._renderingCanvas) {
  13153. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13154. }
  13155. };
  13156. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13157. if (this._renderingCanvas) {
  13158. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13159. }
  13160. };
  13161. Engine.prototype.getVertexShaderSource = function (program) {
  13162. var shaders = this._gl.getAttachedShaders(program);
  13163. if (!shaders) {
  13164. return null;
  13165. }
  13166. return this._gl.getShaderSource(shaders[0]);
  13167. };
  13168. Engine.prototype.getFragmentShaderSource = function (program) {
  13169. var shaders = this._gl.getAttachedShaders(program);
  13170. if (!shaders) {
  13171. return null;
  13172. }
  13173. return this._gl.getShaderSource(shaders[1]);
  13174. };
  13175. Engine.prototype.getError = function () {
  13176. return this._gl.getError();
  13177. };
  13178. // FPS
  13179. Engine.prototype.getFps = function () {
  13180. return this._fps;
  13181. };
  13182. Engine.prototype.getDeltaTime = function () {
  13183. return this._deltaTime;
  13184. };
  13185. Engine.prototype._measureFps = function () {
  13186. this._performanceMonitor.sampleFrame();
  13187. this._fps = this._performanceMonitor.averageFPS;
  13188. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13189. };
  13190. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13191. if (faceIndex === void 0) { faceIndex = -1; }
  13192. var gl = this._gl;
  13193. if (!this._dummyFramebuffer) {
  13194. var dummy = gl.createFramebuffer();
  13195. if (!dummy) {
  13196. throw new Error("Unable to create dummy framebuffer");
  13197. }
  13198. this._dummyFramebuffer = dummy;
  13199. }
  13200. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13201. if (faceIndex > -1) {
  13202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13203. }
  13204. else {
  13205. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13206. }
  13207. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13208. var buffer;
  13209. switch (readType) {
  13210. case gl.UNSIGNED_BYTE:
  13211. buffer = new Uint8Array(4 * width * height);
  13212. readType = gl.UNSIGNED_BYTE;
  13213. break;
  13214. default:
  13215. buffer = new Float32Array(4 * width * height);
  13216. readType = gl.FLOAT;
  13217. break;
  13218. }
  13219. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13220. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13221. return buffer;
  13222. };
  13223. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13224. if (this._webGLVersion > 1) {
  13225. return this._caps.colorBufferFloat;
  13226. }
  13227. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13228. };
  13229. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13230. if (this._webGLVersion > 1) {
  13231. return this._caps.colorBufferFloat;
  13232. }
  13233. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13234. };
  13235. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13236. Engine.prototype._canRenderToFramebuffer = function (type) {
  13237. var gl = this._gl;
  13238. //clear existing errors
  13239. while (gl.getError() !== gl.NO_ERROR) { }
  13240. var successful = true;
  13241. var texture = gl.createTexture();
  13242. gl.bindTexture(gl.TEXTURE_2D, texture);
  13243. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13246. var fb = gl.createFramebuffer();
  13247. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13248. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13249. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13250. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13251. successful = successful && (gl.getError() === gl.NO_ERROR);
  13252. //try render by clearing frame buffer's color buffer
  13253. if (successful) {
  13254. gl.clear(gl.COLOR_BUFFER_BIT);
  13255. successful = successful && (gl.getError() === gl.NO_ERROR);
  13256. }
  13257. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13258. if (successful) {
  13259. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13260. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13261. var readFormat = gl.RGBA;
  13262. var readType = gl.UNSIGNED_BYTE;
  13263. var buffer = new Uint8Array(4);
  13264. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13265. successful = successful && (gl.getError() === gl.NO_ERROR);
  13266. }
  13267. //clean up
  13268. gl.deleteTexture(texture);
  13269. gl.deleteFramebuffer(fb);
  13270. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13271. //clear accumulated errors
  13272. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13273. return successful;
  13274. };
  13275. Engine.prototype._getWebGLTextureType = function (type) {
  13276. if (type === Engine.TEXTURETYPE_FLOAT) {
  13277. return this._gl.FLOAT;
  13278. }
  13279. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13280. // Add Half Float Constant.
  13281. return this._gl.HALF_FLOAT_OES;
  13282. }
  13283. return this._gl.UNSIGNED_BYTE;
  13284. };
  13285. ;
  13286. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13287. if (this._webGLVersion === 1) {
  13288. return this._gl.RGBA;
  13289. }
  13290. if (type === Engine.TEXTURETYPE_FLOAT) {
  13291. return this._gl.RGBA32F;
  13292. }
  13293. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13294. return this._gl.RGBA16F;
  13295. }
  13296. return this._gl.RGBA;
  13297. };
  13298. ;
  13299. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13300. if (type === Engine.TEXTURETYPE_FLOAT) {
  13301. return this._gl.RGBA32F;
  13302. }
  13303. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13304. return this._gl.RGBA16F;
  13305. }
  13306. return this._gl.RGBA8;
  13307. };
  13308. ;
  13309. Engine.prototype.createQuery = function () {
  13310. return this._gl.createQuery();
  13311. };
  13312. Engine.prototype.deleteQuery = function (query) {
  13313. this._gl.deleteQuery(query);
  13314. return this;
  13315. };
  13316. Engine.prototype.isQueryResultAvailable = function (query) {
  13317. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13318. };
  13319. Engine.prototype.getQueryResult = function (query) {
  13320. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13321. };
  13322. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13323. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13324. this._gl.beginQuery(glAlgorithm, query);
  13325. return this;
  13326. };
  13327. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13328. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13329. this._gl.endQuery(glAlgorithm);
  13330. return this;
  13331. };
  13332. /* Time queries */
  13333. Engine.prototype._createTimeQuery = function () {
  13334. var timerQuery = this._caps.timerQuery;
  13335. if (timerQuery.createQueryEXT) {
  13336. return timerQuery.createQueryEXT();
  13337. }
  13338. return this.createQuery();
  13339. };
  13340. Engine.prototype._deleteTimeQuery = function (query) {
  13341. var timerQuery = this._caps.timerQuery;
  13342. if (timerQuery.deleteQueryEXT) {
  13343. timerQuery.deleteQueryEXT(query);
  13344. return;
  13345. }
  13346. this.deleteQuery(query);
  13347. };
  13348. Engine.prototype._getTimeQueryResult = function (query) {
  13349. var timerQuery = this._caps.timerQuery;
  13350. if (timerQuery.getQueryObjectEXT) {
  13351. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13352. }
  13353. return this.getQueryResult(query);
  13354. };
  13355. Engine.prototype._getTimeQueryAvailability = function (query) {
  13356. var timerQuery = this._caps.timerQuery;
  13357. if (timerQuery.getQueryObjectEXT) {
  13358. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13359. }
  13360. return this.isQueryResultAvailable(query);
  13361. };
  13362. Engine.prototype.startTimeQuery = function () {
  13363. var timerQuery = this._caps.timerQuery;
  13364. if (!timerQuery) {
  13365. return null;
  13366. }
  13367. var token = new BABYLON._TimeToken();
  13368. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13369. if (this._caps.canUseTimestampForTimerQuery) {
  13370. token._startTimeQuery = this._createTimeQuery();
  13371. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13372. }
  13373. else {
  13374. if (this._currentNonTimestampToken) {
  13375. return this._currentNonTimestampToken;
  13376. }
  13377. token._timeElapsedQuery = this._createTimeQuery();
  13378. if (timerQuery.beginQueryEXT) {
  13379. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13380. }
  13381. else {
  13382. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13383. }
  13384. this._currentNonTimestampToken = token;
  13385. }
  13386. return token;
  13387. };
  13388. Engine.prototype.endTimeQuery = function (token) {
  13389. var timerQuery = this._caps.timerQuery;
  13390. if (!timerQuery || !token) {
  13391. return -1;
  13392. }
  13393. if (this._caps.canUseTimestampForTimerQuery) {
  13394. if (!token._startTimeQuery) {
  13395. return -1;
  13396. }
  13397. if (!token._endTimeQuery) {
  13398. token._endTimeQuery = this._createTimeQuery();
  13399. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13400. }
  13401. }
  13402. else if (!token._timeElapsedQueryEnded) {
  13403. if (!token._timeElapsedQuery) {
  13404. return -1;
  13405. }
  13406. if (timerQuery.endQueryEXT) {
  13407. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13408. }
  13409. else {
  13410. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13411. }
  13412. token._timeElapsedQueryEnded = true;
  13413. }
  13414. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13415. var available = false;
  13416. if (token._endTimeQuery) {
  13417. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13418. }
  13419. else if (token._timeElapsedQuery) {
  13420. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13421. }
  13422. if (available && !disjoint) {
  13423. var result = 0;
  13424. if (this._caps.canUseTimestampForTimerQuery) {
  13425. if (!token._startTimeQuery || !token._endTimeQuery) {
  13426. return -1;
  13427. }
  13428. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13429. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13430. result = timeEnd - timeStart;
  13431. this._deleteTimeQuery(token._startTimeQuery);
  13432. this._deleteTimeQuery(token._endTimeQuery);
  13433. token._startTimeQuery = null;
  13434. token._endTimeQuery = null;
  13435. }
  13436. else {
  13437. if (!token._timeElapsedQuery) {
  13438. return -1;
  13439. }
  13440. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13441. this._deleteTimeQuery(token._timeElapsedQuery);
  13442. token._timeElapsedQuery = null;
  13443. token._timeElapsedQueryEnded = false;
  13444. this._currentNonTimestampToken = null;
  13445. }
  13446. return result;
  13447. }
  13448. return -1;
  13449. };
  13450. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13451. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13452. };
  13453. // Transform feedback
  13454. Engine.prototype.createTransformFeedback = function () {
  13455. return this._gl.createTransformFeedback();
  13456. };
  13457. Engine.prototype.deleteTransformFeedback = function (value) {
  13458. this._gl.deleteTransformFeedback(value);
  13459. };
  13460. Engine.prototype.bindTransformFeedback = function (value) {
  13461. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13462. };
  13463. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13464. if (usePoints === void 0) { usePoints = true; }
  13465. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13466. };
  13467. Engine.prototype.endTransformFeedback = function () {
  13468. this._gl.endTransformFeedback();
  13469. };
  13470. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13471. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13472. };
  13473. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13474. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13475. };
  13476. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13477. var _this = this;
  13478. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13479. this._activeRequests.push(request);
  13480. request.onCompleteObservable.add(function (request) {
  13481. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13482. });
  13483. return request;
  13484. };
  13485. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13486. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13487. var onload = function (data) {
  13488. loadedFiles[index] = data;
  13489. loadedFiles._internalCount++;
  13490. if (loadedFiles._internalCount === 6) {
  13491. onfinish(loadedFiles);
  13492. }
  13493. };
  13494. var onerror = function (request, exception) {
  13495. if (onErrorCallBack && request) {
  13496. onErrorCallBack(request.status + " " + request.statusText, exception);
  13497. }
  13498. };
  13499. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13500. };
  13501. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13502. if (onError === void 0) { onError = null; }
  13503. var loadedFiles = [];
  13504. loadedFiles._internalCount = 0;
  13505. for (var index = 0; index < 6; index++) {
  13506. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13507. }
  13508. };
  13509. // Statics
  13510. Engine.isSupported = function () {
  13511. try {
  13512. var tempcanvas = document.createElement("canvas");
  13513. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13514. return gl != null && !!window.WebGLRenderingContext;
  13515. }
  13516. catch (e) {
  13517. return false;
  13518. }
  13519. };
  13520. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13521. Engine.ExceptionList = [
  13522. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13523. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }
  13524. ];
  13525. Engine.Instances = new Array();
  13526. // Const statics
  13527. Engine._ALPHA_DISABLE = 0;
  13528. Engine._ALPHA_ADD = 1;
  13529. Engine._ALPHA_COMBINE = 2;
  13530. Engine._ALPHA_SUBTRACT = 3;
  13531. Engine._ALPHA_MULTIPLY = 4;
  13532. Engine._ALPHA_MAXIMIZED = 5;
  13533. Engine._ALPHA_ONEONE = 6;
  13534. Engine._ALPHA_PREMULTIPLIED = 7;
  13535. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13536. Engine._ALPHA_INTERPOLATE = 9;
  13537. Engine._ALPHA_SCREENMODE = 10;
  13538. Engine._DELAYLOADSTATE_NONE = 0;
  13539. Engine._DELAYLOADSTATE_LOADED = 1;
  13540. Engine._DELAYLOADSTATE_LOADING = 2;
  13541. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13542. Engine._TEXTUREFORMAT_ALPHA = 0;
  13543. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13544. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13545. Engine._TEXTUREFORMAT_RGB = 4;
  13546. Engine._TEXTUREFORMAT_RGBA = 5;
  13547. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13548. Engine._TEXTURETYPE_FLOAT = 1;
  13549. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13550. // Depht or Stencil test Constants.
  13551. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13552. 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.
  13553. 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.
  13554. 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.
  13555. 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.
  13556. 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.
  13557. 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.
  13558. 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.
  13559. // Stencil Actions Constants.
  13560. Engine._KEEP = 0x1E00;
  13561. Engine._REPLACE = 0x1E01;
  13562. Engine._INCR = 0x1E02;
  13563. Engine._DECR = 0x1E03;
  13564. Engine._INVERT = 0x150A;
  13565. Engine._INCR_WRAP = 0x8507;
  13566. Engine._DECR_WRAP = 0x8508;
  13567. // Texture rescaling mode
  13568. Engine._SCALEMODE_FLOOR = 1;
  13569. Engine._SCALEMODE_NEAREST = 2;
  13570. Engine._SCALEMODE_CEILING = 3;
  13571. // Updatable statics so stick with vars here
  13572. Engine.CollisionsEpsilon = 0.001;
  13573. Engine.CodeRepository = "src/";
  13574. Engine.ShadersRepository = "src/Shaders/";
  13575. return Engine;
  13576. }());
  13577. BABYLON.Engine = Engine;
  13578. })(BABYLON || (BABYLON = {}));
  13579. //# sourceMappingURL=babylon.engine.js.map
  13580. var BABYLON;
  13581. (function (BABYLON) {
  13582. /**
  13583. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13584. */
  13585. var Node = /** @class */ (function () {
  13586. /**
  13587. * @constructor
  13588. * @param {string} name - the name and id to be given to this node
  13589. * @param {BABYLON.Scene} the scene this node will be added to
  13590. */
  13591. function Node(name, scene) {
  13592. if (scene === void 0) { scene = null; }
  13593. this.state = "";
  13594. this.metadata = null;
  13595. this.doNotSerialize = false;
  13596. this.animations = new Array();
  13597. this._ranges = {};
  13598. this._isEnabled = true;
  13599. this._isReady = true;
  13600. this._currentRenderId = -1;
  13601. this._parentRenderId = -1;
  13602. /**
  13603. * An event triggered when the mesh is disposed.
  13604. * @type {BABYLON.Observable}
  13605. */
  13606. this.onDisposeObservable = new BABYLON.Observable();
  13607. // Behaviors
  13608. this._behaviors = new Array();
  13609. this.name = name;
  13610. this.id = name;
  13611. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13612. this.uniqueId = this._scene.getUniqueId();
  13613. this._initCache();
  13614. }
  13615. Object.defineProperty(Node.prototype, "parent", {
  13616. get: function () {
  13617. return this._parentNode;
  13618. },
  13619. set: function (parent) {
  13620. if (this._parentNode === parent) {
  13621. return;
  13622. }
  13623. // Remove self from list of children of parent
  13624. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13625. var index = this._parentNode._children.indexOf(this);
  13626. if (index !== -1) {
  13627. this._parentNode._children.splice(index, 1);
  13628. }
  13629. }
  13630. // Store new parent
  13631. this._parentNode = parent;
  13632. // Add as child to new parent
  13633. if (this._parentNode) {
  13634. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13635. this._parentNode._children = new Array();
  13636. }
  13637. this._parentNode._children.push(this);
  13638. }
  13639. },
  13640. enumerable: true,
  13641. configurable: true
  13642. });
  13643. Node.prototype.getClassName = function () {
  13644. return "Node";
  13645. };
  13646. Object.defineProperty(Node.prototype, "onDispose", {
  13647. set: function (callback) {
  13648. if (this._onDisposeObserver) {
  13649. this.onDisposeObservable.remove(this._onDisposeObserver);
  13650. }
  13651. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13652. },
  13653. enumerable: true,
  13654. configurable: true
  13655. });
  13656. Node.prototype.getScene = function () {
  13657. return this._scene;
  13658. };
  13659. Node.prototype.getEngine = function () {
  13660. return this._scene.getEngine();
  13661. };
  13662. Node.prototype.addBehavior = function (behavior) {
  13663. var _this = this;
  13664. var index = this._behaviors.indexOf(behavior);
  13665. if (index !== -1) {
  13666. return this;
  13667. }
  13668. behavior.init();
  13669. if (this._scene.isLoading) {
  13670. // We defer the attach when the scene will be loaded
  13671. var observer = this._scene.onDataLoadedObservable.add(function () {
  13672. behavior.attach(_this);
  13673. setTimeout(function () {
  13674. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13675. _this._scene.onDataLoadedObservable.remove(observer);
  13676. }, 0);
  13677. });
  13678. }
  13679. else {
  13680. behavior.attach(this);
  13681. }
  13682. this._behaviors.push(behavior);
  13683. return this;
  13684. };
  13685. Node.prototype.removeBehavior = function (behavior) {
  13686. var index = this._behaviors.indexOf(behavior);
  13687. if (index === -1) {
  13688. return this;
  13689. }
  13690. this._behaviors[index].detach();
  13691. this._behaviors.splice(index, 1);
  13692. return this;
  13693. };
  13694. Object.defineProperty(Node.prototype, "behaviors", {
  13695. get: function () {
  13696. return this._behaviors;
  13697. },
  13698. enumerable: true,
  13699. configurable: true
  13700. });
  13701. Node.prototype.getBehaviorByName = function (name) {
  13702. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13703. var behavior = _a[_i];
  13704. if (behavior.name === name) {
  13705. return behavior;
  13706. }
  13707. }
  13708. return null;
  13709. };
  13710. // override it in derived class
  13711. Node.prototype.getWorldMatrix = function () {
  13712. return BABYLON.Matrix.Identity();
  13713. };
  13714. // override it in derived class if you add new variables to the cache
  13715. // and call the parent class method
  13716. Node.prototype._initCache = function () {
  13717. this._cache = {};
  13718. this._cache.parent = undefined;
  13719. };
  13720. Node.prototype.updateCache = function (force) {
  13721. if (!force && this.isSynchronized())
  13722. return;
  13723. this._cache.parent = this.parent;
  13724. this._updateCache();
  13725. };
  13726. // override it in derived class if you add new variables to the cache
  13727. // and call the parent class method if !ignoreParentClass
  13728. Node.prototype._updateCache = function (ignoreParentClass) {
  13729. };
  13730. // override it in derived class if you add new variables to the cache
  13731. Node.prototype._isSynchronized = function () {
  13732. return true;
  13733. };
  13734. Node.prototype._markSyncedWithParent = function () {
  13735. if (this.parent) {
  13736. this._parentRenderId = this.parent._currentRenderId;
  13737. }
  13738. };
  13739. Node.prototype.isSynchronizedWithParent = function () {
  13740. if (!this.parent) {
  13741. return true;
  13742. }
  13743. if (this._parentRenderId !== this.parent._currentRenderId) {
  13744. return false;
  13745. }
  13746. return this.parent.isSynchronized();
  13747. };
  13748. Node.prototype.isSynchronized = function (updateCache) {
  13749. var check = this.hasNewParent();
  13750. check = check || !this.isSynchronizedWithParent();
  13751. check = check || !this._isSynchronized();
  13752. if (updateCache)
  13753. this.updateCache(true);
  13754. return !check;
  13755. };
  13756. Node.prototype.hasNewParent = function (update) {
  13757. if (this._cache.parent === this.parent)
  13758. return false;
  13759. if (update)
  13760. this._cache.parent = this.parent;
  13761. return true;
  13762. };
  13763. /**
  13764. * Is this node ready to be used/rendered
  13765. * @return {boolean} is it ready
  13766. */
  13767. Node.prototype.isReady = function () {
  13768. return this._isReady;
  13769. };
  13770. /**
  13771. * Is this node enabled.
  13772. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  13773. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13774. * @return {boolean} whether this node (and its parent) is enabled.
  13775. * @see setEnabled
  13776. */
  13777. Node.prototype.isEnabled = function (checkAncestors) {
  13778. if (checkAncestors === void 0) { checkAncestors = true; }
  13779. if (checkAncestors === false) {
  13780. return this._isEnabled;
  13781. }
  13782. if (this._isEnabled === false) {
  13783. return false;
  13784. }
  13785. if (this.parent !== undefined && this.parent !== null) {
  13786. return this.parent.isEnabled(checkAncestors);
  13787. }
  13788. return true;
  13789. };
  13790. /**
  13791. * Set the enabled state of this node.
  13792. * @param {boolean} value - the new enabled state
  13793. * @see isEnabled
  13794. */
  13795. Node.prototype.setEnabled = function (value) {
  13796. this._isEnabled = value;
  13797. };
  13798. /**
  13799. * Is this node a descendant of the given node.
  13800. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13801. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13802. * @see parent
  13803. */
  13804. Node.prototype.isDescendantOf = function (ancestor) {
  13805. if (this.parent) {
  13806. if (this.parent === ancestor) {
  13807. return true;
  13808. }
  13809. return this.parent.isDescendantOf(ancestor);
  13810. }
  13811. return false;
  13812. };
  13813. /**
  13814. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13815. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13816. * @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.
  13817. * @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.
  13818. */
  13819. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13820. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13821. if (!this._children) {
  13822. return;
  13823. }
  13824. for (var index = 0; index < this._children.length; index++) {
  13825. var item = this._children[index];
  13826. if (!predicate || predicate(item)) {
  13827. results.push(item);
  13828. }
  13829. if (!directDescendantsOnly) {
  13830. item._getDescendants(results, false, predicate);
  13831. }
  13832. }
  13833. };
  13834. /**
  13835. * Will return all nodes that have this node as ascendant.
  13836. * @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.
  13837. * @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.
  13838. * @return {BABYLON.Node[]} all children nodes of all types.
  13839. */
  13840. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13841. var results = new Array();
  13842. this._getDescendants(results, directDescendantsOnly, predicate);
  13843. return results;
  13844. };
  13845. /**
  13846. * Get all child-meshes of this node.
  13847. */
  13848. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13849. var results = [];
  13850. this._getDescendants(results, directDescendantsOnly, function (node) {
  13851. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13852. });
  13853. return results;
  13854. };
  13855. /**
  13856. * Get all child-transformNodes of this node.
  13857. */
  13858. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13859. var results = [];
  13860. this._getDescendants(results, directDescendantsOnly, function (node) {
  13861. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13862. });
  13863. return results;
  13864. };
  13865. /**
  13866. * Get all direct children of this node.
  13867. */
  13868. Node.prototype.getChildren = function (predicate) {
  13869. return this.getDescendants(true, predicate);
  13870. };
  13871. Node.prototype._setReady = function (state) {
  13872. if (state === this._isReady) {
  13873. return;
  13874. }
  13875. if (!state) {
  13876. this._isReady = false;
  13877. return;
  13878. }
  13879. this._isReady = true;
  13880. if (this.onReady) {
  13881. this.onReady(this);
  13882. }
  13883. };
  13884. Node.prototype.getAnimationByName = function (name) {
  13885. for (var i = 0; i < this.animations.length; i++) {
  13886. var animation = this.animations[i];
  13887. if (animation.name === name) {
  13888. return animation;
  13889. }
  13890. }
  13891. return null;
  13892. };
  13893. Node.prototype.createAnimationRange = function (name, from, to) {
  13894. // check name not already in use
  13895. if (!this._ranges[name]) {
  13896. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13897. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13898. if (this.animations[i]) {
  13899. this.animations[i].createRange(name, from, to);
  13900. }
  13901. }
  13902. }
  13903. };
  13904. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13905. if (deleteFrames === void 0) { deleteFrames = true; }
  13906. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13907. if (this.animations[i]) {
  13908. this.animations[i].deleteRange(name, deleteFrames);
  13909. }
  13910. }
  13911. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13912. };
  13913. Node.prototype.getAnimationRange = function (name) {
  13914. return this._ranges[name];
  13915. };
  13916. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13917. var range = this.getAnimationRange(name);
  13918. if (!range) {
  13919. return;
  13920. }
  13921. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13922. };
  13923. Node.prototype.serializeAnimationRanges = function () {
  13924. var serializationRanges = [];
  13925. for (var name in this._ranges) {
  13926. var localRange = this._ranges[name];
  13927. if (!localRange) {
  13928. continue;
  13929. }
  13930. var range = {};
  13931. range.name = name;
  13932. range.from = localRange.from;
  13933. range.to = localRange.to;
  13934. serializationRanges.push(range);
  13935. }
  13936. return serializationRanges;
  13937. };
  13938. // override it in derived class
  13939. Node.prototype.computeWorldMatrix = function (force) {
  13940. return BABYLON.Matrix.Identity();
  13941. };
  13942. Node.prototype.dispose = function () {
  13943. this.parent = null;
  13944. // Callback
  13945. this.onDisposeObservable.notifyObservers(this);
  13946. this.onDisposeObservable.clear();
  13947. // Behaviors
  13948. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13949. var behavior = _a[_i];
  13950. behavior.detach();
  13951. }
  13952. this._behaviors = [];
  13953. };
  13954. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13955. if (parsedNode.ranges) {
  13956. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13957. var data = parsedNode.ranges[index];
  13958. node.createAnimationRange(data.name, data.from, data.to);
  13959. }
  13960. }
  13961. };
  13962. __decorate([
  13963. BABYLON.serialize()
  13964. ], Node.prototype, "name", void 0);
  13965. __decorate([
  13966. BABYLON.serialize()
  13967. ], Node.prototype, "id", void 0);
  13968. __decorate([
  13969. BABYLON.serialize()
  13970. ], Node.prototype, "uniqueId", void 0);
  13971. __decorate([
  13972. BABYLON.serialize()
  13973. ], Node.prototype, "state", void 0);
  13974. __decorate([
  13975. BABYLON.serialize()
  13976. ], Node.prototype, "metadata", void 0);
  13977. return Node;
  13978. }());
  13979. BABYLON.Node = Node;
  13980. })(BABYLON || (BABYLON = {}));
  13981. //# sourceMappingURL=babylon.node.js.map
  13982. var BABYLON;
  13983. (function (BABYLON) {
  13984. var BoundingSphere = /** @class */ (function () {
  13985. function BoundingSphere(minimum, maximum) {
  13986. this.minimum = minimum;
  13987. this.maximum = maximum;
  13988. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13989. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13990. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13991. this.radius = distance * 0.5;
  13992. this.centerWorld = BABYLON.Vector3.Zero();
  13993. this._update(BABYLON.Matrix.Identity());
  13994. }
  13995. // Methods
  13996. BoundingSphere.prototype._update = function (world) {
  13997. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13998. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13999. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14000. };
  14001. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14002. for (var i = 0; i < 6; i++) {
  14003. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14004. return false;
  14005. }
  14006. return true;
  14007. };
  14008. BoundingSphere.prototype.intersectsPoint = function (point) {
  14009. var x = this.centerWorld.x - point.x;
  14010. var y = this.centerWorld.y - point.y;
  14011. var z = this.centerWorld.z - point.z;
  14012. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14013. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14014. return false;
  14015. return true;
  14016. };
  14017. // Statics
  14018. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14019. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14020. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14021. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14022. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14023. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14024. return false;
  14025. return true;
  14026. };
  14027. return BoundingSphere;
  14028. }());
  14029. BABYLON.BoundingSphere = BoundingSphere;
  14030. })(BABYLON || (BABYLON = {}));
  14031. //# sourceMappingURL=babylon.boundingSphere.js.map
  14032. var BABYLON;
  14033. (function (BABYLON) {
  14034. var BoundingBox = /** @class */ (function () {
  14035. function BoundingBox(minimum, maximum) {
  14036. this.minimum = minimum;
  14037. this.maximum = maximum;
  14038. this.vectors = new Array();
  14039. this.vectorsWorld = new Array();
  14040. // Bounding vectors
  14041. this.vectors.push(this.minimum.clone());
  14042. this.vectors.push(this.maximum.clone());
  14043. this.vectors.push(this.minimum.clone());
  14044. this.vectors[2].x = this.maximum.x;
  14045. this.vectors.push(this.minimum.clone());
  14046. this.vectors[3].y = this.maximum.y;
  14047. this.vectors.push(this.minimum.clone());
  14048. this.vectors[4].z = this.maximum.z;
  14049. this.vectors.push(this.maximum.clone());
  14050. this.vectors[5].z = this.minimum.z;
  14051. this.vectors.push(this.maximum.clone());
  14052. this.vectors[6].x = this.minimum.x;
  14053. this.vectors.push(this.maximum.clone());
  14054. this.vectors[7].y = this.minimum.y;
  14055. // OBB
  14056. this.center = this.maximum.add(this.minimum).scale(0.5);
  14057. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14058. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14059. // World
  14060. for (var index = 0; index < this.vectors.length; index++) {
  14061. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14062. }
  14063. this.minimumWorld = BABYLON.Vector3.Zero();
  14064. this.maximumWorld = BABYLON.Vector3.Zero();
  14065. this.centerWorld = BABYLON.Vector3.Zero();
  14066. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14067. this._update(BABYLON.Matrix.Identity());
  14068. }
  14069. // Methods
  14070. BoundingBox.prototype.getWorldMatrix = function () {
  14071. return this._worldMatrix;
  14072. };
  14073. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14074. this._worldMatrix.copyFrom(matrix);
  14075. return this;
  14076. };
  14077. BoundingBox.prototype._update = function (world) {
  14078. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14079. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14080. for (var index = 0; index < this.vectors.length; index++) {
  14081. var v = this.vectorsWorld[index];
  14082. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14083. if (v.x < this.minimumWorld.x)
  14084. this.minimumWorld.x = v.x;
  14085. if (v.y < this.minimumWorld.y)
  14086. this.minimumWorld.y = v.y;
  14087. if (v.z < this.minimumWorld.z)
  14088. this.minimumWorld.z = v.z;
  14089. if (v.x > this.maximumWorld.x)
  14090. this.maximumWorld.x = v.x;
  14091. if (v.y > this.maximumWorld.y)
  14092. this.maximumWorld.y = v.y;
  14093. if (v.z > this.maximumWorld.z)
  14094. this.maximumWorld.z = v.z;
  14095. }
  14096. // Extend
  14097. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14098. this.extendSizeWorld.scaleInPlace(0.5);
  14099. // OBB
  14100. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14101. this.centerWorld.scaleInPlace(0.5);
  14102. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14103. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14104. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14105. this._worldMatrix = world;
  14106. };
  14107. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14108. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14109. };
  14110. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14111. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14112. };
  14113. BoundingBox.prototype.intersectsPoint = function (point) {
  14114. var delta = -BABYLON.Epsilon;
  14115. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14116. return false;
  14117. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14118. return false;
  14119. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14120. return false;
  14121. return true;
  14122. };
  14123. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14124. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14125. };
  14126. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14127. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14128. return false;
  14129. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14130. return false;
  14131. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14132. return false;
  14133. return true;
  14134. };
  14135. // Statics
  14136. BoundingBox.Intersects = function (box0, box1) {
  14137. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14138. return false;
  14139. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14140. return false;
  14141. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14142. return false;
  14143. return true;
  14144. };
  14145. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14146. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14147. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14148. return (num <= (sphereRadius * sphereRadius));
  14149. };
  14150. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14151. for (var p = 0; p < 6; p++) {
  14152. for (var i = 0; i < 8; i++) {
  14153. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14154. return false;
  14155. }
  14156. }
  14157. }
  14158. return true;
  14159. };
  14160. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14161. for (var p = 0; p < 6; p++) {
  14162. var inCount = 8;
  14163. for (var i = 0; i < 8; i++) {
  14164. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14165. --inCount;
  14166. }
  14167. else {
  14168. break;
  14169. }
  14170. }
  14171. if (inCount === 0)
  14172. return false;
  14173. }
  14174. return true;
  14175. };
  14176. return BoundingBox;
  14177. }());
  14178. BABYLON.BoundingBox = BoundingBox;
  14179. })(BABYLON || (BABYLON = {}));
  14180. //# sourceMappingURL=babylon.boundingBox.js.map
  14181. var BABYLON;
  14182. (function (BABYLON) {
  14183. var computeBoxExtents = function (axis, box) {
  14184. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14185. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14186. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14187. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14188. var r = r0 + r1 + r2;
  14189. return {
  14190. min: p - r,
  14191. max: p + r
  14192. };
  14193. };
  14194. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14195. var axisOverlap = function (axis, box0, box1) {
  14196. var result0 = computeBoxExtents(axis, box0);
  14197. var result1 = computeBoxExtents(axis, box1);
  14198. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14199. };
  14200. var BoundingInfo = /** @class */ (function () {
  14201. function BoundingInfo(minimum, maximum) {
  14202. this.minimum = minimum;
  14203. this.maximum = maximum;
  14204. this._isLocked = false;
  14205. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14206. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14207. }
  14208. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14209. get: function () {
  14210. return this._isLocked;
  14211. },
  14212. set: function (value) {
  14213. this._isLocked = value;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. // Methods
  14219. BoundingInfo.prototype.update = function (world) {
  14220. if (this._isLocked) {
  14221. return;
  14222. }
  14223. this.boundingBox._update(world);
  14224. this.boundingSphere._update(world);
  14225. };
  14226. /**
  14227. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14228. * @param center New center of the bounding info
  14229. * @param extend New extend of the bounding info
  14230. */
  14231. BoundingInfo.prototype.centerOn = function (center, extend) {
  14232. this.minimum = center.subtract(extend);
  14233. this.maximum = center.add(extend);
  14234. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14235. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14236. return this;
  14237. };
  14238. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14239. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14240. return false;
  14241. return this.boundingBox.isInFrustum(frustumPlanes);
  14242. };
  14243. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14244. /**
  14245. * Gets the world distance between the min and max points of the bounding box
  14246. */
  14247. get: function () {
  14248. var boundingBox = this.boundingBox;
  14249. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14250. return size.length();
  14251. },
  14252. enumerable: true,
  14253. configurable: true
  14254. });
  14255. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14256. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14257. };
  14258. BoundingInfo.prototype._checkCollision = function (collider) {
  14259. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14260. };
  14261. BoundingInfo.prototype.intersectsPoint = function (point) {
  14262. if (!this.boundingSphere.centerWorld) {
  14263. return false;
  14264. }
  14265. if (!this.boundingSphere.intersectsPoint(point)) {
  14266. return false;
  14267. }
  14268. if (!this.boundingBox.intersectsPoint(point)) {
  14269. return false;
  14270. }
  14271. return true;
  14272. };
  14273. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14274. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14275. return false;
  14276. }
  14277. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14278. return false;
  14279. }
  14280. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14281. return false;
  14282. }
  14283. if (!precise) {
  14284. return true;
  14285. }
  14286. var box0 = this.boundingBox;
  14287. var box1 = boundingInfo.boundingBox;
  14288. if (!axisOverlap(box0.directions[0], box0, box1))
  14289. return false;
  14290. if (!axisOverlap(box0.directions[1], box0, box1))
  14291. return false;
  14292. if (!axisOverlap(box0.directions[2], box0, box1))
  14293. return false;
  14294. if (!axisOverlap(box1.directions[0], box0, box1))
  14295. return false;
  14296. if (!axisOverlap(box1.directions[1], box0, box1))
  14297. return false;
  14298. if (!axisOverlap(box1.directions[2], box0, box1))
  14299. return false;
  14300. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14301. return false;
  14302. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14303. return false;
  14304. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14305. return false;
  14306. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14307. return false;
  14308. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14309. return false;
  14310. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14311. return false;
  14312. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14313. return false;
  14314. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14315. return false;
  14316. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14317. return false;
  14318. return true;
  14319. };
  14320. return BoundingInfo;
  14321. }());
  14322. BABYLON.BoundingInfo = BoundingInfo;
  14323. })(BABYLON || (BABYLON = {}));
  14324. //# sourceMappingURL=babylon.boundingInfo.js.map
  14325. var BABYLON;
  14326. (function (BABYLON) {
  14327. var TransformNode = /** @class */ (function (_super) {
  14328. __extends(TransformNode, _super);
  14329. function TransformNode(name, scene, isPure) {
  14330. if (scene === void 0) { scene = null; }
  14331. if (isPure === void 0) { isPure = true; }
  14332. var _this = _super.call(this, name, scene) || this;
  14333. // Properties
  14334. _this._rotation = BABYLON.Vector3.Zero();
  14335. _this._scaling = BABYLON.Vector3.One();
  14336. _this._isDirty = false;
  14337. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14338. _this.scalingDeterminant = 1;
  14339. _this.infiniteDistance = false;
  14340. _this.position = BABYLON.Vector3.Zero();
  14341. _this._localWorld = BABYLON.Matrix.Zero();
  14342. _this._worldMatrix = BABYLON.Matrix.Zero();
  14343. _this._worldMatrixDeterminant = 0;
  14344. _this._absolutePosition = BABYLON.Vector3.Zero();
  14345. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14346. _this._postMultiplyPivotMatrix = false;
  14347. _this._isWorldMatrixFrozen = false;
  14348. /**
  14349. * An event triggered after the world matrix is updated
  14350. * @type {BABYLON.Observable}
  14351. */
  14352. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14353. _this._nonUniformScaling = false;
  14354. if (isPure) {
  14355. _this.getScene().addTransformNode(_this);
  14356. }
  14357. return _this;
  14358. }
  14359. Object.defineProperty(TransformNode.prototype, "rotation", {
  14360. /**
  14361. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14362. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14363. * Default : (0.0, 0.0, 0.0)
  14364. */
  14365. get: function () {
  14366. return this._rotation;
  14367. },
  14368. set: function (newRotation) {
  14369. this._rotation = newRotation;
  14370. },
  14371. enumerable: true,
  14372. configurable: true
  14373. });
  14374. Object.defineProperty(TransformNode.prototype, "scaling", {
  14375. /**
  14376. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14377. * Default : (1.0, 1.0, 1.0)
  14378. */
  14379. get: function () {
  14380. return this._scaling;
  14381. },
  14382. /**
  14383. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14384. * Default : (1.0, 1.0, 1.0)
  14385. */
  14386. set: function (newScaling) {
  14387. this._scaling = newScaling;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14393. /**
  14394. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14395. * It's null by default.
  14396. * 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)
  14397. */
  14398. get: function () {
  14399. return this._rotationQuaternion;
  14400. },
  14401. set: function (quaternion) {
  14402. this._rotationQuaternion = quaternion;
  14403. //reset the rotation vector.
  14404. if (quaternion && this.rotation.length()) {
  14405. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14406. }
  14407. },
  14408. enumerable: true,
  14409. configurable: true
  14410. });
  14411. /**
  14412. * Returns the latest update of the World matrix
  14413. * Returns a Matrix.
  14414. */
  14415. TransformNode.prototype.getWorldMatrix = function () {
  14416. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14417. this.computeWorldMatrix();
  14418. }
  14419. return this._worldMatrix;
  14420. };
  14421. /**
  14422. * Returns the latest update of the World matrix determinant.
  14423. */
  14424. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14425. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14426. this.computeWorldMatrix();
  14427. }
  14428. return this._worldMatrixDeterminant;
  14429. };
  14430. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14431. /**
  14432. * Returns directly the latest state of the mesh World matrix.
  14433. * A Matrix is returned.
  14434. */
  14435. get: function () {
  14436. return this._worldMatrix;
  14437. },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. /**
  14442. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14443. * Returns the AbstractMesh.
  14444. */
  14445. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14446. this._poseMatrix.copyFrom(matrix);
  14447. return this;
  14448. };
  14449. /**
  14450. * Returns the mesh Pose matrix.
  14451. * Returned object : Matrix
  14452. */
  14453. TransformNode.prototype.getPoseMatrix = function () {
  14454. return this._poseMatrix;
  14455. };
  14456. TransformNode.prototype._isSynchronized = function () {
  14457. if (this._isDirty) {
  14458. return false;
  14459. }
  14460. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14461. return false;
  14462. if (this._cache.pivotMatrixUpdated) {
  14463. return false;
  14464. }
  14465. if (this.infiniteDistance) {
  14466. return false;
  14467. }
  14468. if (!this._cache.position.equals(this.position))
  14469. return false;
  14470. if (this.rotationQuaternion) {
  14471. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14472. return false;
  14473. }
  14474. if (!this._cache.rotation.equals(this.rotation))
  14475. return false;
  14476. if (!this._cache.scaling.equals(this.scaling))
  14477. return false;
  14478. return true;
  14479. };
  14480. TransformNode.prototype._initCache = function () {
  14481. _super.prototype._initCache.call(this);
  14482. this._cache.localMatrixUpdated = false;
  14483. this._cache.position = BABYLON.Vector3.Zero();
  14484. this._cache.scaling = BABYLON.Vector3.Zero();
  14485. this._cache.rotation = BABYLON.Vector3.Zero();
  14486. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14487. this._cache.billboardMode = -1;
  14488. };
  14489. TransformNode.prototype.markAsDirty = function (property) {
  14490. if (property === "rotation") {
  14491. this.rotationQuaternion = null;
  14492. }
  14493. this._currentRenderId = Number.MAX_VALUE;
  14494. this._isDirty = true;
  14495. return this;
  14496. };
  14497. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14498. /**
  14499. * Returns the current mesh absolute position.
  14500. * Retuns a Vector3.
  14501. */
  14502. get: function () {
  14503. return this._absolutePosition;
  14504. },
  14505. enumerable: true,
  14506. configurable: true
  14507. });
  14508. /**
  14509. * Sets a new pivot matrix to the mesh.
  14510. * Returns the AbstractMesh.
  14511. */
  14512. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14513. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14514. this._pivotMatrix = matrix.clone();
  14515. this._cache.pivotMatrixUpdated = true;
  14516. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14517. if (this._postMultiplyPivotMatrix) {
  14518. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14519. }
  14520. return this;
  14521. };
  14522. /**
  14523. * Returns the mesh pivot matrix.
  14524. * Default : Identity.
  14525. * A Matrix is returned.
  14526. */
  14527. TransformNode.prototype.getPivotMatrix = function () {
  14528. return this._pivotMatrix;
  14529. };
  14530. /**
  14531. * Prevents the World matrix to be computed any longer.
  14532. * Returns the AbstractMesh.
  14533. */
  14534. TransformNode.prototype.freezeWorldMatrix = function () {
  14535. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14536. this.computeWorldMatrix(true);
  14537. this._isWorldMatrixFrozen = true;
  14538. return this;
  14539. };
  14540. /**
  14541. * Allows back the World matrix computation.
  14542. * Returns the AbstractMesh.
  14543. */
  14544. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14545. this._isWorldMatrixFrozen = false;
  14546. this.computeWorldMatrix(true);
  14547. return this;
  14548. };
  14549. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14550. /**
  14551. * True if the World matrix has been frozen.
  14552. * Returns a boolean.
  14553. */
  14554. get: function () {
  14555. return this._isWorldMatrixFrozen;
  14556. },
  14557. enumerable: true,
  14558. configurable: true
  14559. });
  14560. /**
  14561. * Retuns the mesh absolute position in the World.
  14562. * Returns a Vector3.
  14563. */
  14564. TransformNode.prototype.getAbsolutePosition = function () {
  14565. this.computeWorldMatrix();
  14566. return this._absolutePosition;
  14567. };
  14568. /**
  14569. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14570. * Returns the AbstractMesh.
  14571. */
  14572. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14573. if (!absolutePosition) {
  14574. return this;
  14575. }
  14576. var absolutePositionX;
  14577. var absolutePositionY;
  14578. var absolutePositionZ;
  14579. if (absolutePosition.x === undefined) {
  14580. if (arguments.length < 3) {
  14581. return this;
  14582. }
  14583. absolutePositionX = arguments[0];
  14584. absolutePositionY = arguments[1];
  14585. absolutePositionZ = arguments[2];
  14586. }
  14587. else {
  14588. absolutePositionX = absolutePosition.x;
  14589. absolutePositionY = absolutePosition.y;
  14590. absolutePositionZ = absolutePosition.z;
  14591. }
  14592. if (this.parent) {
  14593. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14594. invertParentWorldMatrix.invert();
  14595. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14596. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14597. }
  14598. else {
  14599. this.position.x = absolutePositionX;
  14600. this.position.y = absolutePositionY;
  14601. this.position.z = absolutePositionZ;
  14602. }
  14603. return this;
  14604. };
  14605. /**
  14606. * Sets the mesh position in its local space.
  14607. * Returns the AbstractMesh.
  14608. */
  14609. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14610. this.computeWorldMatrix();
  14611. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14612. return this;
  14613. };
  14614. /**
  14615. * Returns the mesh position in the local space from the current World matrix values.
  14616. * Returns a new Vector3.
  14617. */
  14618. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14619. this.computeWorldMatrix();
  14620. var invLocalWorldMatrix = this._localWorld.clone();
  14621. invLocalWorldMatrix.invert();
  14622. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14623. };
  14624. /**
  14625. * Translates the mesh along the passed Vector3 in its local space.
  14626. * Returns the AbstractMesh.
  14627. */
  14628. TransformNode.prototype.locallyTranslate = function (vector3) {
  14629. this.computeWorldMatrix(true);
  14630. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14631. return this;
  14632. };
  14633. /**
  14634. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14635. * @param targetPoint the position (must be in same space as current mesh) to look at
  14636. * @param yawCor optional yaw (y-axis) correction in radians
  14637. * @param pitchCor optional pitch (x-axis) correction in radians
  14638. * @param rollCor optional roll (z-axis) correction in radians
  14639. * @param space the choosen space of the target
  14640. * @returns the TransformNode.
  14641. */
  14642. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14643. if (yawCor === void 0) { yawCor = 0; }
  14644. if (pitchCor === void 0) { pitchCor = 0; }
  14645. if (rollCor === void 0) { rollCor = 0; }
  14646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14647. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14648. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14649. targetPoint.subtractToRef(pos, dv);
  14650. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14651. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14652. var pitch = Math.atan2(dv.y, len);
  14653. if (this.rotationQuaternion) {
  14654. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14655. }
  14656. else {
  14657. this.rotation.x = pitch + pitchCor;
  14658. this.rotation.y = yaw + yawCor;
  14659. this.rotation.z = rollCor;
  14660. }
  14661. return this;
  14662. };
  14663. /**
  14664. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14665. * This Vector3 is expressed in the World space.
  14666. */
  14667. TransformNode.prototype.getDirection = function (localAxis) {
  14668. var result = BABYLON.Vector3.Zero();
  14669. this.getDirectionToRef(localAxis, result);
  14670. return result;
  14671. };
  14672. /**
  14673. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14674. * localAxis is expressed in the mesh local space.
  14675. * result is computed in the Wordl space from the mesh World matrix.
  14676. * Returns the AbstractMesh.
  14677. */
  14678. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14679. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14680. return this;
  14681. };
  14682. TransformNode.prototype.setPivotPoint = function (point, space) {
  14683. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14684. if (this.getScene().getRenderId() == 0) {
  14685. this.computeWorldMatrix(true);
  14686. }
  14687. var wm = this.getWorldMatrix();
  14688. if (space == BABYLON.Space.WORLD) {
  14689. var tmat = BABYLON.Tmp.Matrix[0];
  14690. wm.invertToRef(tmat);
  14691. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14692. }
  14693. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14694. this._pivotMatrix.m[12] = -point.x;
  14695. this._pivotMatrix.m[13] = -point.y;
  14696. this._pivotMatrix.m[14] = -point.z;
  14697. this._cache.pivotMatrixUpdated = true;
  14698. return this;
  14699. };
  14700. /**
  14701. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14702. */
  14703. TransformNode.prototype.getPivotPoint = function () {
  14704. var point = BABYLON.Vector3.Zero();
  14705. this.getPivotPointToRef(point);
  14706. return point;
  14707. };
  14708. /**
  14709. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14710. * Returns the AbstractMesh.
  14711. */
  14712. TransformNode.prototype.getPivotPointToRef = function (result) {
  14713. result.x = -this._pivotMatrix.m[12];
  14714. result.y = -this._pivotMatrix.m[13];
  14715. result.z = -this._pivotMatrix.m[14];
  14716. return this;
  14717. };
  14718. /**
  14719. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14720. */
  14721. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14722. var point = BABYLON.Vector3.Zero();
  14723. this.getAbsolutePivotPointToRef(point);
  14724. return point;
  14725. };
  14726. /**
  14727. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14728. * Returns the AbstractMesh.
  14729. */
  14730. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14731. result.x = this._pivotMatrix.m[12];
  14732. result.y = this._pivotMatrix.m[13];
  14733. result.z = this._pivotMatrix.m[14];
  14734. this.getPivotPointToRef(result);
  14735. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14736. return this;
  14737. };
  14738. /**
  14739. * Defines the passed node as the parent of the current node.
  14740. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14741. * Returns the TransformNode.
  14742. */
  14743. TransformNode.prototype.setParent = function (node) {
  14744. if (node === null) {
  14745. var rotation = BABYLON.Tmp.Quaternion[0];
  14746. var position = BABYLON.Tmp.Vector3[0];
  14747. var scale = BABYLON.Tmp.Vector3[1];
  14748. if (this.parent && this.parent.computeWorldMatrix) {
  14749. this.parent.computeWorldMatrix(true);
  14750. }
  14751. this.computeWorldMatrix(true);
  14752. this.getWorldMatrix().decompose(scale, rotation, position);
  14753. if (this.rotationQuaternion) {
  14754. this.rotationQuaternion.copyFrom(rotation);
  14755. }
  14756. else {
  14757. rotation.toEulerAnglesToRef(this.rotation);
  14758. }
  14759. this.scaling.x = scale.x;
  14760. this.scaling.y = scale.y;
  14761. this.scaling.z = scale.z;
  14762. this.position.x = position.x;
  14763. this.position.y = position.y;
  14764. this.position.z = position.z;
  14765. }
  14766. else {
  14767. var rotation = BABYLON.Tmp.Quaternion[0];
  14768. var position = BABYLON.Tmp.Vector3[0];
  14769. var scale = BABYLON.Tmp.Vector3[1];
  14770. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14771. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14772. this.computeWorldMatrix(true);
  14773. node.computeWorldMatrix(true);
  14774. node.getWorldMatrix().invertToRef(invParentMatrix);
  14775. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14776. diffMatrix.decompose(scale, rotation, position);
  14777. if (this.rotationQuaternion) {
  14778. this.rotationQuaternion.copyFrom(rotation);
  14779. }
  14780. else {
  14781. rotation.toEulerAnglesToRef(this.rotation);
  14782. }
  14783. this.position.x = position.x;
  14784. this.position.y = position.y;
  14785. this.position.z = position.z;
  14786. this.scaling.x = scale.x;
  14787. this.scaling.y = scale.y;
  14788. this.scaling.z = scale.z;
  14789. }
  14790. this.parent = node;
  14791. return this;
  14792. };
  14793. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14794. get: function () {
  14795. return this._nonUniformScaling;
  14796. },
  14797. enumerable: true,
  14798. configurable: true
  14799. });
  14800. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14801. if (this._nonUniformScaling === value) {
  14802. return false;
  14803. }
  14804. this._nonUniformScaling = true;
  14805. return true;
  14806. };
  14807. /**
  14808. * Attach the current TransformNode to another TransformNode associated with a bone
  14809. * @param bone Bone affecting the TransformNode
  14810. * @param affectedTransformNode TransformNode associated with the bone
  14811. */
  14812. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14813. this._transformToBoneReferal = affectedTransformNode;
  14814. this.parent = bone;
  14815. if (bone.getWorldMatrix().determinant() < 0) {
  14816. this.scalingDeterminant *= -1;
  14817. }
  14818. return this;
  14819. };
  14820. TransformNode.prototype.detachFromBone = function () {
  14821. if (!this.parent) {
  14822. return this;
  14823. }
  14824. if (this.parent.getWorldMatrix().determinant() < 0) {
  14825. this.scalingDeterminant *= -1;
  14826. }
  14827. this._transformToBoneReferal = null;
  14828. this.parent = null;
  14829. return this;
  14830. };
  14831. /**
  14832. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14833. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14834. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14835. * The passed axis is also normalized.
  14836. * Returns the AbstractMesh.
  14837. */
  14838. TransformNode.prototype.rotate = function (axis, amount, space) {
  14839. axis.normalize();
  14840. if (!this.rotationQuaternion) {
  14841. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14842. this.rotation = BABYLON.Vector3.Zero();
  14843. }
  14844. var rotationQuaternion;
  14845. if (!space || space === BABYLON.Space.LOCAL) {
  14846. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14847. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14848. }
  14849. else {
  14850. if (this.parent) {
  14851. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14852. invertParentWorldMatrix.invert();
  14853. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14854. }
  14855. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14856. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14857. }
  14858. return this;
  14859. };
  14860. /**
  14861. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14862. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14863. * The passed axis is also normalized.
  14864. * Returns the AbstractMesh.
  14865. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14866. */
  14867. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14868. axis.normalize();
  14869. if (!this.rotationQuaternion) {
  14870. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14871. this.rotation.copyFromFloats(0, 0, 0);
  14872. }
  14873. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14874. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14875. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14876. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14877. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14878. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14879. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14880. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14881. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14882. return this;
  14883. };
  14884. /**
  14885. * Translates the mesh along the axis vector for the passed distance in the given space.
  14886. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14887. * Returns the AbstractMesh.
  14888. */
  14889. TransformNode.prototype.translate = function (axis, distance, space) {
  14890. var displacementVector = axis.scale(distance);
  14891. if (!space || space === BABYLON.Space.LOCAL) {
  14892. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14893. this.setPositionWithLocalVector(tempV3);
  14894. }
  14895. else {
  14896. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14897. }
  14898. return this;
  14899. };
  14900. /**
  14901. * Adds a rotation step to the mesh current rotation.
  14902. * x, y, z are Euler angles expressed in radians.
  14903. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14904. * This means this rotation is made in the mesh local space only.
  14905. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14906. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14907. * ```javascript
  14908. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14909. * ```
  14910. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14911. * 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.
  14912. * Returns the AbstractMesh.
  14913. */
  14914. TransformNode.prototype.addRotation = function (x, y, z) {
  14915. var rotationQuaternion;
  14916. if (this.rotationQuaternion) {
  14917. rotationQuaternion = this.rotationQuaternion;
  14918. }
  14919. else {
  14920. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14921. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14922. }
  14923. var accumulation = BABYLON.Tmp.Quaternion[0];
  14924. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14925. rotationQuaternion.multiplyInPlace(accumulation);
  14926. if (!this.rotationQuaternion) {
  14927. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14928. }
  14929. return this;
  14930. };
  14931. /**
  14932. * Computes the mesh World matrix and returns it.
  14933. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14934. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14935. * If the parameter `force`is set to `true`, the actual computation is done.
  14936. * Returns the mesh World Matrix.
  14937. */
  14938. TransformNode.prototype.computeWorldMatrix = function (force) {
  14939. if (this._isWorldMatrixFrozen) {
  14940. return this._worldMatrix;
  14941. }
  14942. if (!force && this.isSynchronized(true)) {
  14943. return this._worldMatrix;
  14944. }
  14945. this._cache.position.copyFrom(this.position);
  14946. this._cache.scaling.copyFrom(this.scaling);
  14947. this._cache.pivotMatrixUpdated = false;
  14948. this._cache.billboardMode = this.billboardMode;
  14949. this._currentRenderId = this.getScene().getRenderId();
  14950. this._isDirty = false;
  14951. // Scaling
  14952. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14953. // Rotation
  14954. //rotate, if quaternion is set and rotation was used
  14955. if (this.rotationQuaternion) {
  14956. var len = this.rotation.length();
  14957. if (len) {
  14958. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14959. this.rotation.copyFromFloats(0, 0, 0);
  14960. }
  14961. }
  14962. if (this.rotationQuaternion) {
  14963. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14964. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14965. }
  14966. else {
  14967. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14968. this._cache.rotation.copyFrom(this.rotation);
  14969. }
  14970. // Translation
  14971. var camera = this.getScene().activeCamera;
  14972. if (this.infiniteDistance && !this.parent && camera) {
  14973. var cameraWorldMatrix = camera.getWorldMatrix();
  14974. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14975. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14976. }
  14977. else {
  14978. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14979. }
  14980. // Composing transformations
  14981. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14982. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14983. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14984. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14985. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14986. // Need to decompose each rotation here
  14987. var currentPosition = BABYLON.Tmp.Vector3[3];
  14988. if (this.parent && this.parent.getWorldMatrix) {
  14989. if (this._transformToBoneReferal) {
  14990. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14991. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14992. }
  14993. else {
  14994. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14995. }
  14996. }
  14997. else {
  14998. currentPosition.copyFrom(this.position);
  14999. }
  15000. currentPosition.subtractInPlace(camera.globalPosition);
  15001. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15002. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15003. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15004. }
  15005. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15006. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15007. }
  15008. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15009. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15010. }
  15011. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15012. }
  15013. else {
  15014. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15015. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15016. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15017. }
  15018. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15019. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15020. }
  15021. // Local world
  15022. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15023. // Parent
  15024. if (this.parent && this.parent.getWorldMatrix) {
  15025. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15026. if (this._transformToBoneReferal) {
  15027. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15028. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15029. }
  15030. else {
  15031. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15032. }
  15033. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15034. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15035. this._worldMatrix.copyFrom(this._localWorld);
  15036. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15037. }
  15038. else {
  15039. if (this._transformToBoneReferal) {
  15040. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15041. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15042. }
  15043. else {
  15044. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15045. }
  15046. }
  15047. this._markSyncedWithParent();
  15048. }
  15049. else {
  15050. this._worldMatrix.copyFrom(this._localWorld);
  15051. }
  15052. // Post multiply inverse of pivotMatrix
  15053. if (this._postMultiplyPivotMatrix) {
  15054. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15055. }
  15056. // Normal matrix
  15057. if (this.scaling.isNonUniform) {
  15058. this._updateNonUniformScalingState(true);
  15059. }
  15060. else if (this.parent && this.parent._nonUniformScaling) {
  15061. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15062. }
  15063. else {
  15064. this._updateNonUniformScalingState(false);
  15065. }
  15066. this._afterComputeWorldMatrix();
  15067. // Absolute position
  15068. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15069. // Callbacks
  15070. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15071. if (!this._poseMatrix) {
  15072. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15073. }
  15074. // Cache the determinant
  15075. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15076. return this._worldMatrix;
  15077. };
  15078. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15079. };
  15080. /**
  15081. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15082. * @param func: callback function to add
  15083. *
  15084. * Returns the TransformNode.
  15085. */
  15086. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15087. this.onAfterWorldMatrixUpdateObservable.add(func);
  15088. return this;
  15089. };
  15090. /**
  15091. * Removes a registered callback function.
  15092. * Returns the TransformNode.
  15093. */
  15094. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15095. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15096. return this;
  15097. };
  15098. /**
  15099. * Clone the current transform node
  15100. * Returns the new transform node
  15101. * @param name Name of the new clone
  15102. * @param newParent New parent for the clone
  15103. * @param doNotCloneChildren Do not clone children hierarchy
  15104. */
  15105. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15106. var _this = this;
  15107. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15108. result.name = name;
  15109. result.id = name;
  15110. if (newParent) {
  15111. result.parent = newParent;
  15112. }
  15113. if (!doNotCloneChildren) {
  15114. // Children
  15115. var directDescendants = this.getDescendants(true);
  15116. for (var index = 0; index < directDescendants.length; index++) {
  15117. var child = directDescendants[index];
  15118. if (child.clone) {
  15119. child.clone(name + "." + child.name, result);
  15120. }
  15121. }
  15122. }
  15123. return result;
  15124. };
  15125. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15126. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15127. serializationObject.type = this.getClassName();
  15128. // Parent
  15129. if (this.parent) {
  15130. serializationObject.parentId = this.parent.id;
  15131. }
  15132. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15133. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15134. }
  15135. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15136. serializationObject.isEnabled = this.isEnabled();
  15137. // Parent
  15138. if (this.parent) {
  15139. serializationObject.parentId = this.parent.id;
  15140. }
  15141. return serializationObject;
  15142. };
  15143. // Statics
  15144. /**
  15145. * Returns a new TransformNode object parsed from the source provided.
  15146. * The parameter `parsedMesh` is the source.
  15147. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15148. */
  15149. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15150. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15151. if (BABYLON.Tags) {
  15152. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15153. }
  15154. if (parsedTransformNode.localMatrix) {
  15155. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15156. }
  15157. else if (parsedTransformNode.pivotMatrix) {
  15158. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15159. }
  15160. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15161. // Parent
  15162. if (parsedTransformNode.parentId) {
  15163. transformNode._waitingParentId = parsedTransformNode.parentId;
  15164. }
  15165. return transformNode;
  15166. };
  15167. /**
  15168. * Disposes the TransformNode.
  15169. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15170. * Returns nothing.
  15171. */
  15172. TransformNode.prototype.dispose = function (doNotRecurse) {
  15173. // Animations
  15174. this.getScene().stopAnimation(this);
  15175. // Remove from scene
  15176. this.getScene().removeTransformNode(this);
  15177. if (!doNotRecurse) {
  15178. // Children
  15179. var objects = this.getDescendants(true);
  15180. for (var index = 0; index < objects.length; index++) {
  15181. objects[index].dispose();
  15182. }
  15183. }
  15184. else {
  15185. var childMeshes = this.getChildMeshes(true);
  15186. for (index = 0; index < childMeshes.length; index++) {
  15187. var child = childMeshes[index];
  15188. child.parent = null;
  15189. child.computeWorldMatrix(true);
  15190. }
  15191. }
  15192. this.onAfterWorldMatrixUpdateObservable.clear();
  15193. _super.prototype.dispose.call(this);
  15194. };
  15195. // Statics
  15196. TransformNode.BILLBOARDMODE_NONE = 0;
  15197. TransformNode.BILLBOARDMODE_X = 1;
  15198. TransformNode.BILLBOARDMODE_Y = 2;
  15199. TransformNode.BILLBOARDMODE_Z = 4;
  15200. TransformNode.BILLBOARDMODE_ALL = 7;
  15201. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15202. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15203. __decorate([
  15204. BABYLON.serializeAsVector3()
  15205. ], TransformNode.prototype, "_rotation", void 0);
  15206. __decorate([
  15207. BABYLON.serializeAsQuaternion()
  15208. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15209. __decorate([
  15210. BABYLON.serializeAsVector3()
  15211. ], TransformNode.prototype, "_scaling", void 0);
  15212. __decorate([
  15213. BABYLON.serialize()
  15214. ], TransformNode.prototype, "billboardMode", void 0);
  15215. __decorate([
  15216. BABYLON.serialize()
  15217. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15218. __decorate([
  15219. BABYLON.serialize()
  15220. ], TransformNode.prototype, "infiniteDistance", void 0);
  15221. __decorate([
  15222. BABYLON.serializeAsVector3()
  15223. ], TransformNode.prototype, "position", void 0);
  15224. return TransformNode;
  15225. }(BABYLON.Node));
  15226. BABYLON.TransformNode = TransformNode;
  15227. })(BABYLON || (BABYLON = {}));
  15228. //# sourceMappingURL=babylon.transformNode.js.map
  15229. var BABYLON;
  15230. (function (BABYLON) {
  15231. var AbstractMesh = /** @class */ (function (_super) {
  15232. __extends(AbstractMesh, _super);
  15233. // Constructor
  15234. function AbstractMesh(name, scene) {
  15235. if (scene === void 0) { scene = null; }
  15236. var _this = _super.call(this, name, scene, false) || this;
  15237. _this._facetNb = 0; // facet number
  15238. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15239. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15240. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15241. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15242. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15243. _this._subDiv = {
  15244. max: 1,
  15245. X: 1,
  15246. Y: 1,
  15247. Z: 1
  15248. };
  15249. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15250. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15251. // Events
  15252. /**
  15253. * An event triggered when this mesh collides with another one
  15254. * @type {BABYLON.Observable}
  15255. */
  15256. _this.onCollideObservable = new BABYLON.Observable();
  15257. /**
  15258. * An event triggered when the collision's position changes
  15259. * @type {BABYLON.Observable}
  15260. */
  15261. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15262. /**
  15263. * An event triggered when material is changed
  15264. * @type {BABYLON.Observable}
  15265. */
  15266. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15267. // Properties
  15268. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15269. /**
  15270. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15271. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15272. * or
  15273. * 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.
  15274. * for more info check WebGl documentations
  15275. */
  15276. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15277. /**
  15278. * 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:
  15279. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15280. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15281. * 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.
  15282. */
  15283. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15284. /**
  15285. * 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.
  15286. * The default value is -1 which means don't break the query and wait till the result.
  15287. */
  15288. _this.occlusionRetryCount = -1;
  15289. _this._occlusionInternalRetryCounter = 0;
  15290. _this._isOccluded = false;
  15291. _this._isOcclusionQueryInProgress = false;
  15292. _this.visibility = 1.0;
  15293. _this.alphaIndex = Number.MAX_VALUE;
  15294. _this.isVisible = true;
  15295. _this.isPickable = true;
  15296. _this.showBoundingBox = false;
  15297. _this.showSubMeshesBoundingBox = false;
  15298. _this.isBlocker = false;
  15299. _this.enablePointerMoveEvents = false;
  15300. _this.renderingGroupId = 0;
  15301. _this._receiveShadows = false;
  15302. _this.renderOutline = false;
  15303. _this.outlineColor = BABYLON.Color3.Red();
  15304. _this.outlineWidth = 0.02;
  15305. _this.renderOverlay = false;
  15306. _this.overlayColor = BABYLON.Color3.Red();
  15307. _this.overlayAlpha = 0.5;
  15308. _this._hasVertexAlpha = false;
  15309. _this._useVertexColors = true;
  15310. _this._computeBonesUsingShaders = true;
  15311. _this._numBoneInfluencers = 4;
  15312. _this._applyFog = true;
  15313. _this.useOctreeForRenderingSelection = true;
  15314. _this.useOctreeForPicking = true;
  15315. _this.useOctreeForCollisions = true;
  15316. _this._layerMask = 0x0FFFFFFF;
  15317. /**
  15318. * True if the mesh must be rendered in any case.
  15319. */
  15320. _this.alwaysSelectAsActiveMesh = false;
  15321. /**
  15322. * This scene's action manager
  15323. * @type {BABYLON.ActionManager}
  15324. */
  15325. _this.actionManager = null;
  15326. // Physics
  15327. _this.physicsImpostor = null;
  15328. // Collisions
  15329. _this._checkCollisions = false;
  15330. _this._collisionMask = -1;
  15331. _this._collisionGroup = -1;
  15332. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15333. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15334. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15335. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15336. // Edges
  15337. _this.edgesWidth = 1;
  15338. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15339. // Cache
  15340. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15341. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15342. _this._isDisposed = false;
  15343. _this._renderId = 0;
  15344. _this._intersectionsInProgress = new Array();
  15345. _this._unIndexed = false;
  15346. _this._lightSources = new Array();
  15347. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15348. if (collidedMesh === void 0) { collidedMesh = null; }
  15349. //TODO move this to the collision coordinator!
  15350. if (_this.getScene().workerCollisions)
  15351. newPosition.multiplyInPlace(_this._collider._radius);
  15352. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15353. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15354. _this.position.addInPlace(_this._diffPositionForCollisions);
  15355. }
  15356. if (collidedMesh) {
  15357. _this.onCollideObservable.notifyObservers(collidedMesh);
  15358. }
  15359. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15360. };
  15361. _this.getScene().addMesh(_this);
  15362. _this._resyncLightSources();
  15363. return _this;
  15364. }
  15365. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15366. get: function () {
  15367. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15368. },
  15369. enumerable: true,
  15370. configurable: true
  15371. });
  15372. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15373. get: function () {
  15374. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15375. },
  15376. enumerable: true,
  15377. configurable: true
  15378. });
  15379. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15380. get: function () {
  15381. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15382. },
  15383. enumerable: true,
  15384. configurable: true
  15385. });
  15386. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15387. get: function () {
  15388. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15389. },
  15390. enumerable: true,
  15391. configurable: true
  15392. });
  15393. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15394. get: function () {
  15395. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15396. },
  15397. enumerable: true,
  15398. configurable: true
  15399. });
  15400. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15401. /**
  15402. * Read-only : the number of facets in the mesh
  15403. */
  15404. get: function () {
  15405. return this._facetNb;
  15406. },
  15407. enumerable: true,
  15408. configurable: true
  15409. });
  15410. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15411. /**
  15412. * The number (integer) of subdivisions per axis in the partioning space
  15413. */
  15414. get: function () {
  15415. return this._partitioningSubdivisions;
  15416. },
  15417. set: function (nb) {
  15418. this._partitioningSubdivisions = nb;
  15419. },
  15420. enumerable: true,
  15421. configurable: true
  15422. });
  15423. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15424. /**
  15425. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15426. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15427. */
  15428. get: function () {
  15429. return this._partitioningBBoxRatio;
  15430. },
  15431. set: function (ratio) {
  15432. this._partitioningBBoxRatio = ratio;
  15433. },
  15434. enumerable: true,
  15435. configurable: true
  15436. });
  15437. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15438. /**
  15439. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15440. * Works only for updatable meshes.
  15441. * Doesn't work with multi-materials.
  15442. */
  15443. get: function () {
  15444. return this._facetDepthSort;
  15445. },
  15446. set: function (sort) {
  15447. this._facetDepthSort = sort;
  15448. },
  15449. enumerable: true,
  15450. configurable: true
  15451. });
  15452. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15453. /**
  15454. * The location (Vector3) where the facet depth sort must be computed from.
  15455. * By default, the active camera position.
  15456. * Used only when facet depth sort is enabled.
  15457. */
  15458. get: function () {
  15459. return this._facetDepthSortFrom;
  15460. },
  15461. set: function (location) {
  15462. this._facetDepthSortFrom = location;
  15463. },
  15464. enumerable: true,
  15465. configurable: true
  15466. });
  15467. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15468. /**
  15469. * Read-only boolean : is the feature facetData enabled ?
  15470. */
  15471. get: function () {
  15472. return this._facetDataEnabled;
  15473. },
  15474. enumerable: true,
  15475. configurable: true
  15476. });
  15477. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15478. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15479. return false;
  15480. }
  15481. this._markSubMeshesAsMiscDirty();
  15482. return true;
  15483. };
  15484. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15485. set: function (callback) {
  15486. if (this._onCollideObserver) {
  15487. this.onCollideObservable.remove(this._onCollideObserver);
  15488. }
  15489. this._onCollideObserver = this.onCollideObservable.add(callback);
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15495. set: function (callback) {
  15496. if (this._onCollisionPositionChangeObserver) {
  15497. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15498. }
  15499. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15500. },
  15501. enumerable: true,
  15502. configurable: true
  15503. });
  15504. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15505. /**
  15506. * 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.
  15507. */
  15508. get: function () {
  15509. return this._isOccluded;
  15510. },
  15511. set: function (value) {
  15512. this._isOccluded = value;
  15513. },
  15514. enumerable: true,
  15515. configurable: true
  15516. });
  15517. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15518. /**
  15519. * Flag to check the progress status of the query
  15520. */
  15521. get: function () {
  15522. return this._isOcclusionQueryInProgress;
  15523. },
  15524. enumerable: true,
  15525. configurable: true
  15526. });
  15527. Object.defineProperty(AbstractMesh.prototype, "material", {
  15528. get: function () {
  15529. return this._material;
  15530. },
  15531. set: function (value) {
  15532. if (this._material === value) {
  15533. return;
  15534. }
  15535. this._material = value;
  15536. if (this.onMaterialChangedObservable.hasObservers) {
  15537. this.onMaterialChangedObservable.notifyObservers(this);
  15538. }
  15539. if (!this.subMeshes) {
  15540. return;
  15541. }
  15542. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15543. var subMesh = _a[_i];
  15544. subMesh.setEffect(null);
  15545. }
  15546. },
  15547. enumerable: true,
  15548. configurable: true
  15549. });
  15550. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15551. get: function () {
  15552. return this._receiveShadows;
  15553. },
  15554. set: function (value) {
  15555. if (this._receiveShadows === value) {
  15556. return;
  15557. }
  15558. this._receiveShadows = value;
  15559. this._markSubMeshesAsLightDirty();
  15560. },
  15561. enumerable: true,
  15562. configurable: true
  15563. });
  15564. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15565. get: function () {
  15566. return this._hasVertexAlpha;
  15567. },
  15568. set: function (value) {
  15569. if (this._hasVertexAlpha === value) {
  15570. return;
  15571. }
  15572. this._hasVertexAlpha = value;
  15573. this._markSubMeshesAsAttributesDirty();
  15574. },
  15575. enumerable: true,
  15576. configurable: true
  15577. });
  15578. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15579. get: function () {
  15580. return this._useVertexColors;
  15581. },
  15582. set: function (value) {
  15583. if (this._useVertexColors === value) {
  15584. return;
  15585. }
  15586. this._useVertexColors = value;
  15587. this._markSubMeshesAsAttributesDirty();
  15588. },
  15589. enumerable: true,
  15590. configurable: true
  15591. });
  15592. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15593. get: function () {
  15594. return this._computeBonesUsingShaders;
  15595. },
  15596. set: function (value) {
  15597. if (this._computeBonesUsingShaders === value) {
  15598. return;
  15599. }
  15600. this._computeBonesUsingShaders = value;
  15601. this._markSubMeshesAsAttributesDirty();
  15602. },
  15603. enumerable: true,
  15604. configurable: true
  15605. });
  15606. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15607. get: function () {
  15608. return this._numBoneInfluencers;
  15609. },
  15610. set: function (value) {
  15611. if (this._numBoneInfluencers === value) {
  15612. return;
  15613. }
  15614. this._numBoneInfluencers = value;
  15615. this._markSubMeshesAsAttributesDirty();
  15616. },
  15617. enumerable: true,
  15618. configurable: true
  15619. });
  15620. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15621. get: function () {
  15622. return this._applyFog;
  15623. },
  15624. set: function (value) {
  15625. if (this._applyFog === value) {
  15626. return;
  15627. }
  15628. this._applyFog = value;
  15629. this._markSubMeshesAsMiscDirty();
  15630. },
  15631. enumerable: true,
  15632. configurable: true
  15633. });
  15634. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15635. get: function () {
  15636. return this._layerMask;
  15637. },
  15638. set: function (value) {
  15639. if (value === this._layerMask) {
  15640. return;
  15641. }
  15642. this._layerMask = value;
  15643. this._resyncLightSources();
  15644. },
  15645. enumerable: true,
  15646. configurable: true
  15647. });
  15648. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15649. get: function () {
  15650. return this._collisionMask;
  15651. },
  15652. set: function (mask) {
  15653. this._collisionMask = !isNaN(mask) ? mask : -1;
  15654. },
  15655. enumerable: true,
  15656. configurable: true
  15657. });
  15658. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15659. get: function () {
  15660. return this._collisionGroup;
  15661. },
  15662. set: function (mask) {
  15663. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15669. get: function () {
  15670. return null;
  15671. },
  15672. enumerable: true,
  15673. configurable: true
  15674. });
  15675. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15676. get: function () {
  15677. return this._skeleton;
  15678. },
  15679. set: function (value) {
  15680. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15681. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15682. }
  15683. if (value && value.needInitialSkinMatrix) {
  15684. value._registerMeshWithPoseMatrix(this);
  15685. }
  15686. this._skeleton = value;
  15687. if (!this._skeleton) {
  15688. this._bonesTransformMatrices = null;
  15689. }
  15690. this._markSubMeshesAsAttributesDirty();
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. /**
  15696. * Boolean : true if the mesh has been disposed.
  15697. */
  15698. AbstractMesh.prototype.isDisposed = function () {
  15699. return this._isDisposed;
  15700. };
  15701. /**
  15702. * Returns the string "AbstractMesh"
  15703. */
  15704. AbstractMesh.prototype.getClassName = function () {
  15705. return "AbstractMesh";
  15706. };
  15707. /**
  15708. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15709. */
  15710. AbstractMesh.prototype.toString = function (fullDetails) {
  15711. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15712. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15713. if (this._skeleton) {
  15714. ret += ", skeleton: " + this._skeleton.name;
  15715. }
  15716. if (fullDetails) {
  15717. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15718. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15719. }
  15720. return ret;
  15721. };
  15722. AbstractMesh.prototype._rebuild = function () {
  15723. if (this._occlusionQuery) {
  15724. this._occlusionQuery = null;
  15725. }
  15726. if (this._edgesRenderer) {
  15727. this._edgesRenderer._rebuild();
  15728. }
  15729. if (!this.subMeshes) {
  15730. return;
  15731. }
  15732. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15733. var subMesh = _a[_i];
  15734. subMesh._rebuild();
  15735. }
  15736. };
  15737. AbstractMesh.prototype._resyncLightSources = function () {
  15738. this._lightSources.length = 0;
  15739. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15740. var light = _a[_i];
  15741. if (!light.isEnabled()) {
  15742. continue;
  15743. }
  15744. if (light.canAffectMesh(this)) {
  15745. this._lightSources.push(light);
  15746. }
  15747. }
  15748. this._markSubMeshesAsLightDirty();
  15749. };
  15750. AbstractMesh.prototype._resyncLighSource = function (light) {
  15751. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15752. var index = this._lightSources.indexOf(light);
  15753. if (index === -1) {
  15754. if (!isIn) {
  15755. return;
  15756. }
  15757. this._lightSources.push(light);
  15758. }
  15759. else {
  15760. if (isIn) {
  15761. return;
  15762. }
  15763. this._lightSources.splice(index, 1);
  15764. }
  15765. this._markSubMeshesAsLightDirty();
  15766. };
  15767. AbstractMesh.prototype._removeLightSource = function (light) {
  15768. var index = this._lightSources.indexOf(light);
  15769. if (index === -1) {
  15770. return;
  15771. }
  15772. this._lightSources.splice(index, 1);
  15773. };
  15774. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15775. if (!this.subMeshes) {
  15776. return;
  15777. }
  15778. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15779. var subMesh = _a[_i];
  15780. if (subMesh._materialDefines) {
  15781. func(subMesh._materialDefines);
  15782. }
  15783. }
  15784. };
  15785. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15786. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15787. };
  15788. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15789. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15790. };
  15791. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15792. if (!this.subMeshes) {
  15793. return;
  15794. }
  15795. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15796. var subMesh = _a[_i];
  15797. var material = subMesh.getMaterial();
  15798. if (material) {
  15799. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15800. }
  15801. }
  15802. };
  15803. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15804. /**
  15805. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15806. * Default : (1.0, 1.0, 1.0)
  15807. */
  15808. get: function () {
  15809. return this._scaling;
  15810. },
  15811. /**
  15812. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15813. * Default : (1.0, 1.0, 1.0)
  15814. */
  15815. set: function (newScaling) {
  15816. this._scaling = newScaling;
  15817. if (this.physicsImpostor) {
  15818. this.physicsImpostor.forceUpdate();
  15819. }
  15820. },
  15821. enumerable: true,
  15822. configurable: true
  15823. });
  15824. // Methods
  15825. /**
  15826. * Disables the mesh edger rendering mode.
  15827. * Returns the AbstractMesh.
  15828. */
  15829. AbstractMesh.prototype.disableEdgesRendering = function () {
  15830. if (this._edgesRenderer) {
  15831. this._edgesRenderer.dispose();
  15832. this._edgesRenderer = null;
  15833. }
  15834. return this;
  15835. };
  15836. /**
  15837. * Enables the edge rendering mode on the mesh.
  15838. * This mode makes the mesh edges visible.
  15839. * Returns the AbstractMesh.
  15840. */
  15841. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15842. if (epsilon === void 0) { epsilon = 0.95; }
  15843. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15844. this.disableEdgesRendering();
  15845. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15846. return this;
  15847. };
  15848. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15849. /**
  15850. * Returns true if the mesh is blocked. Used by the class Mesh.
  15851. * Returns the boolean `false` by default.
  15852. */
  15853. get: function () {
  15854. return false;
  15855. },
  15856. enumerable: true,
  15857. configurable: true
  15858. });
  15859. /**
  15860. * Returns the mesh itself by default, used by the class Mesh.
  15861. * Returned type : AbstractMesh
  15862. */
  15863. AbstractMesh.prototype.getLOD = function (camera) {
  15864. return this;
  15865. };
  15866. /**
  15867. * Returns 0 by default, used by the class Mesh.
  15868. * Returns an integer.
  15869. */
  15870. AbstractMesh.prototype.getTotalVertices = function () {
  15871. return 0;
  15872. };
  15873. /**
  15874. * Returns null by default, used by the class Mesh.
  15875. * Returned type : integer array
  15876. */
  15877. AbstractMesh.prototype.getIndices = function () {
  15878. return null;
  15879. };
  15880. /**
  15881. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15882. * Returned type : float array or Float32Array
  15883. */
  15884. AbstractMesh.prototype.getVerticesData = function (kind) {
  15885. return null;
  15886. };
  15887. /**
  15888. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15889. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15890. * The `data` are either a numeric array either a Float32Array.
  15891. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15892. * 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).
  15893. * Note that a new underlying VertexBuffer object is created each call.
  15894. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15895. *
  15896. * Possible `kind` values :
  15897. * - BABYLON.VertexBuffer.PositionKind
  15898. * - BABYLON.VertexBuffer.UVKind
  15899. * - BABYLON.VertexBuffer.UV2Kind
  15900. * - BABYLON.VertexBuffer.UV3Kind
  15901. * - BABYLON.VertexBuffer.UV4Kind
  15902. * - BABYLON.VertexBuffer.UV5Kind
  15903. * - BABYLON.VertexBuffer.UV6Kind
  15904. * - BABYLON.VertexBuffer.ColorKind
  15905. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15906. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15907. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15908. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15909. *
  15910. * Returns the Mesh.
  15911. */
  15912. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15913. return this;
  15914. };
  15915. /**
  15916. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15917. * If the mesh has no geometry, it is simply returned as it is.
  15918. * The `data` are either a numeric array either a Float32Array.
  15919. * No new underlying VertexBuffer object is created.
  15920. * 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.
  15921. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15922. *
  15923. * Possible `kind` values :
  15924. * - BABYLON.VertexBuffer.PositionKind
  15925. * - BABYLON.VertexBuffer.UVKind
  15926. * - BABYLON.VertexBuffer.UV2Kind
  15927. * - BABYLON.VertexBuffer.UV3Kind
  15928. * - BABYLON.VertexBuffer.UV4Kind
  15929. * - BABYLON.VertexBuffer.UV5Kind
  15930. * - BABYLON.VertexBuffer.UV6Kind
  15931. * - BABYLON.VertexBuffer.ColorKind
  15932. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15933. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15934. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15935. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15936. *
  15937. * Returns the Mesh.
  15938. */
  15939. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15940. return this;
  15941. };
  15942. /**
  15943. * Sets the mesh indices.
  15944. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15945. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15946. * This method creates a new index buffer each call.
  15947. * Returns the Mesh.
  15948. */
  15949. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15950. return this;
  15951. };
  15952. /** Returns false by default, used by the class Mesh.
  15953. * Returns a boolean
  15954. */
  15955. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15956. return false;
  15957. };
  15958. /**
  15959. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15960. * Returns a BoundingInfo
  15961. */
  15962. AbstractMesh.prototype.getBoundingInfo = function () {
  15963. if (this._masterMesh) {
  15964. return this._masterMesh.getBoundingInfo();
  15965. }
  15966. if (!this._boundingInfo) {
  15967. // this._boundingInfo is being created here
  15968. this._updateBoundingInfo();
  15969. }
  15970. // cannot be null.
  15971. return this._boundingInfo;
  15972. };
  15973. /**
  15974. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15975. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15976. */
  15977. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15978. if (includeDescendants === void 0) { includeDescendants = true; }
  15979. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15980. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15981. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15982. if (maxDimension === 0) {
  15983. return this;
  15984. }
  15985. var scale = 1 / maxDimension;
  15986. this.scaling.scaleInPlace(scale);
  15987. return this;
  15988. };
  15989. /**
  15990. * Sets a mesh new object BoundingInfo.
  15991. * Returns the AbstractMesh.
  15992. */
  15993. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15994. this._boundingInfo = boundingInfo;
  15995. return this;
  15996. };
  15997. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15998. get: function () {
  15999. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16000. },
  16001. enumerable: true,
  16002. configurable: true
  16003. });
  16004. AbstractMesh.prototype._preActivate = function () {
  16005. };
  16006. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16007. };
  16008. AbstractMesh.prototype._activate = function (renderId) {
  16009. this._renderId = renderId;
  16010. };
  16011. /**
  16012. * Returns the latest update of the World matrix
  16013. * Returns a Matrix.
  16014. */
  16015. AbstractMesh.prototype.getWorldMatrix = function () {
  16016. if (this._masterMesh) {
  16017. return this._masterMesh.getWorldMatrix();
  16018. }
  16019. return _super.prototype.getWorldMatrix.call(this);
  16020. };
  16021. /**
  16022. * Returns the latest update of the World matrix determinant.
  16023. */
  16024. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16025. if (this._masterMesh) {
  16026. return this._masterMesh._getWorldMatrixDeterminant();
  16027. }
  16028. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16029. };
  16030. // ================================== Point of View Movement =================================
  16031. /**
  16032. * Perform relative position change from the point of view of behind the front of the mesh.
  16033. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16034. * Supports definition of mesh facing forward or backward.
  16035. * @param {number} amountRight
  16036. * @param {number} amountUp
  16037. * @param {number} amountForward
  16038. *
  16039. * Returns the AbstractMesh.
  16040. */
  16041. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16042. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16043. return this;
  16044. };
  16045. /**
  16046. * Calculate relative position change from the point of view of behind the front of the mesh.
  16047. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16048. * Supports definition of mesh facing forward or backward.
  16049. * @param {number} amountRight
  16050. * @param {number} amountUp
  16051. * @param {number} amountForward
  16052. *
  16053. * Returns a new Vector3.
  16054. */
  16055. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16056. var rotMatrix = new BABYLON.Matrix();
  16057. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16058. rotQuaternion.toRotationMatrix(rotMatrix);
  16059. var translationDelta = BABYLON.Vector3.Zero();
  16060. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16061. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16062. return translationDelta;
  16063. };
  16064. // ================================== Point of View Rotation =================================
  16065. /**
  16066. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16067. * Supports definition of mesh facing forward or backward.
  16068. * @param {number} flipBack
  16069. * @param {number} twirlClockwise
  16070. * @param {number} tiltRight
  16071. *
  16072. * Returns the AbstractMesh.
  16073. */
  16074. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16075. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16076. return this;
  16077. };
  16078. /**
  16079. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16080. * Supports definition of mesh facing forward or backward.
  16081. * @param {number} flipBack
  16082. * @param {number} twirlClockwise
  16083. * @param {number} tiltRight
  16084. *
  16085. * Returns a new Vector3.
  16086. */
  16087. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16088. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16089. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16090. };
  16091. /**
  16092. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16093. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16094. */
  16095. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16096. if (includeDescendants === void 0) { includeDescendants = true; }
  16097. this.computeWorldMatrix(true);
  16098. var min;
  16099. var max;
  16100. var boundingInfo = this.getBoundingInfo();
  16101. if (!this.subMeshes) {
  16102. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16103. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16104. }
  16105. else {
  16106. min = boundingInfo.boundingBox.minimumWorld;
  16107. max = boundingInfo.boundingBox.maximumWorld;
  16108. }
  16109. if (includeDescendants) {
  16110. var descendants = this.getDescendants(false);
  16111. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16112. var descendant = descendants_1[_i];
  16113. var childMesh = descendant;
  16114. childMesh.computeWorldMatrix(true);
  16115. //make sure we have the needed params to get mix and max
  16116. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16117. continue;
  16118. }
  16119. var childBoundingInfo = childMesh.getBoundingInfo();
  16120. var boundingBox = childBoundingInfo.boundingBox;
  16121. var minBox = boundingBox.minimumWorld;
  16122. var maxBox = boundingBox.maximumWorld;
  16123. BABYLON.Tools.CheckExtends(minBox, min, max);
  16124. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16125. }
  16126. }
  16127. return {
  16128. min: min,
  16129. max: max
  16130. };
  16131. };
  16132. /**
  16133. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16134. * Returns the AbstractMesh.
  16135. */
  16136. AbstractMesh.prototype._updateBoundingInfo = function () {
  16137. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16138. this._boundingInfo.update(this.worldMatrixFromCache);
  16139. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16140. return this;
  16141. };
  16142. /**
  16143. * Update a mesh's children BoundingInfo objects only.
  16144. * Returns the AbstractMesh.
  16145. */
  16146. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16147. if (!this.subMeshes) {
  16148. return this;
  16149. }
  16150. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16151. var subMesh = this.subMeshes[subIndex];
  16152. if (!subMesh.IsGlobal) {
  16153. subMesh.updateBoundingInfo(matrix);
  16154. }
  16155. }
  16156. return this;
  16157. };
  16158. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16159. // Bounding info
  16160. this._updateBoundingInfo();
  16161. };
  16162. /**
  16163. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16164. * A mesh is in the frustum if its bounding box intersects the frustum.
  16165. * Boolean returned.
  16166. */
  16167. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16168. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16169. };
  16170. /**
  16171. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16172. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16173. * Boolean returned.
  16174. */
  16175. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16176. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16177. ;
  16178. };
  16179. /**
  16180. * True if the mesh intersects another mesh or a SolidParticle object.
  16181. * 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)
  16182. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16183. * Returns a boolean.
  16184. */
  16185. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16186. if (precise === void 0) { precise = false; }
  16187. if (!this._boundingInfo || !mesh._boundingInfo) {
  16188. return false;
  16189. }
  16190. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16191. return true;
  16192. }
  16193. if (includeDescendants) {
  16194. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16195. var child = _a[_i];
  16196. if (child.intersectsMesh(mesh, precise, true)) {
  16197. return true;
  16198. }
  16199. }
  16200. }
  16201. return false;
  16202. };
  16203. /**
  16204. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16205. * Returns a boolean.
  16206. */
  16207. AbstractMesh.prototype.intersectsPoint = function (point) {
  16208. if (!this._boundingInfo) {
  16209. return false;
  16210. }
  16211. return this._boundingInfo.intersectsPoint(point);
  16212. };
  16213. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16214. return this.physicsImpostor;
  16215. };
  16216. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16217. if (camera === void 0) { camera = null; }
  16218. if (!camera) {
  16219. camera = this.getScene().activeCamera;
  16220. }
  16221. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16222. };
  16223. /**
  16224. * Returns the distance from the mesh to the active camera.
  16225. * Returns a float.
  16226. */
  16227. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16228. if (camera === void 0) { camera = null; }
  16229. if (!camera) {
  16230. camera = this.getScene().activeCamera;
  16231. }
  16232. return this.absolutePosition.subtract(camera.position).length();
  16233. };
  16234. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16235. if (!this.physicsImpostor) {
  16236. return this;
  16237. }
  16238. this.physicsImpostor.applyImpulse(force, contactPoint);
  16239. return this;
  16240. };
  16241. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16242. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16243. return this;
  16244. }
  16245. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16246. mainPivot: pivot1,
  16247. connectedPivot: pivot2,
  16248. nativeParams: options
  16249. });
  16250. return this;
  16251. };
  16252. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16253. // Collisions
  16254. /**
  16255. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16256. * Default `false`.
  16257. */
  16258. get: function () {
  16259. return this._checkCollisions;
  16260. },
  16261. set: function (collisionEnabled) {
  16262. this._checkCollisions = collisionEnabled;
  16263. if (this.getScene().workerCollisions) {
  16264. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16265. }
  16266. },
  16267. enumerable: true,
  16268. configurable: true
  16269. });
  16270. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16271. /**
  16272. * Gets Collider object used to compute collisions (not physics)
  16273. */
  16274. get: function () {
  16275. return this._collider;
  16276. },
  16277. enumerable: true,
  16278. configurable: true
  16279. });
  16280. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16281. var globalPosition = this.getAbsolutePosition();
  16282. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16283. if (!this._collider) {
  16284. this._collider = new BABYLON.Collider();
  16285. }
  16286. this._collider._radius = this.ellipsoid;
  16287. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16288. return this;
  16289. };
  16290. // Submeshes octree
  16291. /**
  16292. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16293. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16294. * Returns an Octree of submeshes.
  16295. */
  16296. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16297. if (maxCapacity === void 0) { maxCapacity = 64; }
  16298. if (maxDepth === void 0) { maxDepth = 2; }
  16299. if (!this._submeshesOctree) {
  16300. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16301. }
  16302. this.computeWorldMatrix(true);
  16303. var boundingInfo = this.getBoundingInfo();
  16304. // Update octree
  16305. var bbox = boundingInfo.boundingBox;
  16306. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16307. return this._submeshesOctree;
  16308. };
  16309. // Collisions
  16310. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16311. this._generatePointsArray();
  16312. if (!this._positions) {
  16313. return this;
  16314. }
  16315. // Transformation
  16316. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16317. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16318. subMesh._lastColliderWorldVertices = [];
  16319. subMesh._trianglePlanes = [];
  16320. var start = subMesh.verticesStart;
  16321. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16322. for (var i = start; i < end; i++) {
  16323. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16324. }
  16325. }
  16326. // Collide
  16327. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16328. if (collider.collisionFound) {
  16329. collider.collidedMesh = this;
  16330. }
  16331. return this;
  16332. };
  16333. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16334. var subMeshes;
  16335. var len;
  16336. // Octrees
  16337. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16338. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16339. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16340. len = intersections.length;
  16341. subMeshes = intersections.data;
  16342. }
  16343. else {
  16344. subMeshes = this.subMeshes;
  16345. len = subMeshes.length;
  16346. }
  16347. for (var index = 0; index < len; index++) {
  16348. var subMesh = subMeshes[index];
  16349. // Bounding test
  16350. if (len > 1 && !subMesh._checkCollision(collider))
  16351. continue;
  16352. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16353. }
  16354. return this;
  16355. };
  16356. AbstractMesh.prototype._checkCollision = function (collider) {
  16357. // Bounding box test
  16358. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16359. return this;
  16360. // Transformation matrix
  16361. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16362. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16363. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16364. return this;
  16365. };
  16366. // Picking
  16367. AbstractMesh.prototype._generatePointsArray = function () {
  16368. return false;
  16369. };
  16370. /**
  16371. * Checks if the passed Ray intersects with the mesh.
  16372. * Returns an object PickingInfo.
  16373. */
  16374. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16375. var pickingInfo = new BABYLON.PickingInfo();
  16376. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16377. return pickingInfo;
  16378. }
  16379. if (!this._generatePointsArray()) {
  16380. return pickingInfo;
  16381. }
  16382. var intersectInfo = null;
  16383. // Octrees
  16384. var subMeshes;
  16385. var len;
  16386. if (this._submeshesOctree && this.useOctreeForPicking) {
  16387. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16388. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16389. len = intersections.length;
  16390. subMeshes = intersections.data;
  16391. }
  16392. else {
  16393. subMeshes = this.subMeshes;
  16394. len = subMeshes.length;
  16395. }
  16396. for (var index = 0; index < len; index++) {
  16397. var subMesh = subMeshes[index];
  16398. // Bounding test
  16399. if (len > 1 && !subMesh.canIntersects(ray))
  16400. continue;
  16401. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16402. if (currentIntersectInfo) {
  16403. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16404. intersectInfo = currentIntersectInfo;
  16405. intersectInfo.subMeshId = index;
  16406. if (fastCheck) {
  16407. break;
  16408. }
  16409. }
  16410. }
  16411. }
  16412. if (intersectInfo) {
  16413. // Get picked point
  16414. var world = this.getWorldMatrix();
  16415. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16416. var direction = ray.direction.clone();
  16417. direction = direction.scale(intersectInfo.distance);
  16418. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16419. var pickedPoint = worldOrigin.add(worldDirection);
  16420. // Return result
  16421. pickingInfo.hit = true;
  16422. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16423. pickingInfo.pickedPoint = pickedPoint;
  16424. pickingInfo.pickedMesh = this;
  16425. pickingInfo.bu = intersectInfo.bu || 0;
  16426. pickingInfo.bv = intersectInfo.bv || 0;
  16427. pickingInfo.faceId = intersectInfo.faceId;
  16428. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16429. return pickingInfo;
  16430. }
  16431. return pickingInfo;
  16432. };
  16433. /**
  16434. * Clones the mesh, used by the class Mesh.
  16435. * Just returns `null` for an AbstractMesh.
  16436. */
  16437. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16438. return null;
  16439. };
  16440. /**
  16441. * Disposes all the mesh submeshes.
  16442. * Returns the AbstractMesh.
  16443. */
  16444. AbstractMesh.prototype.releaseSubMeshes = function () {
  16445. if (this.subMeshes) {
  16446. while (this.subMeshes.length) {
  16447. this.subMeshes[0].dispose();
  16448. }
  16449. }
  16450. else {
  16451. this.subMeshes = new Array();
  16452. }
  16453. return this;
  16454. };
  16455. /**
  16456. * Disposes the AbstractMesh.
  16457. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16458. * Returns nothing.
  16459. */
  16460. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16461. var _this = this;
  16462. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16463. var index;
  16464. // Action manager
  16465. if (this.actionManager !== undefined && this.actionManager !== null) {
  16466. this.actionManager.dispose();
  16467. this.actionManager = null;
  16468. }
  16469. // Skeleton
  16470. this.skeleton = null;
  16471. // Physics
  16472. if (this.physicsImpostor) {
  16473. this.physicsImpostor.dispose();
  16474. }
  16475. // Intersections in progress
  16476. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16477. var other = this._intersectionsInProgress[index];
  16478. var pos = other._intersectionsInProgress.indexOf(this);
  16479. other._intersectionsInProgress.splice(pos, 1);
  16480. }
  16481. this._intersectionsInProgress = [];
  16482. // Lights
  16483. var lights = this.getScene().lights;
  16484. lights.forEach(function (light) {
  16485. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16486. if (meshIndex !== -1) {
  16487. light.includedOnlyMeshes.splice(meshIndex, 1);
  16488. }
  16489. meshIndex = light.excludedMeshes.indexOf(_this);
  16490. if (meshIndex !== -1) {
  16491. light.excludedMeshes.splice(meshIndex, 1);
  16492. }
  16493. // Shadow generators
  16494. var generator = light.getShadowGenerator();
  16495. if (generator) {
  16496. var shadowMap = generator.getShadowMap();
  16497. if (shadowMap && shadowMap.renderList) {
  16498. meshIndex = shadowMap.renderList.indexOf(_this);
  16499. if (meshIndex !== -1) {
  16500. shadowMap.renderList.splice(meshIndex, 1);
  16501. }
  16502. }
  16503. }
  16504. });
  16505. // Edges
  16506. if (this._edgesRenderer) {
  16507. this._edgesRenderer.dispose();
  16508. this._edgesRenderer = null;
  16509. }
  16510. // SubMeshes
  16511. if (this.getClassName() !== "InstancedMesh") {
  16512. this.releaseSubMeshes();
  16513. }
  16514. // Octree
  16515. var sceneOctree = this.getScene().selectionOctree;
  16516. if (sceneOctree !== undefined && sceneOctree !== null) {
  16517. var index = sceneOctree.dynamicContent.indexOf(this);
  16518. if (index !== -1) {
  16519. sceneOctree.dynamicContent.splice(index, 1);
  16520. }
  16521. }
  16522. // Query
  16523. var engine = this.getScene().getEngine();
  16524. if (this._occlusionQuery) {
  16525. this._isOcclusionQueryInProgress = false;
  16526. engine.deleteQuery(this._occlusionQuery);
  16527. this._occlusionQuery = null;
  16528. }
  16529. // Engine
  16530. engine.wipeCaches();
  16531. // Remove from scene
  16532. this.getScene().removeMesh(this);
  16533. if (disposeMaterialAndTextures) {
  16534. if (this.material) {
  16535. this.material.dispose(false, true);
  16536. }
  16537. }
  16538. if (!doNotRecurse) {
  16539. // Particles
  16540. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16541. if (this.getScene().particleSystems[index].emitter === this) {
  16542. this.getScene().particleSystems[index].dispose();
  16543. index--;
  16544. }
  16545. }
  16546. }
  16547. // facet data
  16548. if (this._facetDataEnabled) {
  16549. this.disableFacetData();
  16550. }
  16551. this.onAfterWorldMatrixUpdateObservable.clear();
  16552. this.onCollideObservable.clear();
  16553. this.onCollisionPositionChangeObservable.clear();
  16554. this._isDisposed = true;
  16555. _super.prototype.dispose.call(this, doNotRecurse);
  16556. };
  16557. /**
  16558. * Adds the passed mesh as a child to the current mesh.
  16559. * Returns the AbstractMesh.
  16560. */
  16561. AbstractMesh.prototype.addChild = function (mesh) {
  16562. mesh.setParent(this);
  16563. return this;
  16564. };
  16565. /**
  16566. * Removes the passed mesh from the current mesh children list.
  16567. * Returns the AbstractMesh.
  16568. */
  16569. AbstractMesh.prototype.removeChild = function (mesh) {
  16570. mesh.setParent(null);
  16571. return this;
  16572. };
  16573. // Facet data
  16574. /**
  16575. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16576. * Returns the AbstractMesh.
  16577. */
  16578. AbstractMesh.prototype._initFacetData = function () {
  16579. if (!this._facetNormals) {
  16580. this._facetNormals = new Array();
  16581. }
  16582. if (!this._facetPositions) {
  16583. this._facetPositions = new Array();
  16584. }
  16585. if (!this._facetPartitioning) {
  16586. this._facetPartitioning = new Array();
  16587. }
  16588. this._facetNb = (this.getIndices().length / 3) | 0;
  16589. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16590. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16591. for (var f = 0; f < this._facetNb; f++) {
  16592. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16593. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16594. }
  16595. this._facetDataEnabled = true;
  16596. return this;
  16597. };
  16598. /**
  16599. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16600. * This method can be called within the render loop.
  16601. * 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.
  16602. * Returns the AbstractMesh.
  16603. */
  16604. AbstractMesh.prototype.updateFacetData = function () {
  16605. if (!this._facetDataEnabled) {
  16606. this._initFacetData();
  16607. }
  16608. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16609. var indices = this.getIndices();
  16610. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16611. var bInfo = this.getBoundingInfo();
  16612. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16613. // init arrays, matrix and sort function on first call
  16614. this._facetDepthSortEnabled = true;
  16615. if (indices instanceof Uint16Array) {
  16616. this._depthSortedIndices = new Uint16Array(indices);
  16617. }
  16618. else if (indices instanceof Uint32Array) {
  16619. this._depthSortedIndices = new Uint32Array(indices);
  16620. }
  16621. else {
  16622. var needs32bits = false;
  16623. for (var i = 0; i < indices.length; i++) {
  16624. if (indices[i] > 65535) {
  16625. needs32bits = true;
  16626. break;
  16627. }
  16628. }
  16629. if (needs32bits) {
  16630. this._depthSortedIndices = new Uint32Array(indices);
  16631. }
  16632. else {
  16633. this._depthSortedIndices = new Uint16Array(indices);
  16634. }
  16635. }
  16636. this._facetDepthSortFunction = function (f1, f2) {
  16637. return (f2.sqDistance - f1.sqDistance);
  16638. };
  16639. if (!this._facetDepthSortFrom) {
  16640. var camera = this.getScene().activeCamera;
  16641. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16642. }
  16643. this._depthSortedFacets = [];
  16644. for (var f = 0; f < this._facetNb; f++) {
  16645. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16646. this._depthSortedFacets.push(depthSortedFacet);
  16647. }
  16648. this._invertedMatrix = BABYLON.Matrix.Identity();
  16649. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16650. }
  16651. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16652. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16653. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16654. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16655. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16656. this._subDiv.max = this._partitioningSubdivisions;
  16657. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16658. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16659. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16660. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16661. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16662. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16663. // set the parameters for ComputeNormals()
  16664. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16665. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16666. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16667. this._facetParameters.bInfo = bInfo;
  16668. this._facetParameters.bbSize = this._bbSize;
  16669. this._facetParameters.subDiv = this._subDiv;
  16670. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16671. this._facetParameters.depthSort = this._facetDepthSort;
  16672. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16673. this.computeWorldMatrix(true);
  16674. this._worldMatrix.invertToRef(this._invertedMatrix);
  16675. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16676. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16677. }
  16678. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16679. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16680. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16681. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16682. var l = (this._depthSortedIndices.length / 3) | 0;
  16683. for (var f = 0; f < l; f++) {
  16684. var sind = this._depthSortedFacets[f].ind;
  16685. this._depthSortedIndices[f * 3] = indices[sind];
  16686. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16687. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16688. }
  16689. this.updateIndices(this._depthSortedIndices);
  16690. }
  16691. return this;
  16692. };
  16693. /**
  16694. * Returns the facetLocalNormals array.
  16695. * The normals are expressed in the mesh local space.
  16696. */
  16697. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16698. if (!this._facetNormals) {
  16699. this.updateFacetData();
  16700. }
  16701. return this._facetNormals;
  16702. };
  16703. /**
  16704. * Returns the facetLocalPositions array.
  16705. * The facet positions are expressed in the mesh local space.
  16706. */
  16707. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16708. if (!this._facetPositions) {
  16709. this.updateFacetData();
  16710. }
  16711. return this._facetPositions;
  16712. };
  16713. /**
  16714. * Returns the facetLocalPartioning array.
  16715. */
  16716. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16717. if (!this._facetPartitioning) {
  16718. this.updateFacetData();
  16719. }
  16720. return this._facetPartitioning;
  16721. };
  16722. /**
  16723. * Returns the i-th facet position in the world system.
  16724. * This method allocates a new Vector3 per call.
  16725. */
  16726. AbstractMesh.prototype.getFacetPosition = function (i) {
  16727. var pos = BABYLON.Vector3.Zero();
  16728. this.getFacetPositionToRef(i, pos);
  16729. return pos;
  16730. };
  16731. /**
  16732. * Sets the reference Vector3 with the i-th facet position in the world system.
  16733. * Returns the AbstractMesh.
  16734. */
  16735. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16736. var localPos = (this.getFacetLocalPositions())[i];
  16737. var world = this.getWorldMatrix();
  16738. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16739. return this;
  16740. };
  16741. /**
  16742. * Returns the i-th facet normal in the world system.
  16743. * This method allocates a new Vector3 per call.
  16744. */
  16745. AbstractMesh.prototype.getFacetNormal = function (i) {
  16746. var norm = BABYLON.Vector3.Zero();
  16747. this.getFacetNormalToRef(i, norm);
  16748. return norm;
  16749. };
  16750. /**
  16751. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16752. * Returns the AbstractMesh.
  16753. */
  16754. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16755. var localNorm = (this.getFacetLocalNormals())[i];
  16756. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16757. return this;
  16758. };
  16759. /**
  16760. * 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).
  16761. */
  16762. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16763. var bInfo = this.getBoundingInfo();
  16764. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16765. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16766. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16767. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16768. return null;
  16769. }
  16770. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16771. };
  16772. /**
  16773. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16774. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16775. * 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.
  16776. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16777. * 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.
  16778. */
  16779. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16780. if (checkFace === void 0) { checkFace = false; }
  16781. if (facing === void 0) { facing = true; }
  16782. var world = this.getWorldMatrix();
  16783. var invMat = BABYLON.Tmp.Matrix[5];
  16784. world.invertToRef(invMat);
  16785. var invVect = BABYLON.Tmp.Vector3[8];
  16786. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16787. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16788. if (projected) {
  16789. // tranform the local computed projected vector to world coordinates
  16790. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16791. }
  16792. return closest;
  16793. };
  16794. /**
  16795. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16796. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16797. * 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.
  16798. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16799. * 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.
  16800. */
  16801. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16802. if (checkFace === void 0) { checkFace = false; }
  16803. if (facing === void 0) { facing = true; }
  16804. var closest = null;
  16805. var tmpx = 0.0;
  16806. var tmpy = 0.0;
  16807. var tmpz = 0.0;
  16808. var d = 0.0; // tmp dot facet normal * facet position
  16809. var t0 = 0.0;
  16810. var projx = 0.0;
  16811. var projy = 0.0;
  16812. var projz = 0.0;
  16813. // Get all the facets in the same partitioning block than (x, y, z)
  16814. var facetPositions = this.getFacetLocalPositions();
  16815. var facetNormals = this.getFacetLocalNormals();
  16816. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16817. if (!facetsInBlock) {
  16818. return null;
  16819. }
  16820. // Get the closest facet to (x, y, z)
  16821. var shortest = Number.MAX_VALUE; // init distance vars
  16822. var tmpDistance = shortest;
  16823. var fib; // current facet in the block
  16824. var norm; // current facet normal
  16825. var p0; // current facet barycenter position
  16826. // loop on all the facets in the current partitioning block
  16827. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16828. fib = facetsInBlock[idx];
  16829. norm = facetNormals[fib];
  16830. p0 = facetPositions[fib];
  16831. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16832. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16833. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16834. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16835. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16836. projx = x + norm.x * t0;
  16837. projy = y + norm.y * t0;
  16838. projz = z + norm.z * t0;
  16839. tmpx = projx - x;
  16840. tmpy = projy - y;
  16841. tmpz = projz - z;
  16842. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16843. if (tmpDistance < shortest) {
  16844. shortest = tmpDistance;
  16845. closest = fib;
  16846. if (projected) {
  16847. projected.x = projx;
  16848. projected.y = projy;
  16849. projected.z = projz;
  16850. }
  16851. }
  16852. }
  16853. }
  16854. return closest;
  16855. };
  16856. /**
  16857. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16858. */
  16859. AbstractMesh.prototype.getFacetDataParameters = function () {
  16860. return this._facetParameters;
  16861. };
  16862. /**
  16863. * Disables the feature FacetData and frees the related memory.
  16864. * Returns the AbstractMesh.
  16865. */
  16866. AbstractMesh.prototype.disableFacetData = function () {
  16867. if (this._facetDataEnabled) {
  16868. this._facetDataEnabled = false;
  16869. this._facetPositions = new Array();
  16870. this._facetNormals = new Array();
  16871. this._facetPartitioning = new Array();
  16872. this._facetParameters = null;
  16873. this._depthSortedIndices = new Uint32Array(0);
  16874. }
  16875. return this;
  16876. };
  16877. /**
  16878. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16879. * Returns the mesh.
  16880. */
  16881. AbstractMesh.prototype.updateIndices = function (indices) {
  16882. return this;
  16883. };
  16884. /**
  16885. * The mesh Geometry. Actually used by the Mesh object.
  16886. * Returns a blank geometry object.
  16887. */
  16888. /**
  16889. * Creates new normals data for the mesh.
  16890. * @param updatable.
  16891. */
  16892. AbstractMesh.prototype.createNormals = function (updatable) {
  16893. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16894. var indices = this.getIndices();
  16895. var normals;
  16896. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16897. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16898. }
  16899. else {
  16900. normals = [];
  16901. }
  16902. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16903. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16904. };
  16905. /**
  16906. * Align the mesh with a normal.
  16907. * Returns the mesh.
  16908. */
  16909. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16910. if (!upDirection) {
  16911. upDirection = BABYLON.Axis.Y;
  16912. }
  16913. var axisX = BABYLON.Tmp.Vector3[0];
  16914. var axisZ = BABYLON.Tmp.Vector3[1];
  16915. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16916. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16917. if (this.rotationQuaternion) {
  16918. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16919. }
  16920. else {
  16921. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16922. }
  16923. return this;
  16924. };
  16925. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16926. var engine = this.getEngine();
  16927. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16928. this._isOccluded = false;
  16929. return;
  16930. }
  16931. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16932. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16933. if (isOcclusionQueryAvailable) {
  16934. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16935. this._isOcclusionQueryInProgress = false;
  16936. this._occlusionInternalRetryCounter = 0;
  16937. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16938. }
  16939. else {
  16940. this._occlusionInternalRetryCounter++;
  16941. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16942. this._isOcclusionQueryInProgress = false;
  16943. this._occlusionInternalRetryCounter = 0;
  16944. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16945. // if strict continue the last state of the object.
  16946. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16947. }
  16948. else {
  16949. return;
  16950. }
  16951. }
  16952. }
  16953. var scene = this.getScene();
  16954. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16955. if (!this._occlusionQuery) {
  16956. this._occlusionQuery = engine.createQuery();
  16957. }
  16958. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16959. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16960. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16961. this._isOcclusionQueryInProgress = true;
  16962. };
  16963. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16964. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16965. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16966. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16967. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16968. return AbstractMesh;
  16969. }(BABYLON.TransformNode));
  16970. BABYLON.AbstractMesh = AbstractMesh;
  16971. })(BABYLON || (BABYLON = {}));
  16972. //# sourceMappingURL=babylon.abstractMesh.js.map
  16973. var BABYLON;
  16974. (function (BABYLON) {
  16975. var Light = /** @class */ (function (_super) {
  16976. __extends(Light, _super);
  16977. /**
  16978. * Creates a Light object in the scene.
  16979. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16980. */
  16981. function Light(name, scene) {
  16982. var _this = _super.call(this, name, scene) || this;
  16983. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16984. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16985. _this.intensity = 1.0;
  16986. _this.range = Number.MAX_VALUE;
  16987. /**
  16988. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16989. * of light.
  16990. */
  16991. _this._photometricScale = 1.0;
  16992. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16993. _this._radius = 0.00001;
  16994. _this.renderPriority = 0;
  16995. /**
  16996. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16997. * the current shadow generator.
  16998. */
  16999. _this.shadowEnabled = true;
  17000. _this._excludeWithLayerMask = 0;
  17001. _this._includeOnlyWithLayerMask = 0;
  17002. _this._lightmapMode = 0;
  17003. _this._excludedMeshesIds = new Array();
  17004. _this._includedOnlyMeshesIds = new Array();
  17005. _this.getScene().addLight(_this);
  17006. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17007. _this._buildUniformLayout();
  17008. _this.includedOnlyMeshes = new Array();
  17009. _this.excludedMeshes = new Array();
  17010. _this._resyncMeshes();
  17011. return _this;
  17012. }
  17013. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17014. /**
  17015. * If every light affecting the material is in this lightmapMode,
  17016. * material.lightmapTexture adds or multiplies
  17017. * (depends on material.useLightmapAsShadowmap)
  17018. * after every other light calculations.
  17019. */
  17020. get: function () {
  17021. return Light._LIGHTMAP_DEFAULT;
  17022. },
  17023. enumerable: true,
  17024. configurable: true
  17025. });
  17026. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17027. /**
  17028. * material.lightmapTexture as only diffuse lighting from this light
  17029. * adds pnly specular lighting from this light
  17030. * adds dynamic shadows
  17031. */
  17032. get: function () {
  17033. return Light._LIGHTMAP_SPECULAR;
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17039. /**
  17040. * material.lightmapTexture as only lighting
  17041. * no light calculation from this light
  17042. * only adds dynamic shadows from this light
  17043. */
  17044. get: function () {
  17045. return Light._LIGHTMAP_SHADOWSONLY;
  17046. },
  17047. enumerable: true,
  17048. configurable: true
  17049. });
  17050. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17051. /**
  17052. * Each light type uses the default quantity according to its type:
  17053. * point/spot lights use luminous intensity
  17054. * directional lights use illuminance
  17055. */
  17056. get: function () {
  17057. return Light._INTENSITYMODE_AUTOMATIC;
  17058. },
  17059. enumerable: true,
  17060. configurable: true
  17061. });
  17062. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17063. /**
  17064. * lumen (lm)
  17065. */
  17066. get: function () {
  17067. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17068. },
  17069. enumerable: true,
  17070. configurable: true
  17071. });
  17072. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17073. /**
  17074. * candela (lm/sr)
  17075. */
  17076. get: function () {
  17077. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17083. /**
  17084. * lux (lm/m^2)
  17085. */
  17086. get: function () {
  17087. return Light._INTENSITYMODE_ILLUMINANCE;
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17093. /**
  17094. * nit (cd/m^2)
  17095. */
  17096. get: function () {
  17097. return Light._INTENSITYMODE_LUMINANCE;
  17098. },
  17099. enumerable: true,
  17100. configurable: true
  17101. });
  17102. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17103. /**
  17104. * Light type const id of the point light.
  17105. */
  17106. get: function () {
  17107. return Light._LIGHTTYPEID_POINTLIGHT;
  17108. },
  17109. enumerable: true,
  17110. configurable: true
  17111. });
  17112. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17113. /**
  17114. * Light type const id of the directional light.
  17115. */
  17116. get: function () {
  17117. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17118. },
  17119. enumerable: true,
  17120. configurable: true
  17121. });
  17122. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17123. /**
  17124. * Light type const id of the spot light.
  17125. */
  17126. get: function () {
  17127. return Light._LIGHTTYPEID_SPOTLIGHT;
  17128. },
  17129. enumerable: true,
  17130. configurable: true
  17131. });
  17132. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17133. /**
  17134. * Light type const id of the hemispheric light.
  17135. */
  17136. get: function () {
  17137. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17138. },
  17139. enumerable: true,
  17140. configurable: true
  17141. });
  17142. Object.defineProperty(Light.prototype, "intensityMode", {
  17143. /**
  17144. * Gets the photometric scale used to interpret the intensity.
  17145. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17146. */
  17147. get: function () {
  17148. return this._intensityMode;
  17149. },
  17150. /**
  17151. * Sets the photometric scale used to interpret the intensity.
  17152. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17153. */
  17154. set: function (value) {
  17155. this._intensityMode = value;
  17156. this._computePhotometricScale();
  17157. },
  17158. enumerable: true,
  17159. configurable: true
  17160. });
  17161. ;
  17162. ;
  17163. Object.defineProperty(Light.prototype, "radius", {
  17164. /**
  17165. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17166. */
  17167. get: function () {
  17168. return this._radius;
  17169. },
  17170. /**
  17171. * sets the light radius used by PBR Materials to simulate soft area lights.
  17172. */
  17173. set: function (value) {
  17174. this._radius = value;
  17175. this._computePhotometricScale();
  17176. },
  17177. enumerable: true,
  17178. configurable: true
  17179. });
  17180. ;
  17181. ;
  17182. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17183. get: function () {
  17184. return this._includedOnlyMeshes;
  17185. },
  17186. set: function (value) {
  17187. this._includedOnlyMeshes = value;
  17188. this._hookArrayForIncludedOnly(value);
  17189. },
  17190. enumerable: true,
  17191. configurable: true
  17192. });
  17193. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17194. get: function () {
  17195. return this._excludedMeshes;
  17196. },
  17197. set: function (value) {
  17198. this._excludedMeshes = value;
  17199. this._hookArrayForExcluded(value);
  17200. },
  17201. enumerable: true,
  17202. configurable: true
  17203. });
  17204. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17205. get: function () {
  17206. return this._excludeWithLayerMask;
  17207. },
  17208. set: function (value) {
  17209. this._excludeWithLayerMask = value;
  17210. this._resyncMeshes();
  17211. },
  17212. enumerable: true,
  17213. configurable: true
  17214. });
  17215. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17216. get: function () {
  17217. return this._includeOnlyWithLayerMask;
  17218. },
  17219. set: function (value) {
  17220. this._includeOnlyWithLayerMask = value;
  17221. this._resyncMeshes();
  17222. },
  17223. enumerable: true,
  17224. configurable: true
  17225. });
  17226. Object.defineProperty(Light.prototype, "lightmapMode", {
  17227. get: function () {
  17228. return this._lightmapMode;
  17229. },
  17230. set: function (value) {
  17231. if (this._lightmapMode === value) {
  17232. return;
  17233. }
  17234. this._lightmapMode = value;
  17235. this._markMeshesAsLightDirty();
  17236. },
  17237. enumerable: true,
  17238. configurable: true
  17239. });
  17240. Light.prototype._buildUniformLayout = function () {
  17241. // Overridden
  17242. };
  17243. /**
  17244. * Returns the string "Light".
  17245. */
  17246. Light.prototype.getClassName = function () {
  17247. return "Light";
  17248. };
  17249. /**
  17250. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17251. */
  17252. Light.prototype.toString = function (fullDetails) {
  17253. var ret = "Name: " + this.name;
  17254. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17255. if (this.animations) {
  17256. for (var i = 0; i < this.animations.length; i++) {
  17257. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17258. }
  17259. }
  17260. if (fullDetails) {
  17261. }
  17262. return ret;
  17263. };
  17264. /**
  17265. * Set the enabled state of this node.
  17266. * @param {boolean} value - the new enabled state
  17267. * @see isEnabled
  17268. */
  17269. Light.prototype.setEnabled = function (value) {
  17270. _super.prototype.setEnabled.call(this, value);
  17271. this._resyncMeshes();
  17272. };
  17273. /**
  17274. * Returns the Light associated shadow generator.
  17275. */
  17276. Light.prototype.getShadowGenerator = function () {
  17277. return this._shadowGenerator;
  17278. };
  17279. /**
  17280. * Returns a Vector3, the absolute light position in the World.
  17281. */
  17282. Light.prototype.getAbsolutePosition = function () {
  17283. return BABYLON.Vector3.Zero();
  17284. };
  17285. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17286. };
  17287. Light.prototype._getWorldMatrix = function () {
  17288. return BABYLON.Matrix.Identity();
  17289. };
  17290. /**
  17291. * Boolean : True if the light will affect the passed mesh.
  17292. */
  17293. Light.prototype.canAffectMesh = function (mesh) {
  17294. if (!mesh) {
  17295. return true;
  17296. }
  17297. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17298. return false;
  17299. }
  17300. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17301. return false;
  17302. }
  17303. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17304. return false;
  17305. }
  17306. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17307. return false;
  17308. }
  17309. return true;
  17310. };
  17311. /**
  17312. * Returns the light World matrix.
  17313. */
  17314. Light.prototype.getWorldMatrix = function () {
  17315. this._currentRenderId = this.getScene().getRenderId();
  17316. var worldMatrix = this._getWorldMatrix();
  17317. if (this.parent && this.parent.getWorldMatrix) {
  17318. if (!this._parentedWorldMatrix) {
  17319. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17320. }
  17321. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17322. this._markSyncedWithParent();
  17323. return this._parentedWorldMatrix;
  17324. }
  17325. return worldMatrix;
  17326. };
  17327. /**
  17328. * Sort function to order lights for rendering.
  17329. * @param a First Light object to compare to second.
  17330. * @param b Second Light object to compare first.
  17331. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17332. */
  17333. Light.compareLightsPriority = function (a, b) {
  17334. //shadow-casting lights have priority over non-shadow-casting lights
  17335. //the renderPrioirty is a secondary sort criterion
  17336. if (a.shadowEnabled !== b.shadowEnabled) {
  17337. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17338. }
  17339. return b.renderPriority - a.renderPriority;
  17340. };
  17341. /**
  17342. * Disposes the light.
  17343. */
  17344. Light.prototype.dispose = function () {
  17345. if (this._shadowGenerator) {
  17346. this._shadowGenerator.dispose();
  17347. this._shadowGenerator = null;
  17348. }
  17349. // Animations
  17350. this.getScene().stopAnimation(this);
  17351. this._uniformBuffer.dispose();
  17352. // Remove from scene
  17353. this.getScene().removeLight(this);
  17354. _super.prototype.dispose.call(this);
  17355. };
  17356. /**
  17357. * Returns the light type ID (integer).
  17358. */
  17359. Light.prototype.getTypeID = function () {
  17360. return 0;
  17361. };
  17362. /**
  17363. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17364. */
  17365. Light.prototype.getScaledIntensity = function () {
  17366. return this._photometricScale * this.intensity;
  17367. };
  17368. /**
  17369. * Returns a new Light object, named "name", from the current one.
  17370. */
  17371. Light.prototype.clone = function (name) {
  17372. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17373. if (!constructor) {
  17374. return null;
  17375. }
  17376. return BABYLON.SerializationHelper.Clone(constructor, this);
  17377. };
  17378. /**
  17379. * Serializes the current light into a Serialization object.
  17380. * Returns the serialized object.
  17381. */
  17382. Light.prototype.serialize = function () {
  17383. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17384. // Type
  17385. serializationObject.type = this.getTypeID();
  17386. // Parent
  17387. if (this.parent) {
  17388. serializationObject.parentId = this.parent.id;
  17389. }
  17390. // Inclusion / exclusions
  17391. if (this.excludedMeshes.length > 0) {
  17392. serializationObject.excludedMeshesIds = [];
  17393. this.excludedMeshes.forEach(function (mesh) {
  17394. serializationObject.excludedMeshesIds.push(mesh.id);
  17395. });
  17396. }
  17397. if (this.includedOnlyMeshes.length > 0) {
  17398. serializationObject.includedOnlyMeshesIds = [];
  17399. this.includedOnlyMeshes.forEach(function (mesh) {
  17400. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17401. });
  17402. }
  17403. // Animations
  17404. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17405. serializationObject.ranges = this.serializeAnimationRanges();
  17406. return serializationObject;
  17407. };
  17408. /**
  17409. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17410. * This new light is named "name" and added to the passed scene.
  17411. */
  17412. Light.GetConstructorFromName = function (type, name, scene) {
  17413. switch (type) {
  17414. case 0:
  17415. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17416. case 1:
  17417. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17418. case 2:
  17419. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17420. case 3:
  17421. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17422. }
  17423. return null;
  17424. };
  17425. /**
  17426. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17427. */
  17428. Light.Parse = function (parsedLight, scene) {
  17429. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17430. if (!constructor) {
  17431. return null;
  17432. }
  17433. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17434. // Inclusion / exclusions
  17435. if (parsedLight.excludedMeshesIds) {
  17436. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17437. }
  17438. if (parsedLight.includedOnlyMeshesIds) {
  17439. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17440. }
  17441. // Parent
  17442. if (parsedLight.parentId) {
  17443. light._waitingParentId = parsedLight.parentId;
  17444. }
  17445. // Animations
  17446. if (parsedLight.animations) {
  17447. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17448. var parsedAnimation = parsedLight.animations[animationIndex];
  17449. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17450. }
  17451. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17452. }
  17453. if (parsedLight.autoAnimate) {
  17454. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17455. }
  17456. return light;
  17457. };
  17458. Light.prototype._hookArrayForExcluded = function (array) {
  17459. var _this = this;
  17460. var oldPush = array.push;
  17461. array.push = function () {
  17462. var items = [];
  17463. for (var _i = 0; _i < arguments.length; _i++) {
  17464. items[_i] = arguments[_i];
  17465. }
  17466. var result = oldPush.apply(array, items);
  17467. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17468. var item = items_1[_a];
  17469. item._resyncLighSource(_this);
  17470. }
  17471. return result;
  17472. };
  17473. var oldSplice = array.splice;
  17474. array.splice = function (index, deleteCount) {
  17475. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17476. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17477. var item = deleted_1[_i];
  17478. item._resyncLighSource(_this);
  17479. }
  17480. return deleted;
  17481. };
  17482. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17483. var item = array_1[_i];
  17484. item._resyncLighSource(this);
  17485. }
  17486. };
  17487. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17488. var _this = this;
  17489. var oldPush = array.push;
  17490. array.push = function () {
  17491. var items = [];
  17492. for (var _i = 0; _i < arguments.length; _i++) {
  17493. items[_i] = arguments[_i];
  17494. }
  17495. var result = oldPush.apply(array, items);
  17496. _this._resyncMeshes();
  17497. return result;
  17498. };
  17499. var oldSplice = array.splice;
  17500. array.splice = function (index, deleteCount) {
  17501. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17502. _this._resyncMeshes();
  17503. return deleted;
  17504. };
  17505. this._resyncMeshes();
  17506. };
  17507. Light.prototype._resyncMeshes = function () {
  17508. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17509. var mesh = _a[_i];
  17510. mesh._resyncLighSource(this);
  17511. }
  17512. };
  17513. Light.prototype._markMeshesAsLightDirty = function () {
  17514. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17515. var mesh = _a[_i];
  17516. if (mesh._lightSources.indexOf(this) !== -1) {
  17517. mesh._markSubMeshesAsLightDirty();
  17518. }
  17519. }
  17520. };
  17521. /**
  17522. * Recomputes the cached photometric scale if needed.
  17523. */
  17524. Light.prototype._computePhotometricScale = function () {
  17525. this._photometricScale = this._getPhotometricScale();
  17526. this.getScene().resetCachedMaterial();
  17527. };
  17528. /**
  17529. * Returns the Photometric Scale according to the light type and intensity mode.
  17530. */
  17531. Light.prototype._getPhotometricScale = function () {
  17532. var photometricScale = 0.0;
  17533. var lightTypeID = this.getTypeID();
  17534. //get photometric mode
  17535. var photometricMode = this.intensityMode;
  17536. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17537. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17538. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17539. }
  17540. else {
  17541. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17542. }
  17543. }
  17544. //compute photometric scale
  17545. switch (lightTypeID) {
  17546. case Light.LIGHTTYPEID_POINTLIGHT:
  17547. case Light.LIGHTTYPEID_SPOTLIGHT:
  17548. switch (photometricMode) {
  17549. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17550. photometricScale = 1.0 / (4.0 * Math.PI);
  17551. break;
  17552. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17553. photometricScale = 1.0;
  17554. break;
  17555. case Light.INTENSITYMODE_LUMINANCE:
  17556. photometricScale = this.radius * this.radius;
  17557. break;
  17558. }
  17559. break;
  17560. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17561. switch (photometricMode) {
  17562. case Light.INTENSITYMODE_ILLUMINANCE:
  17563. photometricScale = 1.0;
  17564. break;
  17565. case Light.INTENSITYMODE_LUMINANCE:
  17566. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17567. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17568. var apexAngleRadians = this.radius;
  17569. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17570. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17571. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17572. photometricScale = solidAngle;
  17573. break;
  17574. }
  17575. break;
  17576. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17577. // No fall off in hemisperic light.
  17578. photometricScale = 1.0;
  17579. break;
  17580. }
  17581. return photometricScale;
  17582. };
  17583. Light.prototype._reorderLightsInScene = function () {
  17584. var scene = this.getScene();
  17585. if (this._renderPriority != 0) {
  17586. scene.requireLightSorting = true;
  17587. }
  17588. this.getScene().sortLightsByPriority();
  17589. };
  17590. //lightmapMode Consts
  17591. Light._LIGHTMAP_DEFAULT = 0;
  17592. Light._LIGHTMAP_SPECULAR = 1;
  17593. Light._LIGHTMAP_SHADOWSONLY = 2;
  17594. // Intensity Mode Consts
  17595. Light._INTENSITYMODE_AUTOMATIC = 0;
  17596. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17597. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17598. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17599. Light._INTENSITYMODE_LUMINANCE = 4;
  17600. // Light types ids const.
  17601. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17602. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17603. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17604. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17605. __decorate([
  17606. BABYLON.serializeAsColor3()
  17607. ], Light.prototype, "diffuse", void 0);
  17608. __decorate([
  17609. BABYLON.serializeAsColor3()
  17610. ], Light.prototype, "specular", void 0);
  17611. __decorate([
  17612. BABYLON.serialize()
  17613. ], Light.prototype, "intensity", void 0);
  17614. __decorate([
  17615. BABYLON.serialize()
  17616. ], Light.prototype, "range", void 0);
  17617. __decorate([
  17618. BABYLON.serialize()
  17619. ], Light.prototype, "intensityMode", null);
  17620. __decorate([
  17621. BABYLON.serialize()
  17622. ], Light.prototype, "radius", null);
  17623. __decorate([
  17624. BABYLON.serialize()
  17625. ], Light.prototype, "_renderPriority", void 0);
  17626. __decorate([
  17627. BABYLON.expandToProperty("_reorderLightsInScene")
  17628. ], Light.prototype, "renderPriority", void 0);
  17629. __decorate([
  17630. BABYLON.serialize()
  17631. ], Light.prototype, "shadowEnabled", void 0);
  17632. __decorate([
  17633. BABYLON.serialize("excludeWithLayerMask")
  17634. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17635. __decorate([
  17636. BABYLON.serialize("includeOnlyWithLayerMask")
  17637. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17638. __decorate([
  17639. BABYLON.serialize("lightmapMode")
  17640. ], Light.prototype, "_lightmapMode", void 0);
  17641. return Light;
  17642. }(BABYLON.Node));
  17643. BABYLON.Light = Light;
  17644. })(BABYLON || (BABYLON = {}));
  17645. //# sourceMappingURL=babylon.light.js.map
  17646. var BABYLON;
  17647. (function (BABYLON) {
  17648. var Camera = /** @class */ (function (_super) {
  17649. __extends(Camera, _super);
  17650. function Camera(name, position, scene) {
  17651. var _this = _super.call(this, name, scene) || this;
  17652. _this.upVector = BABYLON.Vector3.Up();
  17653. _this.orthoLeft = null;
  17654. _this.orthoRight = null;
  17655. _this.orthoBottom = null;
  17656. _this.orthoTop = null;
  17657. /**
  17658. * default : 0.8
  17659. * FOV is set in Radians.
  17660. */
  17661. _this.fov = 0.8;
  17662. _this.minZ = 1;
  17663. _this.maxZ = 10000.0;
  17664. _this.inertia = 0.9;
  17665. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17666. _this.isIntermediate = false;
  17667. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17668. /**
  17669. * Restricts the camera to viewing objects with the same layerMask.
  17670. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17671. */
  17672. _this.layerMask = 0x0FFFFFFF;
  17673. /**
  17674. * default : FOVMODE_VERTICAL_FIXED
  17675. * fovMode sets the camera frustum bounds to the viewport bounds.
  17676. */
  17677. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17678. // Camera rig members
  17679. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17680. _this._rigCameras = new Array();
  17681. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17682. _this._skipRendering = false;
  17683. _this.customRenderTargets = new Array();
  17684. // Observables
  17685. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17686. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17687. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17688. _this.onRestoreStateObservable = new BABYLON.Observable();
  17689. // Cache
  17690. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17691. _this._projectionMatrix = new BABYLON.Matrix();
  17692. _this._doNotComputeProjectionMatrix = false;
  17693. _this._postProcesses = new Array();
  17694. _this._transformMatrix = BABYLON.Matrix.Zero();
  17695. _this._activeMeshes = new BABYLON.SmartArray(256);
  17696. _this._globalPosition = BABYLON.Vector3.Zero();
  17697. _this._refreshFrustumPlanes = true;
  17698. _this.getScene().addCamera(_this);
  17699. if (!_this.getScene().activeCamera) {
  17700. _this.getScene().activeCamera = _this;
  17701. }
  17702. _this.position = position;
  17703. return _this;
  17704. }
  17705. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17706. get: function () {
  17707. return Camera._PERSPECTIVE_CAMERA;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17713. get: function () {
  17714. return Camera._ORTHOGRAPHIC_CAMERA;
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17720. /**
  17721. * This is the default FOV mode for perspective cameras.
  17722. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17723. *
  17724. */
  17725. get: function () {
  17726. return Camera._FOVMODE_VERTICAL_FIXED;
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17732. /**
  17733. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17734. *
  17735. */
  17736. get: function () {
  17737. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17743. get: function () {
  17744. return Camera._RIG_MODE_NONE;
  17745. },
  17746. enumerable: true,
  17747. configurable: true
  17748. });
  17749. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17750. get: function () {
  17751. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17757. get: function () {
  17758. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17764. get: function () {
  17765. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17771. get: function () {
  17772. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17778. get: function () {
  17779. return Camera._RIG_MODE_VR;
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17785. get: function () {
  17786. return Camera._RIG_MODE_WEBVR;
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. /**
  17792. * Store current camera state (fov, position, etc..)
  17793. */
  17794. Camera.prototype.storeState = function () {
  17795. this._stateStored = true;
  17796. this._storedFov = this.fov;
  17797. return this;
  17798. };
  17799. /**
  17800. * Restores the camera state values if it has been stored. You must call storeState() first
  17801. */
  17802. Camera.prototype._restoreStateValues = function () {
  17803. if (!this._stateStored) {
  17804. return false;
  17805. }
  17806. this.fov = this._storedFov;
  17807. return true;
  17808. };
  17809. /**
  17810. * Restored camera state. You must call storeState() first
  17811. */
  17812. Camera.prototype.restoreState = function () {
  17813. if (this._restoreStateValues()) {
  17814. this.onRestoreStateObservable.notifyObservers(this);
  17815. return true;
  17816. }
  17817. return false;
  17818. };
  17819. Camera.prototype.getClassName = function () {
  17820. return "Camera";
  17821. };
  17822. /**
  17823. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17824. */
  17825. Camera.prototype.toString = function (fullDetails) {
  17826. var ret = "Name: " + this.name;
  17827. ret += ", type: " + this.getClassName();
  17828. if (this.animations) {
  17829. for (var i = 0; i < this.animations.length; i++) {
  17830. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17831. }
  17832. }
  17833. if (fullDetails) {
  17834. }
  17835. return ret;
  17836. };
  17837. Object.defineProperty(Camera.prototype, "globalPosition", {
  17838. get: function () {
  17839. return this._globalPosition;
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. Camera.prototype.getActiveMeshes = function () {
  17845. return this._activeMeshes;
  17846. };
  17847. Camera.prototype.isActiveMesh = function (mesh) {
  17848. return (this._activeMeshes.indexOf(mesh) !== -1);
  17849. };
  17850. //Cache
  17851. Camera.prototype._initCache = function () {
  17852. _super.prototype._initCache.call(this);
  17853. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17854. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17855. this._cache.mode = undefined;
  17856. this._cache.minZ = undefined;
  17857. this._cache.maxZ = undefined;
  17858. this._cache.fov = undefined;
  17859. this._cache.fovMode = undefined;
  17860. this._cache.aspectRatio = undefined;
  17861. this._cache.orthoLeft = undefined;
  17862. this._cache.orthoRight = undefined;
  17863. this._cache.orthoBottom = undefined;
  17864. this._cache.orthoTop = undefined;
  17865. this._cache.renderWidth = undefined;
  17866. this._cache.renderHeight = undefined;
  17867. };
  17868. Camera.prototype._updateCache = function (ignoreParentClass) {
  17869. if (!ignoreParentClass) {
  17870. _super.prototype._updateCache.call(this);
  17871. }
  17872. this._cache.position.copyFrom(this.position);
  17873. this._cache.upVector.copyFrom(this.upVector);
  17874. };
  17875. // Synchronized
  17876. Camera.prototype._isSynchronized = function () {
  17877. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17878. };
  17879. Camera.prototype._isSynchronizedViewMatrix = function () {
  17880. if (!_super.prototype._isSynchronized.call(this))
  17881. return false;
  17882. return this._cache.position.equals(this.position)
  17883. && this._cache.upVector.equals(this.upVector)
  17884. && this.isSynchronizedWithParent();
  17885. };
  17886. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17887. var check = this._cache.mode === this.mode
  17888. && this._cache.minZ === this.minZ
  17889. && this._cache.maxZ === this.maxZ;
  17890. if (!check) {
  17891. return false;
  17892. }
  17893. var engine = this.getEngine();
  17894. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17895. check = this._cache.fov === this.fov
  17896. && this._cache.fovMode === this.fovMode
  17897. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17898. }
  17899. else {
  17900. check = this._cache.orthoLeft === this.orthoLeft
  17901. && this._cache.orthoRight === this.orthoRight
  17902. && this._cache.orthoBottom === this.orthoBottom
  17903. && this._cache.orthoTop === this.orthoTop
  17904. && this._cache.renderWidth === engine.getRenderWidth()
  17905. && this._cache.renderHeight === engine.getRenderHeight();
  17906. }
  17907. return check;
  17908. };
  17909. // Controls
  17910. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17911. };
  17912. Camera.prototype.detachControl = function (element) {
  17913. };
  17914. Camera.prototype.update = function () {
  17915. this._checkInputs();
  17916. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17917. this._updateRigCameras();
  17918. }
  17919. };
  17920. Camera.prototype._checkInputs = function () {
  17921. this.onAfterCheckInputsObservable.notifyObservers(this);
  17922. };
  17923. Object.defineProperty(Camera.prototype, "rigCameras", {
  17924. get: function () {
  17925. return this._rigCameras;
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17931. get: function () {
  17932. return this._rigPostProcess;
  17933. },
  17934. enumerable: true,
  17935. configurable: true
  17936. });
  17937. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17938. // invalidate framebuffer
  17939. if (this._postProcesses.length > 0) {
  17940. this._postProcesses[0].markTextureDirty();
  17941. }
  17942. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17943. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17944. var cam = this._rigCameras[i];
  17945. var rigPostProcess = cam._rigPostProcess;
  17946. // for VR rig, there does not have to be a post process
  17947. if (rigPostProcess) {
  17948. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17949. if (isPass) {
  17950. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17951. cam.isIntermediate = this._postProcesses.length === 0;
  17952. }
  17953. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17954. rigPostProcess.markTextureDirty();
  17955. }
  17956. else {
  17957. cam._postProcesses = this._postProcesses.slice(0);
  17958. }
  17959. }
  17960. };
  17961. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17962. if (insertAt === void 0) { insertAt = null; }
  17963. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17964. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17965. return 0;
  17966. }
  17967. if (insertAt == null || insertAt < 0) {
  17968. this._postProcesses.push(postProcess);
  17969. }
  17970. else {
  17971. this._postProcesses.splice(insertAt, 0, postProcess);
  17972. }
  17973. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17974. return this._postProcesses.indexOf(postProcess);
  17975. };
  17976. Camera.prototype.detachPostProcess = function (postProcess) {
  17977. var idx = this._postProcesses.indexOf(postProcess);
  17978. if (idx !== -1) {
  17979. this._postProcesses.splice(idx, 1);
  17980. }
  17981. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17982. };
  17983. Camera.prototype.getWorldMatrix = function () {
  17984. if (!this._worldMatrix) {
  17985. this._worldMatrix = BABYLON.Matrix.Identity();
  17986. }
  17987. var viewMatrix = this.getViewMatrix();
  17988. viewMatrix.invertToRef(this._worldMatrix);
  17989. return this._worldMatrix;
  17990. };
  17991. Camera.prototype._getViewMatrix = function () {
  17992. return BABYLON.Matrix.Identity();
  17993. };
  17994. Camera.prototype.getViewMatrix = function (force) {
  17995. if (!force && this._isSynchronizedViewMatrix()) {
  17996. return this._computedViewMatrix;
  17997. }
  17998. this.updateCache();
  17999. this._computedViewMatrix = this._getViewMatrix();
  18000. this._currentRenderId = this.getScene().getRenderId();
  18001. this._refreshFrustumPlanes = true;
  18002. if (!this.parent || !this.parent.getWorldMatrix) {
  18003. this._globalPosition.copyFrom(this.position);
  18004. }
  18005. else {
  18006. if (!this._worldMatrix) {
  18007. this._worldMatrix = BABYLON.Matrix.Identity();
  18008. }
  18009. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18010. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18011. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18012. this._computedViewMatrix.invert();
  18013. this._markSyncedWithParent();
  18014. }
  18015. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18016. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18017. }
  18018. this.onViewMatrixChangedObservable.notifyObservers(this);
  18019. return this._computedViewMatrix;
  18020. };
  18021. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18022. this._doNotComputeProjectionMatrix = true;
  18023. if (projection !== undefined) {
  18024. this._projectionMatrix = projection;
  18025. }
  18026. };
  18027. ;
  18028. Camera.prototype.unfreezeProjectionMatrix = function () {
  18029. this._doNotComputeProjectionMatrix = false;
  18030. };
  18031. ;
  18032. Camera.prototype.getProjectionMatrix = function (force) {
  18033. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18034. return this._projectionMatrix;
  18035. }
  18036. // Cache
  18037. this._cache.mode = this.mode;
  18038. this._cache.minZ = this.minZ;
  18039. this._cache.maxZ = this.maxZ;
  18040. // Matrix
  18041. this._refreshFrustumPlanes = true;
  18042. var engine = this.getEngine();
  18043. var scene = this.getScene();
  18044. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18045. this._cache.fov = this.fov;
  18046. this._cache.fovMode = this.fovMode;
  18047. this._cache.aspectRatio = engine.getAspectRatio(this);
  18048. if (this.minZ <= 0) {
  18049. this.minZ = 0.1;
  18050. }
  18051. if (scene.useRightHandedSystem) {
  18052. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18053. }
  18054. else {
  18055. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18056. }
  18057. }
  18058. else {
  18059. var halfWidth = engine.getRenderWidth() / 2.0;
  18060. var halfHeight = engine.getRenderHeight() / 2.0;
  18061. if (scene.useRightHandedSystem) {
  18062. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18063. }
  18064. else {
  18065. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18066. }
  18067. this._cache.orthoLeft = this.orthoLeft;
  18068. this._cache.orthoRight = this.orthoRight;
  18069. this._cache.orthoBottom = this.orthoBottom;
  18070. this._cache.orthoTop = this.orthoTop;
  18071. this._cache.renderWidth = engine.getRenderWidth();
  18072. this._cache.renderHeight = engine.getRenderHeight();
  18073. }
  18074. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18075. return this._projectionMatrix;
  18076. };
  18077. Camera.prototype.getTranformationMatrix = function () {
  18078. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18079. return this._transformMatrix;
  18080. };
  18081. Camera.prototype.updateFrustumPlanes = function () {
  18082. if (!this._refreshFrustumPlanes) {
  18083. return;
  18084. }
  18085. this.getTranformationMatrix();
  18086. if (!this._frustumPlanes) {
  18087. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18088. }
  18089. else {
  18090. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18091. }
  18092. this._refreshFrustumPlanes = false;
  18093. };
  18094. Camera.prototype.isInFrustum = function (target) {
  18095. this.updateFrustumPlanes();
  18096. return target.isInFrustum(this._frustumPlanes);
  18097. };
  18098. Camera.prototype.isCompletelyInFrustum = function (target) {
  18099. this.updateFrustumPlanes();
  18100. return target.isCompletelyInFrustum(this._frustumPlanes);
  18101. };
  18102. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18103. if (length === void 0) { length = 100; }
  18104. if (!transform) {
  18105. transform = this.getWorldMatrix();
  18106. }
  18107. if (!origin) {
  18108. origin = this.position;
  18109. }
  18110. var forward = new BABYLON.Vector3(0, 0, 1);
  18111. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18112. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18113. return new BABYLON.Ray(origin, direction, length);
  18114. };
  18115. Camera.prototype.dispose = function () {
  18116. // Observables
  18117. this.onViewMatrixChangedObservable.clear();
  18118. this.onProjectionMatrixChangedObservable.clear();
  18119. this.onAfterCheckInputsObservable.clear();
  18120. this.onRestoreStateObservable.clear();
  18121. // Inputs
  18122. if (this.inputs) {
  18123. this.inputs.clear();
  18124. }
  18125. // Animations
  18126. this.getScene().stopAnimation(this);
  18127. // Remove from scene
  18128. this.getScene().removeCamera(this);
  18129. while (this._rigCameras.length > 0) {
  18130. var camera = this._rigCameras.pop();
  18131. if (camera) {
  18132. camera.dispose();
  18133. }
  18134. }
  18135. // Postprocesses
  18136. if (this._rigPostProcess) {
  18137. this._rigPostProcess.dispose(this);
  18138. this._rigPostProcess = null;
  18139. this._postProcesses = [];
  18140. }
  18141. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18142. this._rigPostProcess = null;
  18143. this._postProcesses = [];
  18144. }
  18145. else {
  18146. var i = this._postProcesses.length;
  18147. while (--i >= 0) {
  18148. this._postProcesses[i].dispose(this);
  18149. }
  18150. }
  18151. // Render targets
  18152. var i = this.customRenderTargets.length;
  18153. while (--i >= 0) {
  18154. this.customRenderTargets[i].dispose();
  18155. }
  18156. this.customRenderTargets = [];
  18157. // Active Meshes
  18158. this._activeMeshes.dispose();
  18159. _super.prototype.dispose.call(this);
  18160. };
  18161. Object.defineProperty(Camera.prototype, "leftCamera", {
  18162. // ---- Camera rigs section ----
  18163. get: function () {
  18164. if (this._rigCameras.length < 1) {
  18165. return null;
  18166. }
  18167. return this._rigCameras[0];
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. Object.defineProperty(Camera.prototype, "rightCamera", {
  18173. get: function () {
  18174. if (this._rigCameras.length < 2) {
  18175. return null;
  18176. }
  18177. return this._rigCameras[1];
  18178. },
  18179. enumerable: true,
  18180. configurable: true
  18181. });
  18182. Camera.prototype.getLeftTarget = function () {
  18183. if (this._rigCameras.length < 1) {
  18184. return null;
  18185. }
  18186. return this._rigCameras[0].getTarget();
  18187. };
  18188. Camera.prototype.getRightTarget = function () {
  18189. if (this._rigCameras.length < 2) {
  18190. return null;
  18191. }
  18192. return this._rigCameras[1].getTarget();
  18193. };
  18194. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18195. if (this.cameraRigMode === mode) {
  18196. return;
  18197. }
  18198. while (this._rigCameras.length > 0) {
  18199. var camera = this._rigCameras.pop();
  18200. if (camera) {
  18201. camera.dispose();
  18202. }
  18203. }
  18204. this.cameraRigMode = mode;
  18205. this._cameraRigParams = {};
  18206. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18207. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18208. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18209. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18210. // create the rig cameras, unless none
  18211. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18212. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18213. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18214. if (leftCamera && rightCamera) {
  18215. this._rigCameras.push(leftCamera);
  18216. this._rigCameras.push(rightCamera);
  18217. }
  18218. }
  18219. switch (this.cameraRigMode) {
  18220. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18221. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18222. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18223. break;
  18224. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18225. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18226. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18227. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18228. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18229. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18230. break;
  18231. case Camera.RIG_MODE_VR:
  18232. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18233. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18234. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18235. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18236. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18237. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18238. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18239. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18240. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18241. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18242. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18243. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18244. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18245. if (metrics.compensateDistortion) {
  18246. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18247. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18248. }
  18249. break;
  18250. case Camera.RIG_MODE_WEBVR:
  18251. if (rigParams.vrDisplay) {
  18252. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18253. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18254. //Left eye
  18255. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18256. this._rigCameras[0].setCameraRigParameter("left", true);
  18257. //leaving this for future reference
  18258. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18259. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18260. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18261. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18262. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18263. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18264. this._rigCameras[0].parent = this;
  18265. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18266. //Right eye
  18267. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18268. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18269. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18270. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18271. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18272. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18273. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18274. this._rigCameras[1].parent = this;
  18275. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18276. if (Camera.UseAlternateWebVRRendering) {
  18277. this._rigCameras[1]._skipRendering = true;
  18278. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18279. }
  18280. }
  18281. break;
  18282. }
  18283. this._cascadePostProcessesToRigCams();
  18284. this.update();
  18285. };
  18286. Camera.prototype._getVRProjectionMatrix = function () {
  18287. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18288. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18289. return this._projectionMatrix;
  18290. };
  18291. Camera.prototype._updateCameraRotationMatrix = function () {
  18292. //Here for WebVR
  18293. };
  18294. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18295. //Here for WebVR
  18296. };
  18297. /**
  18298. * This function MUST be overwritten by the different WebVR cameras available.
  18299. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18300. */
  18301. Camera.prototype._getWebVRProjectionMatrix = function () {
  18302. return BABYLON.Matrix.Identity();
  18303. };
  18304. /**
  18305. * This function MUST be overwritten by the different WebVR cameras available.
  18306. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18307. */
  18308. Camera.prototype._getWebVRViewMatrix = function () {
  18309. return BABYLON.Matrix.Identity();
  18310. };
  18311. Camera.prototype.setCameraRigParameter = function (name, value) {
  18312. if (!this._cameraRigParams) {
  18313. this._cameraRigParams = {};
  18314. }
  18315. this._cameraRigParams[name] = value;
  18316. //provisionnally:
  18317. if (name === "interaxialDistance") {
  18318. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18319. }
  18320. };
  18321. /**
  18322. * needs to be overridden by children so sub has required properties to be copied
  18323. */
  18324. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18325. return null;
  18326. };
  18327. /**
  18328. * May need to be overridden by children
  18329. */
  18330. Camera.prototype._updateRigCameras = function () {
  18331. for (var i = 0; i < this._rigCameras.length; i++) {
  18332. this._rigCameras[i].minZ = this.minZ;
  18333. this._rigCameras[i].maxZ = this.maxZ;
  18334. this._rigCameras[i].fov = this.fov;
  18335. }
  18336. // only update viewport when ANAGLYPH
  18337. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18338. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18339. }
  18340. };
  18341. Camera.prototype._setupInputs = function () {
  18342. };
  18343. Camera.prototype.serialize = function () {
  18344. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18345. // Type
  18346. serializationObject.type = this.getClassName();
  18347. // Parent
  18348. if (this.parent) {
  18349. serializationObject.parentId = this.parent.id;
  18350. }
  18351. if (this.inputs) {
  18352. this.inputs.serialize(serializationObject);
  18353. }
  18354. // Animations
  18355. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18356. serializationObject.ranges = this.serializeAnimationRanges();
  18357. return serializationObject;
  18358. };
  18359. Camera.prototype.clone = function (name) {
  18360. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18361. };
  18362. Camera.prototype.getDirection = function (localAxis) {
  18363. var result = BABYLON.Vector3.Zero();
  18364. this.getDirectionToRef(localAxis, result);
  18365. return result;
  18366. };
  18367. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18368. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18369. };
  18370. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18371. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18372. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18373. switch (type) {
  18374. case "ArcRotateCamera":
  18375. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18376. case "DeviceOrientationCamera":
  18377. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18378. case "FollowCamera":
  18379. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18380. case "ArcFollowCamera":
  18381. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18382. case "GamepadCamera":
  18383. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18384. case "TouchCamera":
  18385. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18386. case "VirtualJoysticksCamera":
  18387. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18388. case "WebVRFreeCamera":
  18389. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18390. case "WebVRGamepadCamera":
  18391. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18392. case "VRDeviceOrientationFreeCamera":
  18393. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18394. case "VRDeviceOrientationGamepadCamera":
  18395. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18396. case "AnaglyphArcRotateCamera":
  18397. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18398. case "AnaglyphFreeCamera":
  18399. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18400. case "AnaglyphGamepadCamera":
  18401. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18402. case "AnaglyphUniversalCamera":
  18403. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18404. case "StereoscopicArcRotateCamera":
  18405. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18406. case "StereoscopicFreeCamera":
  18407. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18408. case "StereoscopicGamepadCamera":
  18409. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18410. case "StereoscopicUniversalCamera":
  18411. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18412. case "FreeCamera":// Forcing Universal here
  18413. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18414. default:// Universal Camera is the default value
  18415. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18416. }
  18417. };
  18418. Camera.prototype.computeWorldMatrix = function () {
  18419. return this.getWorldMatrix();
  18420. };
  18421. Camera.Parse = function (parsedCamera, scene) {
  18422. var type = parsedCamera.type;
  18423. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18424. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18425. // Parent
  18426. if (parsedCamera.parentId) {
  18427. camera._waitingParentId = parsedCamera.parentId;
  18428. }
  18429. //If camera has an input manager, let it parse inputs settings
  18430. if (camera.inputs) {
  18431. camera.inputs.parse(parsedCamera);
  18432. camera._setupInputs();
  18433. }
  18434. if (camera.setPosition) {
  18435. camera.position.copyFromFloats(0, 0, 0);
  18436. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18437. }
  18438. // Target
  18439. if (parsedCamera.target) {
  18440. if (camera.setTarget) {
  18441. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18442. }
  18443. }
  18444. // Apply 3d rig, when found
  18445. if (parsedCamera.cameraRigMode) {
  18446. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18447. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18448. }
  18449. // Animations
  18450. if (parsedCamera.animations) {
  18451. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18452. var parsedAnimation = parsedCamera.animations[animationIndex];
  18453. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18454. }
  18455. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18456. }
  18457. if (parsedCamera.autoAnimate) {
  18458. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18459. }
  18460. return camera;
  18461. };
  18462. // Statics
  18463. Camera._PERSPECTIVE_CAMERA = 0;
  18464. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18465. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18466. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18467. Camera._RIG_MODE_NONE = 0;
  18468. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18469. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18470. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18471. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18472. Camera._RIG_MODE_VR = 20;
  18473. Camera._RIG_MODE_WEBVR = 21;
  18474. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18475. Camera.UseAlternateWebVRRendering = false;
  18476. __decorate([
  18477. BABYLON.serializeAsVector3()
  18478. ], Camera.prototype, "position", void 0);
  18479. __decorate([
  18480. BABYLON.serializeAsVector3()
  18481. ], Camera.prototype, "upVector", void 0);
  18482. __decorate([
  18483. BABYLON.serialize()
  18484. ], Camera.prototype, "orthoLeft", void 0);
  18485. __decorate([
  18486. BABYLON.serialize()
  18487. ], Camera.prototype, "orthoRight", void 0);
  18488. __decorate([
  18489. BABYLON.serialize()
  18490. ], Camera.prototype, "orthoBottom", void 0);
  18491. __decorate([
  18492. BABYLON.serialize()
  18493. ], Camera.prototype, "orthoTop", void 0);
  18494. __decorate([
  18495. BABYLON.serialize()
  18496. ], Camera.prototype, "fov", void 0);
  18497. __decorate([
  18498. BABYLON.serialize()
  18499. ], Camera.prototype, "minZ", void 0);
  18500. __decorate([
  18501. BABYLON.serialize()
  18502. ], Camera.prototype, "maxZ", void 0);
  18503. __decorate([
  18504. BABYLON.serialize()
  18505. ], Camera.prototype, "inertia", void 0);
  18506. __decorate([
  18507. BABYLON.serialize()
  18508. ], Camera.prototype, "mode", void 0);
  18509. __decorate([
  18510. BABYLON.serialize()
  18511. ], Camera.prototype, "layerMask", void 0);
  18512. __decorate([
  18513. BABYLON.serialize()
  18514. ], Camera.prototype, "fovMode", void 0);
  18515. __decorate([
  18516. BABYLON.serialize()
  18517. ], Camera.prototype, "cameraRigMode", void 0);
  18518. __decorate([
  18519. BABYLON.serialize()
  18520. ], Camera.prototype, "interaxialDistance", void 0);
  18521. __decorate([
  18522. BABYLON.serialize()
  18523. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18524. return Camera;
  18525. }(BABYLON.Node));
  18526. BABYLON.Camera = Camera;
  18527. })(BABYLON || (BABYLON = {}));
  18528. //# sourceMappingURL=babylon.camera.js.map
  18529. var BABYLON;
  18530. (function (BABYLON) {
  18531. var RenderingManager = /** @class */ (function () {
  18532. function RenderingManager(scene) {
  18533. this._renderingGroups = new Array();
  18534. this._autoClearDepthStencil = {};
  18535. this._customOpaqueSortCompareFn = {};
  18536. this._customAlphaTestSortCompareFn = {};
  18537. this._customTransparentSortCompareFn = {};
  18538. this._renderinGroupInfo = null;
  18539. this._scene = scene;
  18540. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18541. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18542. }
  18543. }
  18544. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18545. if (depth === void 0) { depth = true; }
  18546. if (stencil === void 0) { stencil = true; }
  18547. if (this._depthStencilBufferAlreadyCleaned) {
  18548. return;
  18549. }
  18550. this._scene.getEngine().clear(null, false, depth, stencil);
  18551. this._depthStencilBufferAlreadyCleaned = true;
  18552. };
  18553. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18554. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18555. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18556. var info = null;
  18557. if (observable) {
  18558. if (!this._renderinGroupInfo) {
  18559. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18560. }
  18561. info = this._renderinGroupInfo;
  18562. info.scene = this._scene;
  18563. info.camera = this._scene.activeCamera;
  18564. }
  18565. // Dispatch sprites
  18566. if (renderSprites) {
  18567. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18568. var manager = this._scene.spriteManagers[index];
  18569. this.dispatchSprites(manager);
  18570. }
  18571. }
  18572. // Render
  18573. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18574. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18575. var renderingGroup = this._renderingGroups[index];
  18576. if (!renderingGroup && !observable)
  18577. continue;
  18578. var renderingGroupMask = 0;
  18579. // Fire PRECLEAR stage
  18580. if (observable && info) {
  18581. renderingGroupMask = Math.pow(2, index);
  18582. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18583. info.renderingGroupId = index;
  18584. observable.notifyObservers(info, renderingGroupMask);
  18585. }
  18586. // Clear depth/stencil if needed
  18587. if (RenderingManager.AUTOCLEAR) {
  18588. var autoClear = this._autoClearDepthStencil[index];
  18589. if (autoClear && autoClear.autoClear) {
  18590. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18591. }
  18592. }
  18593. if (observable && info) {
  18594. // Fire PREOPAQUE stage
  18595. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18596. observable.notifyObservers(info, renderingGroupMask);
  18597. // Fire PRETRANSPARENT stage
  18598. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18599. observable.notifyObservers(info, renderingGroupMask);
  18600. }
  18601. if (renderingGroup)
  18602. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18603. // Fire POSTTRANSPARENT stage
  18604. if (observable && info) {
  18605. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18606. observable.notifyObservers(info, renderingGroupMask);
  18607. }
  18608. }
  18609. };
  18610. RenderingManager.prototype.reset = function () {
  18611. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18612. var renderingGroup = this._renderingGroups[index];
  18613. if (renderingGroup) {
  18614. renderingGroup.prepare();
  18615. }
  18616. }
  18617. };
  18618. RenderingManager.prototype.dispose = function () {
  18619. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18620. var renderingGroup = this._renderingGroups[index];
  18621. if (renderingGroup) {
  18622. renderingGroup.dispose();
  18623. }
  18624. }
  18625. this._renderingGroups.length = 0;
  18626. };
  18627. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18628. if (this._renderingGroups[renderingGroupId] === undefined) {
  18629. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18630. }
  18631. };
  18632. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18633. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18634. this._prepareRenderingGroup(renderingGroupId);
  18635. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18636. };
  18637. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18638. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18639. this._prepareRenderingGroup(renderingGroupId);
  18640. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18641. };
  18642. /**
  18643. * @param subMesh The submesh to dispatch
  18644. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18645. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18646. */
  18647. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18648. if (mesh === undefined) {
  18649. mesh = subMesh.getMesh();
  18650. }
  18651. var renderingGroupId = mesh.renderingGroupId || 0;
  18652. this._prepareRenderingGroup(renderingGroupId);
  18653. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18654. };
  18655. /**
  18656. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18657. * This allowed control for front to back rendering or reversly depending of the special needs.
  18658. *
  18659. * @param renderingGroupId The rendering group id corresponding to its index
  18660. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18661. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18662. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18663. */
  18664. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18665. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18666. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18667. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18668. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18669. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18670. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18671. if (this._renderingGroups[renderingGroupId]) {
  18672. var group = this._renderingGroups[renderingGroupId];
  18673. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18674. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18675. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18676. }
  18677. };
  18678. /**
  18679. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18680. *
  18681. * @param renderingGroupId The rendering group id corresponding to its index
  18682. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18683. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18684. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18685. */
  18686. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18687. if (depth === void 0) { depth = true; }
  18688. if (stencil === void 0) { stencil = true; }
  18689. this._autoClearDepthStencil[renderingGroupId] = {
  18690. autoClear: autoClearDepthStencil,
  18691. depth: depth,
  18692. stencil: stencil
  18693. };
  18694. };
  18695. /**
  18696. * The max id used for rendering groups (not included)
  18697. */
  18698. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18699. /**
  18700. * The min id used for rendering groups (included)
  18701. */
  18702. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18703. /**
  18704. * Used to globally prevent autoclearing scenes.
  18705. */
  18706. RenderingManager.AUTOCLEAR = true;
  18707. return RenderingManager;
  18708. }());
  18709. BABYLON.RenderingManager = RenderingManager;
  18710. })(BABYLON || (BABYLON = {}));
  18711. //# sourceMappingURL=babylon.renderingManager.js.map
  18712. var BABYLON;
  18713. (function (BABYLON) {
  18714. var RenderingGroup = /** @class */ (function () {
  18715. /**
  18716. * Creates a new rendering group.
  18717. * @param index The rendering group index
  18718. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18719. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18720. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18721. */
  18722. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18723. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18724. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18725. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18726. this.index = index;
  18727. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18728. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18729. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18730. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18731. this._particleSystems = new BABYLON.SmartArray(256);
  18732. this._spriteManagers = new BABYLON.SmartArray(256);
  18733. this._edgesRenderers = new BABYLON.SmartArray(16);
  18734. this._scene = scene;
  18735. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18736. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18737. this.transparentSortCompareFn = transparentSortCompareFn;
  18738. }
  18739. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18740. /**
  18741. * Set the opaque sort comparison function.
  18742. * If null the sub meshes will be render in the order they were created
  18743. */
  18744. set: function (value) {
  18745. this._opaqueSortCompareFn = value;
  18746. if (value) {
  18747. this._renderOpaque = this.renderOpaqueSorted;
  18748. }
  18749. else {
  18750. this._renderOpaque = RenderingGroup.renderUnsorted;
  18751. }
  18752. },
  18753. enumerable: true,
  18754. configurable: true
  18755. });
  18756. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18757. /**
  18758. * Set the alpha test sort comparison function.
  18759. * If null the sub meshes will be render in the order they were created
  18760. */
  18761. set: function (value) {
  18762. this._alphaTestSortCompareFn = value;
  18763. if (value) {
  18764. this._renderAlphaTest = this.renderAlphaTestSorted;
  18765. }
  18766. else {
  18767. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18768. }
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18774. /**
  18775. * Set the transparent sort comparison function.
  18776. * If null the sub meshes will be render in the order they were created
  18777. */
  18778. set: function (value) {
  18779. if (value) {
  18780. this._transparentSortCompareFn = value;
  18781. }
  18782. else {
  18783. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18784. }
  18785. this._renderTransparent = this.renderTransparentSorted;
  18786. },
  18787. enumerable: true,
  18788. configurable: true
  18789. });
  18790. /**
  18791. * Render all the sub meshes contained in the group.
  18792. * @param customRenderFunction Used to override the default render behaviour of the group.
  18793. * @returns true if rendered some submeshes.
  18794. */
  18795. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18796. if (customRenderFunction) {
  18797. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18798. return;
  18799. }
  18800. var engine = this._scene.getEngine();
  18801. // Depth only
  18802. if (this._depthOnlySubMeshes.length !== 0) {
  18803. engine.setAlphaTesting(true);
  18804. engine.setColorWrite(false);
  18805. this._renderAlphaTest(this._depthOnlySubMeshes);
  18806. engine.setAlphaTesting(false);
  18807. engine.setColorWrite(true);
  18808. }
  18809. // Opaque
  18810. if (this._opaqueSubMeshes.length !== 0) {
  18811. this._renderOpaque(this._opaqueSubMeshes);
  18812. }
  18813. // Alpha test
  18814. if (this._alphaTestSubMeshes.length !== 0) {
  18815. engine.setAlphaTesting(true);
  18816. this._renderAlphaTest(this._alphaTestSubMeshes);
  18817. engine.setAlphaTesting(false);
  18818. }
  18819. var stencilState = engine.getStencilBuffer();
  18820. engine.setStencilBuffer(false);
  18821. // Sprites
  18822. if (renderSprites) {
  18823. this._renderSprites();
  18824. }
  18825. // Particles
  18826. if (renderParticles) {
  18827. this._renderParticles(activeMeshes);
  18828. }
  18829. if (this.onBeforeTransparentRendering) {
  18830. this.onBeforeTransparentRendering();
  18831. }
  18832. // Transparent
  18833. if (this._transparentSubMeshes.length !== 0) {
  18834. this._renderTransparent(this._transparentSubMeshes);
  18835. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18836. }
  18837. // Set back stencil to false in case it changes before the edge renderer.
  18838. engine.setStencilBuffer(false);
  18839. // Edges
  18840. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18841. this._edgesRenderers.data[edgesRendererIndex].render();
  18842. }
  18843. // Restore Stencil state.
  18844. engine.setStencilBuffer(stencilState);
  18845. };
  18846. /**
  18847. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18848. * @param subMeshes The submeshes to render
  18849. */
  18850. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18851. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18852. };
  18853. /**
  18854. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18855. * @param subMeshes The submeshes to render
  18856. */
  18857. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18858. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18859. };
  18860. /**
  18861. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18862. * @param subMeshes The submeshes to render
  18863. */
  18864. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18865. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18866. };
  18867. /**
  18868. * Renders the submeshes in a specified order.
  18869. * @param subMeshes The submeshes to sort before render
  18870. * @param sortCompareFn The comparison function use to sort
  18871. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18872. * @param transparent Specifies to activate blending if true
  18873. */
  18874. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18875. var subIndex = 0;
  18876. var subMesh;
  18877. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18878. for (; subIndex < subMeshes.length; subIndex++) {
  18879. subMesh = subMeshes.data[subIndex];
  18880. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18881. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18882. }
  18883. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18884. if (sortCompareFn) {
  18885. sortedArray.sort(sortCompareFn);
  18886. }
  18887. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18888. subMesh = sortedArray[subIndex];
  18889. if (transparent) {
  18890. var material = subMesh.getMaterial();
  18891. if (material && material.needDepthPrePass) {
  18892. var engine = material.getScene().getEngine();
  18893. engine.setColorWrite(false);
  18894. engine.setAlphaTesting(true);
  18895. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18896. subMesh.render(false);
  18897. engine.setAlphaTesting(false);
  18898. engine.setColorWrite(true);
  18899. }
  18900. }
  18901. subMesh.render(transparent);
  18902. }
  18903. };
  18904. /**
  18905. * Renders the submeshes in the order they were dispatched (no sort applied).
  18906. * @param subMeshes The submeshes to render
  18907. */
  18908. RenderingGroup.renderUnsorted = function (subMeshes) {
  18909. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18910. var submesh = subMeshes.data[subIndex];
  18911. submesh.render(false);
  18912. }
  18913. };
  18914. /**
  18915. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18916. * are rendered back to front if in the same alpha index.
  18917. *
  18918. * @param a The first submesh
  18919. * @param b The second submesh
  18920. * @returns The result of the comparison
  18921. */
  18922. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18923. // Alpha index first
  18924. if (a._alphaIndex > b._alphaIndex) {
  18925. return 1;
  18926. }
  18927. if (a._alphaIndex < b._alphaIndex) {
  18928. return -1;
  18929. }
  18930. // Then distance to camera
  18931. return RenderingGroup.backToFrontSortCompare(a, b);
  18932. };
  18933. /**
  18934. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18935. * are rendered back to front.
  18936. *
  18937. * @param a The first submesh
  18938. * @param b The second submesh
  18939. * @returns The result of the comparison
  18940. */
  18941. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18942. // Then distance to camera
  18943. if (a._distanceToCamera < b._distanceToCamera) {
  18944. return 1;
  18945. }
  18946. if (a._distanceToCamera > b._distanceToCamera) {
  18947. return -1;
  18948. }
  18949. return 0;
  18950. };
  18951. /**
  18952. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18953. * are rendered front to back (prevent overdraw).
  18954. *
  18955. * @param a The first submesh
  18956. * @param b The second submesh
  18957. * @returns The result of the comparison
  18958. */
  18959. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18960. // Then distance to camera
  18961. if (a._distanceToCamera < b._distanceToCamera) {
  18962. return -1;
  18963. }
  18964. if (a._distanceToCamera > b._distanceToCamera) {
  18965. return 1;
  18966. }
  18967. return 0;
  18968. };
  18969. /**
  18970. * Resets the different lists of submeshes to prepare a new frame.
  18971. */
  18972. RenderingGroup.prototype.prepare = function () {
  18973. this._opaqueSubMeshes.reset();
  18974. this._transparentSubMeshes.reset();
  18975. this._alphaTestSubMeshes.reset();
  18976. this._depthOnlySubMeshes.reset();
  18977. this._particleSystems.reset();
  18978. this._spriteManagers.reset();
  18979. this._edgesRenderers.reset();
  18980. };
  18981. RenderingGroup.prototype.dispose = function () {
  18982. this._opaqueSubMeshes.dispose();
  18983. this._transparentSubMeshes.dispose();
  18984. this._alphaTestSubMeshes.dispose();
  18985. this._depthOnlySubMeshes.dispose();
  18986. this._particleSystems.dispose();
  18987. this._spriteManagers.dispose();
  18988. this._edgesRenderers.dispose();
  18989. };
  18990. /**
  18991. * Inserts the submesh in its correct queue depending on its material.
  18992. * @param subMesh The submesh to dispatch
  18993. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18994. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18995. */
  18996. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18997. // Get mesh and materials if not provided
  18998. if (mesh === undefined) {
  18999. mesh = subMesh.getMesh();
  19000. }
  19001. if (material === undefined) {
  19002. material = subMesh.getMaterial();
  19003. }
  19004. if (material === null || material === undefined) {
  19005. return;
  19006. }
  19007. if (material.needAlphaBlendingForMesh(mesh)) {
  19008. this._transparentSubMeshes.push(subMesh);
  19009. }
  19010. else if (material.needAlphaTesting()) {
  19011. if (material.needDepthPrePass) {
  19012. this._depthOnlySubMeshes.push(subMesh);
  19013. }
  19014. this._alphaTestSubMeshes.push(subMesh);
  19015. }
  19016. else {
  19017. if (material.needDepthPrePass) {
  19018. this._depthOnlySubMeshes.push(subMesh);
  19019. }
  19020. this._opaqueSubMeshes.push(subMesh); // Opaque
  19021. }
  19022. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19023. this._edgesRenderers.push(mesh._edgesRenderer);
  19024. }
  19025. };
  19026. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19027. this._spriteManagers.push(spriteManager);
  19028. };
  19029. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19030. this._particleSystems.push(particleSystem);
  19031. };
  19032. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19033. if (this._particleSystems.length === 0) {
  19034. return;
  19035. }
  19036. // Particles
  19037. var activeCamera = this._scene.activeCamera;
  19038. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19039. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19040. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19041. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19042. continue;
  19043. }
  19044. var emitter = particleSystem.emitter;
  19045. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19046. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19047. }
  19048. }
  19049. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19050. };
  19051. RenderingGroup.prototype._renderSprites = function () {
  19052. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19053. return;
  19054. }
  19055. // Sprites
  19056. var activeCamera = this._scene.activeCamera;
  19057. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19058. for (var id = 0; id < this._spriteManagers.length; id++) {
  19059. var spriteManager = this._spriteManagers.data[id];
  19060. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19061. spriteManager.render();
  19062. }
  19063. }
  19064. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19065. };
  19066. return RenderingGroup;
  19067. }());
  19068. BABYLON.RenderingGroup = RenderingGroup;
  19069. })(BABYLON || (BABYLON = {}));
  19070. //# sourceMappingURL=babylon.renderingGroup.js.map
  19071. var BABYLON;
  19072. (function (BABYLON) {
  19073. var ClickInfo = /** @class */ (function () {
  19074. function ClickInfo() {
  19075. this._singleClick = false;
  19076. this._doubleClick = false;
  19077. this._hasSwiped = false;
  19078. this._ignore = false;
  19079. }
  19080. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19081. get: function () {
  19082. return this._singleClick;
  19083. },
  19084. set: function (b) {
  19085. this._singleClick = b;
  19086. },
  19087. enumerable: true,
  19088. configurable: true
  19089. });
  19090. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19091. get: function () {
  19092. return this._doubleClick;
  19093. },
  19094. set: function (b) {
  19095. this._doubleClick = b;
  19096. },
  19097. enumerable: true,
  19098. configurable: true
  19099. });
  19100. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19101. get: function () {
  19102. return this._hasSwiped;
  19103. },
  19104. set: function (b) {
  19105. this._hasSwiped = b;
  19106. },
  19107. enumerable: true,
  19108. configurable: true
  19109. });
  19110. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19111. get: function () {
  19112. return this._ignore;
  19113. },
  19114. set: function (b) {
  19115. this._ignore = b;
  19116. },
  19117. enumerable: true,
  19118. configurable: true
  19119. });
  19120. return ClickInfo;
  19121. }());
  19122. /**
  19123. * This class is used by the onRenderingGroupObservable
  19124. */
  19125. var RenderingGroupInfo = /** @class */ (function () {
  19126. function RenderingGroupInfo() {
  19127. }
  19128. /**
  19129. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19130. * This stage will be fired no matter what
  19131. */
  19132. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19133. /**
  19134. * Called before opaque object are rendered.
  19135. * This stage will be fired only if there's 3D Opaque content to render
  19136. */
  19137. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19138. /**
  19139. * Called after the opaque objects are rendered and before the transparent ones
  19140. * This stage will be fired only if there's 3D transparent content to render
  19141. */
  19142. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19143. /**
  19144. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19145. * This stage will be fired no matter what
  19146. */
  19147. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19148. return RenderingGroupInfo;
  19149. }());
  19150. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19151. /**
  19152. * Represents a scene to be rendered by the engine.
  19153. * @see http://doc.babylonjs.com/page.php?p=21911
  19154. */
  19155. var Scene = /** @class */ (function () {
  19156. /**
  19157. * @constructor
  19158. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19159. */
  19160. function Scene(engine) {
  19161. // Members
  19162. this.autoClear = true;
  19163. this.autoClearDepthAndStencil = true;
  19164. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19165. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19166. this.forceWireframe = false;
  19167. this._forcePointsCloud = false;
  19168. this.forceShowBoundingBoxes = false;
  19169. this.animationsEnabled = true;
  19170. this.useConstantAnimationDeltaTime = false;
  19171. this.constantlyUpdateMeshUnderPointer = false;
  19172. this.hoverCursor = "pointer";
  19173. this.defaultCursor = "";
  19174. /**
  19175. * This is used to call preventDefault() on pointer down
  19176. * in order to block unwanted artifacts like system double clicks
  19177. */
  19178. this.preventDefaultOnPointerDown = true;
  19179. // Metadata
  19180. this.metadata = null;
  19181. /**
  19182. * An event triggered when the scene is disposed.
  19183. * @type {BABYLON.Observable}
  19184. */
  19185. this.onDisposeObservable = new BABYLON.Observable();
  19186. /**
  19187. * An event triggered before rendering the scene (right after animations and physics)
  19188. * @type {BABYLON.Observable}
  19189. */
  19190. this.onBeforeRenderObservable = new BABYLON.Observable();
  19191. /**
  19192. * An event triggered after rendering the scene
  19193. * @type {BABYLON.Observable}
  19194. */
  19195. this.onAfterRenderObservable = new BABYLON.Observable();
  19196. /**
  19197. * An event triggered before animating the scene
  19198. * @type {BABYLON.Observable}
  19199. */
  19200. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19201. /**
  19202. * An event triggered after animations processing
  19203. * @type {BABYLON.Observable}
  19204. */
  19205. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19206. /**
  19207. * An event triggered before draw calls are ready to be sent
  19208. * @type {BABYLON.Observable}
  19209. */
  19210. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19211. /**
  19212. * An event triggered after draw calls have been sent
  19213. * @type {BABYLON.Observable}
  19214. */
  19215. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19216. /**
  19217. * An event triggered when physic simulation is about to be run
  19218. * @type {BABYLON.Observable}
  19219. */
  19220. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19221. /**
  19222. * An event triggered when physic simulation has been done
  19223. * @type {BABYLON.Observable}
  19224. */
  19225. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19226. /**
  19227. * An event triggered when the scene is ready
  19228. * @type {BABYLON.Observable}
  19229. */
  19230. this.onReadyObservable = new BABYLON.Observable();
  19231. /**
  19232. * An event triggered before rendering a camera
  19233. * @type {BABYLON.Observable}
  19234. */
  19235. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19236. /**
  19237. * An event triggered after rendering a camera
  19238. * @type {BABYLON.Observable}
  19239. */
  19240. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19241. /**
  19242. * An event triggered when active meshes evaluation is about to start
  19243. * @type {BABYLON.Observable}
  19244. */
  19245. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19246. /**
  19247. * An event triggered when active meshes evaluation is done
  19248. * @type {BABYLON.Observable}
  19249. */
  19250. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19251. /**
  19252. * An event triggered when particles rendering is about to start
  19253. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19254. * @type {BABYLON.Observable}
  19255. */
  19256. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19257. /**
  19258. * An event triggered when particles rendering is done
  19259. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19260. * @type {BABYLON.Observable}
  19261. */
  19262. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19263. /**
  19264. * An event triggered when sprites rendering is about to start
  19265. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19266. * @type {BABYLON.Observable}
  19267. */
  19268. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19269. /**
  19270. * An event triggered when sprites rendering is done
  19271. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19272. * @type {BABYLON.Observable}
  19273. */
  19274. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19275. /**
  19276. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19277. * @type {BABYLON.Observable}
  19278. */
  19279. this.onDataLoadedObservable = new BABYLON.Observable();
  19280. /**
  19281. * An event triggered when a camera is created
  19282. * @type {BABYLON.Observable}
  19283. */
  19284. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19285. /**
  19286. * An event triggered when a camera is removed
  19287. * @type {BABYLON.Observable}
  19288. */
  19289. this.onCameraRemovedObservable = new BABYLON.Observable();
  19290. /**
  19291. * An event triggered when a light is created
  19292. * @type {BABYLON.Observable}
  19293. */
  19294. this.onNewLightAddedObservable = new BABYLON.Observable();
  19295. /**
  19296. * An event triggered when a light is removed
  19297. * @type {BABYLON.Observable}
  19298. */
  19299. this.onLightRemovedObservable = new BABYLON.Observable();
  19300. /**
  19301. * An event triggered when a geometry is created
  19302. * @type {BABYLON.Observable}
  19303. */
  19304. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19305. /**
  19306. * An event triggered when a geometry is removed
  19307. * @type {BABYLON.Observable}
  19308. */
  19309. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19310. /**
  19311. * An event triggered when a transform node is created
  19312. * @type {BABYLON.Observable}
  19313. */
  19314. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19315. /**
  19316. * An event triggered when a transform node is removed
  19317. * @type {BABYLON.Observable}
  19318. */
  19319. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19320. /**
  19321. * An event triggered when a mesh is created
  19322. * @type {BABYLON.Observable}
  19323. */
  19324. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19325. /**
  19326. * An event triggered when a mesh is removed
  19327. * @type {BABYLON.Observable}
  19328. */
  19329. this.onMeshRemovedObservable = new BABYLON.Observable();
  19330. /**
  19331. * An event triggered when render targets are about to be rendered
  19332. * Can happen multiple times per frame.
  19333. * @type {BABYLON.Observable}
  19334. */
  19335. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19336. /**
  19337. * An event triggered when render targets were rendered.
  19338. * Can happen multiple times per frame.
  19339. * @type {BABYLON.Observable}
  19340. */
  19341. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19342. /**
  19343. * An event triggered before calculating deterministic simulation step
  19344. * @type {BABYLON.Observable}
  19345. */
  19346. this.onBeforeStepObservable = new BABYLON.Observable();
  19347. /**
  19348. * An event triggered after calculating deterministic simulation step
  19349. * @type {BABYLON.Observable}
  19350. */
  19351. this.onAfterStepObservable = new BABYLON.Observable();
  19352. /**
  19353. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19354. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19355. * 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)
  19356. */
  19357. this.onRenderingGroupObservable = new BABYLON.Observable();
  19358. // Animations
  19359. this.animations = [];
  19360. /**
  19361. * 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).
  19362. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19363. */
  19364. this.onPrePointerObservable = new BABYLON.Observable();
  19365. /**
  19366. * Observable event triggered each time an input event is received from the rendering canvas
  19367. */
  19368. this.onPointerObservable = new BABYLON.Observable();
  19369. this._meshPickProceed = false;
  19370. this._currentPickResult = null;
  19371. this._previousPickResult = null;
  19372. this._totalPointersPressed = 0;
  19373. this._doubleClickOccured = false;
  19374. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19375. this.cameraToUseForPointers = null;
  19376. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19377. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19378. this._startingPointerTime = 0;
  19379. this._previousStartingPointerTime = 0;
  19380. // Deterministic lockstep
  19381. this._timeAccumulator = 0;
  19382. this._currentStepId = 0;
  19383. this._currentInternalStep = 0;
  19384. // Keyboard
  19385. /**
  19386. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19387. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19388. */
  19389. this.onPreKeyboardObservable = new BABYLON.Observable();
  19390. /**
  19391. * Observable event triggered each time an keyboard event is received from the hosting window
  19392. */
  19393. this.onKeyboardObservable = new BABYLON.Observable();
  19394. // Coordinate system
  19395. /**
  19396. * use right-handed coordinate system on this scene.
  19397. * @type {boolean}
  19398. */
  19399. this._useRightHandedSystem = false;
  19400. // Fog
  19401. this._fogEnabled = true;
  19402. this._fogMode = Scene.FOGMODE_NONE;
  19403. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19404. this.fogDensity = 0.1;
  19405. this.fogStart = 0;
  19406. this.fogEnd = 1000.0;
  19407. // Lights
  19408. /**
  19409. * is shadow enabled on this scene.
  19410. * @type {boolean}
  19411. */
  19412. this._shadowsEnabled = true;
  19413. /**
  19414. * is light enabled on this scene.
  19415. * @type {boolean}
  19416. */
  19417. this._lightsEnabled = true;
  19418. /**
  19419. * All of the lights added to this scene.
  19420. * @see BABYLON.Light
  19421. * @type {BABYLON.Light[]}
  19422. */
  19423. this.lights = new Array();
  19424. // Cameras
  19425. /** All of the cameras added to this scene. */
  19426. this.cameras = new Array();
  19427. /** All of the active cameras added to this scene. */
  19428. this.activeCameras = new Array();
  19429. // Meshes
  19430. /**
  19431. * All of the tranform nodes added to this scene.
  19432. * @see BABYLON.TransformNode
  19433. * @type {BABYLON.TransformNode[]}
  19434. */
  19435. this.transformNodes = new Array();
  19436. /**
  19437. * All of the (abstract) meshes added to this scene.
  19438. * @see BABYLON.AbstractMesh
  19439. * @type {BABYLON.AbstractMesh[]}
  19440. */
  19441. this.meshes = new Array();
  19442. /**
  19443. * All of the animation groups added to this scene.
  19444. * @see BABYLON.AnimationGroup
  19445. * @type {BABYLON.AnimationGroup[]}
  19446. */
  19447. this.animationGroups = new Array();
  19448. // Geometries
  19449. this._geometries = new Array();
  19450. this.materials = new Array();
  19451. this.multiMaterials = new Array();
  19452. // Textures
  19453. this._texturesEnabled = true;
  19454. this.textures = new Array();
  19455. // Particles
  19456. this.particlesEnabled = true;
  19457. this.particleSystems = new Array();
  19458. // Sprites
  19459. this.spritesEnabled = true;
  19460. this.spriteManagers = new Array();
  19461. // Layers
  19462. this.layers = new Array();
  19463. this.highlightLayers = new Array();
  19464. // Skeletons
  19465. this._skeletonsEnabled = true;
  19466. this.skeletons = new Array();
  19467. // Morph targets
  19468. this.morphTargetManagers = new Array();
  19469. // Lens flares
  19470. this.lensFlaresEnabled = true;
  19471. this.lensFlareSystems = new Array();
  19472. // Collisions
  19473. this.collisionsEnabled = true;
  19474. /** Defines the gravity applied to this scene */
  19475. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19476. // Postprocesses
  19477. this.postProcesses = new Array();
  19478. this.postProcessesEnabled = true;
  19479. // Customs render targets
  19480. this.renderTargetsEnabled = true;
  19481. this.dumpNextRenderTargets = false;
  19482. this.customRenderTargets = new Array();
  19483. // Imported meshes
  19484. this.importedMeshesFiles = new Array();
  19485. // Probes
  19486. this.probesEnabled = true;
  19487. this.reflectionProbes = new Array();
  19488. this._actionManagers = new Array();
  19489. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19490. // Procedural textures
  19491. this.proceduralTexturesEnabled = true;
  19492. this._proceduralTextures = new Array();
  19493. this.soundTracks = new Array();
  19494. this._audioEnabled = true;
  19495. this._headphone = false;
  19496. // Performance counters
  19497. this._totalVertices = new BABYLON.PerfCounter();
  19498. this._activeIndices = new BABYLON.PerfCounter();
  19499. this._activeParticles = new BABYLON.PerfCounter();
  19500. this._activeBones = new BABYLON.PerfCounter();
  19501. this._animationTime = 0;
  19502. this.animationTimeScale = 1;
  19503. this._renderId = 0;
  19504. this._executeWhenReadyTimeoutId = -1;
  19505. this._intermediateRendering = false;
  19506. this._viewUpdateFlag = -1;
  19507. this._projectionUpdateFlag = -1;
  19508. this._alternateViewUpdateFlag = -1;
  19509. this._alternateProjectionUpdateFlag = -1;
  19510. this._toBeDisposed = new BABYLON.SmartArray(256);
  19511. this._activeRequests = new Array();
  19512. this._pendingData = new Array();
  19513. this._isDisposed = false;
  19514. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19515. this._activeMeshes = new BABYLON.SmartArray(256);
  19516. this._processedMaterials = new BABYLON.SmartArray(256);
  19517. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19518. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19519. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19520. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19521. this._activeAnimatables = new Array();
  19522. this._transformMatrix = BABYLON.Matrix.Zero();
  19523. this._useAlternateCameraConfiguration = false;
  19524. this._alternateRendering = false;
  19525. this.requireLightSorting = false;
  19526. this._activeMeshesFrozen = false;
  19527. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19528. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19529. this._engine.scenes.push(this);
  19530. this._uid = null;
  19531. this._renderingManager = new BABYLON.RenderingManager(this);
  19532. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19533. if (BABYLON.OutlineRenderer) {
  19534. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19535. }
  19536. if (BABYLON.Tools.IsWindowObjectExist()) {
  19537. this.attachControl();
  19538. }
  19539. //simplification queue
  19540. if (BABYLON.SimplificationQueue) {
  19541. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19542. }
  19543. //collision coordinator initialization. For now legacy per default.
  19544. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19545. // Uniform Buffer
  19546. this._createUbo();
  19547. // Default Image processing definition.
  19548. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19549. }
  19550. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19551. /** The fog is deactivated */
  19552. get: function () {
  19553. return Scene._FOGMODE_NONE;
  19554. },
  19555. enumerable: true,
  19556. configurable: true
  19557. });
  19558. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19559. /** The fog density is following an exponential function */
  19560. get: function () {
  19561. return Scene._FOGMODE_EXP;
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19567. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19568. get: function () {
  19569. return Scene._FOGMODE_EXP2;
  19570. },
  19571. enumerable: true,
  19572. configurable: true
  19573. });
  19574. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19575. /** The fog density is following a linear function. */
  19576. get: function () {
  19577. return Scene._FOGMODE_LINEAR;
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19583. /**
  19584. * Texture used in all pbr material as the reflection texture.
  19585. * As in the majority of the scene they are the same (exception for multi room and so on),
  19586. * this is easier to reference from here than from all the materials.
  19587. */
  19588. get: function () {
  19589. return this._environmentTexture;
  19590. },
  19591. /**
  19592. * Texture used in all pbr material as the reflection texture.
  19593. * As in the majority of the scene they are the same (exception for multi room and so on),
  19594. * this is easier to set here than in all the materials.
  19595. */
  19596. set: function (value) {
  19597. if (this._environmentTexture === value) {
  19598. return;
  19599. }
  19600. this._environmentTexture = value;
  19601. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19602. },
  19603. enumerable: true,
  19604. configurable: true
  19605. });
  19606. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19607. /**
  19608. * Default image processing configuration used either in the rendering
  19609. * Forward main pass or through the imageProcessingPostProcess if present.
  19610. * As in the majority of the scene they are the same (exception for multi camera),
  19611. * this is easier to reference from here than from all the materials and post process.
  19612. *
  19613. * No setter as we it is a shared configuration, you can set the values instead.
  19614. */
  19615. get: function () {
  19616. return this._imageProcessingConfiguration;
  19617. },
  19618. enumerable: true,
  19619. configurable: true
  19620. });
  19621. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19622. get: function () {
  19623. return this._forcePointsCloud;
  19624. },
  19625. set: function (value) {
  19626. if (this._forcePointsCloud === value) {
  19627. return;
  19628. }
  19629. this._forcePointsCloud = value;
  19630. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. Object.defineProperty(Scene.prototype, "onDispose", {
  19636. /** A function to be executed when this scene is disposed. */
  19637. set: function (callback) {
  19638. if (this._onDisposeObserver) {
  19639. this.onDisposeObservable.remove(this._onDisposeObserver);
  19640. }
  19641. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(Scene.prototype, "beforeRender", {
  19647. /** A function to be executed before rendering this scene */
  19648. set: function (callback) {
  19649. if (this._onBeforeRenderObserver) {
  19650. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19651. }
  19652. if (callback) {
  19653. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19654. }
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Scene.prototype, "afterRender", {
  19660. /** A function to be executed after rendering this scene */
  19661. set: function (callback) {
  19662. if (this._onAfterRenderObserver) {
  19663. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19664. }
  19665. if (callback) {
  19666. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19667. }
  19668. },
  19669. enumerable: true,
  19670. configurable: true
  19671. });
  19672. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19673. set: function (callback) {
  19674. if (this._onBeforeCameraRenderObserver) {
  19675. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19676. }
  19677. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19683. set: function (callback) {
  19684. if (this._onAfterCameraRenderObserver) {
  19685. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19686. }
  19687. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19693. get: function () {
  19694. if (!this._gamepadManager) {
  19695. this._gamepadManager = new BABYLON.GamepadManager(this);
  19696. }
  19697. return this._gamepadManager;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19703. get: function () {
  19704. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19710. get: function () {
  19711. return this._useRightHandedSystem;
  19712. },
  19713. set: function (value) {
  19714. if (this._useRightHandedSystem === value) {
  19715. return;
  19716. }
  19717. this._useRightHandedSystem = value;
  19718. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Scene.prototype.setStepId = function (newStepId) {
  19724. this._currentStepId = newStepId;
  19725. };
  19726. ;
  19727. Scene.prototype.getStepId = function () {
  19728. return this._currentStepId;
  19729. };
  19730. ;
  19731. Scene.prototype.getInternalStep = function () {
  19732. return this._currentInternalStep;
  19733. };
  19734. ;
  19735. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19736. get: function () {
  19737. return this._fogEnabled;
  19738. },
  19739. /**
  19740. * is fog enabled on this scene.
  19741. */
  19742. set: function (value) {
  19743. if (this._fogEnabled === value) {
  19744. return;
  19745. }
  19746. this._fogEnabled = value;
  19747. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(Scene.prototype, "fogMode", {
  19753. get: function () {
  19754. return this._fogMode;
  19755. },
  19756. set: function (value) {
  19757. if (this._fogMode === value) {
  19758. return;
  19759. }
  19760. this._fogMode = value;
  19761. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19767. get: function () {
  19768. return this._shadowsEnabled;
  19769. },
  19770. set: function (value) {
  19771. if (this._shadowsEnabled === value) {
  19772. return;
  19773. }
  19774. this._shadowsEnabled = value;
  19775. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19781. get: function () {
  19782. return this._lightsEnabled;
  19783. },
  19784. set: function (value) {
  19785. if (this._lightsEnabled === value) {
  19786. return;
  19787. }
  19788. this._lightsEnabled = value;
  19789. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19795. /** The default material used on meshes when no material is affected */
  19796. get: function () {
  19797. if (!this._defaultMaterial) {
  19798. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19799. }
  19800. return this._defaultMaterial;
  19801. },
  19802. /** The default material used on meshes when no material is affected */
  19803. set: function (value) {
  19804. this._defaultMaterial = value;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19810. get: function () {
  19811. return this._texturesEnabled;
  19812. },
  19813. set: function (value) {
  19814. if (this._texturesEnabled === value) {
  19815. return;
  19816. }
  19817. this._texturesEnabled = value;
  19818. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19824. get: function () {
  19825. return this._skeletonsEnabled;
  19826. },
  19827. set: function (value) {
  19828. if (this._skeletonsEnabled === value) {
  19829. return;
  19830. }
  19831. this._skeletonsEnabled = value;
  19832. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19838. get: function () {
  19839. if (!this._postProcessRenderPipelineManager) {
  19840. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19841. }
  19842. return this._postProcessRenderPipelineManager;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19848. get: function () {
  19849. if (!this._mainSoundTrack) {
  19850. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19851. }
  19852. return this._mainSoundTrack;
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19858. get: function () {
  19859. return this._alternateRendering;
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19865. get: function () {
  19866. return this._frustumPlanes;
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(Scene.prototype, "debugLayer", {
  19872. // Properties
  19873. get: function () {
  19874. if (!this._debugLayer) {
  19875. this._debugLayer = new BABYLON.DebugLayer(this);
  19876. }
  19877. return this._debugLayer;
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19883. get: function () {
  19884. return this._workerCollisions;
  19885. },
  19886. set: function (enabled) {
  19887. if (!BABYLON.CollisionCoordinatorLegacy) {
  19888. return;
  19889. }
  19890. enabled = (enabled && !!Worker);
  19891. this._workerCollisions = enabled;
  19892. if (this.collisionCoordinator) {
  19893. this.collisionCoordinator.destroy();
  19894. }
  19895. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19896. this.collisionCoordinator.init(this);
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19902. get: function () {
  19903. return this._selectionOctree;
  19904. },
  19905. enumerable: true,
  19906. configurable: true
  19907. });
  19908. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19909. /**
  19910. * The mesh that is currently under the pointer.
  19911. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19912. */
  19913. get: function () {
  19914. return this._pointerOverMesh;
  19915. },
  19916. enumerable: true,
  19917. configurable: true
  19918. });
  19919. Object.defineProperty(Scene.prototype, "pointerX", {
  19920. /**
  19921. * Current on-screen X position of the pointer
  19922. * @return {number} X position of the pointer
  19923. */
  19924. get: function () {
  19925. return this._pointerX;
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Object.defineProperty(Scene.prototype, "pointerY", {
  19931. /**
  19932. * Current on-screen Y position of the pointer
  19933. * @return {number} Y position of the pointer
  19934. */
  19935. get: function () {
  19936. return this._pointerY;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Scene.prototype.getCachedMaterial = function () {
  19942. return this._cachedMaterial;
  19943. };
  19944. Scene.prototype.getCachedEffect = function () {
  19945. return this._cachedEffect;
  19946. };
  19947. Scene.prototype.getCachedVisibility = function () {
  19948. return this._cachedVisibility;
  19949. };
  19950. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19951. if (visibility === void 0) { visibility = 1; }
  19952. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19953. };
  19954. Scene.prototype.getBoundingBoxRenderer = function () {
  19955. if (!this._boundingBoxRenderer) {
  19956. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19957. }
  19958. return this._boundingBoxRenderer;
  19959. };
  19960. Scene.prototype.getOutlineRenderer = function () {
  19961. return this._outlineRenderer;
  19962. };
  19963. Scene.prototype.getEngine = function () {
  19964. return this._engine;
  19965. };
  19966. Scene.prototype.getTotalVertices = function () {
  19967. return this._totalVertices.current;
  19968. };
  19969. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19970. get: function () {
  19971. return this._totalVertices;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Scene.prototype.getActiveIndices = function () {
  19977. return this._activeIndices.current;
  19978. };
  19979. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19980. get: function () {
  19981. return this._activeIndices;
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Scene.prototype.getActiveParticles = function () {
  19987. return this._activeParticles.current;
  19988. };
  19989. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19990. get: function () {
  19991. return this._activeParticles;
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Scene.prototype.getActiveBones = function () {
  19997. return this._activeBones.current;
  19998. };
  19999. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20000. get: function () {
  20001. return this._activeBones;
  20002. },
  20003. enumerable: true,
  20004. configurable: true
  20005. });
  20006. // Stats
  20007. Scene.prototype.getInterFramePerfCounter = function () {
  20008. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20009. return 0;
  20010. };
  20011. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20012. get: function () {
  20013. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20014. return null;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Scene.prototype.getLastFrameDuration = function () {
  20020. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20021. return 0;
  20022. };
  20023. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20024. get: function () {
  20025. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20026. return null;
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20032. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20033. return 0;
  20034. };
  20035. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20036. get: function () {
  20037. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20038. return null;
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. Scene.prototype.getActiveMeshes = function () {
  20044. return this._activeMeshes;
  20045. };
  20046. Scene.prototype.getRenderTargetsDuration = function () {
  20047. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20048. return 0;
  20049. };
  20050. Scene.prototype.getRenderDuration = function () {
  20051. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20052. return 0;
  20053. };
  20054. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20055. get: function () {
  20056. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20057. return null;
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. Scene.prototype.getParticlesDuration = function () {
  20063. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20064. return 0;
  20065. };
  20066. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20067. get: function () {
  20068. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20069. return null;
  20070. },
  20071. enumerable: true,
  20072. configurable: true
  20073. });
  20074. Scene.prototype.getSpritesDuration = function () {
  20075. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20076. return 0;
  20077. };
  20078. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20079. get: function () {
  20080. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20081. return null;
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. Scene.prototype.getAnimationRatio = function () {
  20087. return this._animationRatio;
  20088. };
  20089. Scene.prototype.getRenderId = function () {
  20090. return this._renderId;
  20091. };
  20092. Scene.prototype.incrementRenderId = function () {
  20093. this._renderId++;
  20094. };
  20095. Scene.prototype._updatePointerPosition = function (evt) {
  20096. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20097. if (!canvasRect) {
  20098. return;
  20099. }
  20100. this._pointerX = evt.clientX - canvasRect.left;
  20101. this._pointerY = evt.clientY - canvasRect.top;
  20102. this._unTranslatedPointerX = this._pointerX;
  20103. this._unTranslatedPointerY = this._pointerY;
  20104. };
  20105. Scene.prototype._createUbo = function () {
  20106. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20107. this._sceneUbo.addUniform("viewProjection", 16);
  20108. this._sceneUbo.addUniform("view", 16);
  20109. };
  20110. Scene.prototype._createAlternateUbo = function () {
  20111. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20112. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20113. this._alternateSceneUbo.addUniform("view", 16);
  20114. };
  20115. // Pointers handling
  20116. /**
  20117. * Use this method to simulate a pointer move on a mesh
  20118. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20119. */
  20120. Scene.prototype.simulatePointerMove = function (pickResult) {
  20121. var evt = new PointerEvent("pointermove");
  20122. return this._processPointerMove(pickResult, evt);
  20123. };
  20124. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20125. var canvas = this._engine.getRenderingCanvas();
  20126. if (!canvas) {
  20127. return this;
  20128. }
  20129. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20130. this.setPointerOverSprite(null);
  20131. this.setPointerOverMesh(pickResult.pickedMesh);
  20132. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20133. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20134. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20135. }
  20136. else {
  20137. canvas.style.cursor = this.hoverCursor;
  20138. }
  20139. }
  20140. else {
  20141. canvas.style.cursor = this.defaultCursor;
  20142. }
  20143. }
  20144. else {
  20145. this.setPointerOverMesh(null);
  20146. // Sprites
  20147. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20148. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20149. this.setPointerOverSprite(pickResult.pickedSprite);
  20150. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20151. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20152. }
  20153. else {
  20154. canvas.style.cursor = this.hoverCursor;
  20155. }
  20156. }
  20157. else {
  20158. this.setPointerOverSprite(null);
  20159. // Restore pointer
  20160. canvas.style.cursor = this.defaultCursor;
  20161. }
  20162. }
  20163. if (pickResult) {
  20164. if (this.onPointerMove) {
  20165. this.onPointerMove(evt, pickResult);
  20166. }
  20167. if (this.onPointerObservable.hasObservers()) {
  20168. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20169. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20170. this.onPointerObservable.notifyObservers(pi, type);
  20171. }
  20172. }
  20173. return this;
  20174. };
  20175. /**
  20176. * Use this method to simulate a pointer down on a mesh
  20177. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20178. */
  20179. Scene.prototype.simulatePointerDown = function (pickResult) {
  20180. var evt = new PointerEvent("pointerdown");
  20181. return this._processPointerDown(pickResult, evt);
  20182. };
  20183. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20184. var _this = this;
  20185. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20186. this._pickedDownMesh = pickResult.pickedMesh;
  20187. var actionManager = pickResult.pickedMesh.actionManager;
  20188. if (actionManager) {
  20189. if (actionManager.hasPickTriggers) {
  20190. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20191. switch (evt.button) {
  20192. case 0:
  20193. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20194. break;
  20195. case 1:
  20196. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20197. break;
  20198. case 2:
  20199. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20200. break;
  20201. }
  20202. }
  20203. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20204. window.setTimeout(function () {
  20205. 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);
  20206. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20207. if (_this._totalPointersPressed !== 0 &&
  20208. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20209. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20210. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20211. _this._startingPointerTime = 0;
  20212. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20213. }
  20214. }
  20215. }, Scene.LongPressDelay);
  20216. }
  20217. }
  20218. }
  20219. if (pickResult) {
  20220. if (this.onPointerDown) {
  20221. this.onPointerDown(evt, pickResult);
  20222. }
  20223. if (this.onPointerObservable.hasObservers()) {
  20224. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20225. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20226. this.onPointerObservable.notifyObservers(pi, type);
  20227. }
  20228. }
  20229. return this;
  20230. };
  20231. /**
  20232. * Use this method to simulate a pointer up on a mesh
  20233. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20234. */
  20235. Scene.prototype.simulatePointerUp = function (pickResult) {
  20236. var evt = new PointerEvent("pointerup");
  20237. var clickInfo = new ClickInfo();
  20238. clickInfo.singleClick = true;
  20239. clickInfo.ignore = true;
  20240. return this._processPointerUp(pickResult, evt, clickInfo);
  20241. };
  20242. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20243. if (pickResult && pickResult && pickResult.pickedMesh) {
  20244. this._pickedUpMesh = pickResult.pickedMesh;
  20245. if (this._pickedDownMesh === this._pickedUpMesh) {
  20246. if (this.onPointerPick) {
  20247. this.onPointerPick(evt, pickResult);
  20248. }
  20249. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20250. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20251. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20252. this.onPointerObservable.notifyObservers(pi, type);
  20253. }
  20254. }
  20255. if (pickResult.pickedMesh.actionManager) {
  20256. if (clickInfo.ignore) {
  20257. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20258. }
  20259. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20261. }
  20262. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20263. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20264. }
  20265. }
  20266. }
  20267. if (this._pickedDownMesh &&
  20268. this._pickedDownMesh.actionManager &&
  20269. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20270. this._pickedDownMesh !== this._pickedUpMesh) {
  20271. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20272. }
  20273. if (this.onPointerUp) {
  20274. this.onPointerUp(evt, pickResult);
  20275. }
  20276. if (this.onPointerObservable.hasObservers()) {
  20277. if (!clickInfo.ignore) {
  20278. if (!clickInfo.hasSwiped) {
  20279. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20280. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20281. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20282. this.onPointerObservable.notifyObservers(pi, type);
  20283. }
  20284. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20285. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20286. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20287. this.onPointerObservable.notifyObservers(pi, type);
  20288. }
  20289. }
  20290. }
  20291. else {
  20292. var type = BABYLON.PointerEventTypes.POINTERUP;
  20293. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20294. this.onPointerObservable.notifyObservers(pi, type);
  20295. }
  20296. }
  20297. return this;
  20298. };
  20299. /**
  20300. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20301. * @param attachUp defines if you want to attach events to pointerup
  20302. * @param attachDown defines if you want to attach events to pointerdown
  20303. * @param attachMove defines if you want to attach events to pointermove
  20304. */
  20305. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20306. var _this = this;
  20307. if (attachUp === void 0) { attachUp = true; }
  20308. if (attachDown === void 0) { attachDown = true; }
  20309. if (attachMove === void 0) { attachMove = true; }
  20310. this._initActionManager = function (act, clickInfo) {
  20311. if (!_this._meshPickProceed) {
  20312. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20313. _this._currentPickResult = pickResult;
  20314. if (pickResult) {
  20315. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20316. }
  20317. _this._meshPickProceed = true;
  20318. }
  20319. return act;
  20320. };
  20321. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20322. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20323. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20324. btn !== _this._previousButtonPressed) {
  20325. _this._doubleClickOccured = false;
  20326. clickInfo.singleClick = true;
  20327. clickInfo.ignore = false;
  20328. cb(clickInfo, _this._currentPickResult);
  20329. }
  20330. };
  20331. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20332. var clickInfo = new ClickInfo();
  20333. _this._currentPickResult = null;
  20334. var act = null;
  20335. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20336. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20337. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20338. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20339. act = _this._initActionManager(act, clickInfo);
  20340. if (act)
  20341. checkPicking = act.hasPickTriggers;
  20342. }
  20343. if (checkPicking) {
  20344. var btn = evt.button;
  20345. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20346. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20347. if (!clickInfo.hasSwiped) {
  20348. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20349. if (!checkSingleClickImmediately) {
  20350. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20351. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20352. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20353. act = _this._initActionManager(act, clickInfo);
  20354. if (act)
  20355. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20356. }
  20357. }
  20358. if (checkSingleClickImmediately) {
  20359. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20360. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20361. btn !== _this._previousButtonPressed) {
  20362. clickInfo.singleClick = true;
  20363. cb(clickInfo, _this._currentPickResult);
  20364. }
  20365. }
  20366. else {
  20367. // wait that no double click has been raised during the double click delay
  20368. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20369. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20370. }
  20371. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20372. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20373. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20374. act = _this._initActionManager(act, clickInfo);
  20375. if (act)
  20376. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20377. }
  20378. if (checkDoubleClick) {
  20379. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20380. if (btn === _this._previousButtonPressed &&
  20381. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20382. !_this._doubleClickOccured) {
  20383. // pointer has not moved for 2 clicks, it's a double click
  20384. if (!clickInfo.hasSwiped &&
  20385. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20386. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20387. _this._previousStartingPointerTime = 0;
  20388. _this._doubleClickOccured = true;
  20389. clickInfo.doubleClick = true;
  20390. clickInfo.ignore = false;
  20391. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20392. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20393. }
  20394. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20395. cb(clickInfo, _this._currentPickResult);
  20396. }
  20397. else {
  20398. _this._doubleClickOccured = false;
  20399. _this._previousStartingPointerTime = _this._startingPointerTime;
  20400. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20401. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20402. _this._previousButtonPressed = btn;
  20403. if (Scene.ExclusiveDoubleClickMode) {
  20404. if (_this._previousDelayedSimpleClickTimeout) {
  20405. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20406. }
  20407. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20408. cb(clickInfo, _this._previousPickResult);
  20409. }
  20410. else {
  20411. cb(clickInfo, _this._currentPickResult);
  20412. }
  20413. }
  20414. }
  20415. else {
  20416. _this._doubleClickOccured = false;
  20417. _this._previousStartingPointerTime = _this._startingPointerTime;
  20418. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20419. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20420. _this._previousButtonPressed = btn;
  20421. }
  20422. }
  20423. }
  20424. }
  20425. clickInfo.ignore = true;
  20426. cb(clickInfo, _this._currentPickResult);
  20427. };
  20428. this._spritePredicate = function (sprite) {
  20429. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20430. };
  20431. this._onPointerMove = function (evt) {
  20432. _this._updatePointerPosition(evt);
  20433. // PreObservable support
  20434. if (_this.onPrePointerObservable.hasObservers()) {
  20435. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20436. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20437. _this.onPrePointerObservable.notifyObservers(pi, type);
  20438. if (pi.skipOnPointerObservable) {
  20439. return;
  20440. }
  20441. }
  20442. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20443. return;
  20444. }
  20445. if (!_this.pointerMovePredicate) {
  20446. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20447. }
  20448. // Meshes
  20449. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20450. _this._processPointerMove(pickResult, evt);
  20451. };
  20452. this._onPointerDown = function (evt) {
  20453. _this._totalPointersPressed++;
  20454. _this._pickedDownMesh = null;
  20455. _this._meshPickProceed = false;
  20456. _this._updatePointerPosition(evt);
  20457. if (_this.preventDefaultOnPointerDown && canvas) {
  20458. evt.preventDefault();
  20459. canvas.focus();
  20460. }
  20461. // PreObservable support
  20462. if (_this.onPrePointerObservable.hasObservers()) {
  20463. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20464. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20465. _this.onPrePointerObservable.notifyObservers(pi, type);
  20466. if (pi.skipOnPointerObservable) {
  20467. return;
  20468. }
  20469. }
  20470. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20471. return;
  20472. }
  20473. _this._startingPointerPosition.x = _this._pointerX;
  20474. _this._startingPointerPosition.y = _this._pointerY;
  20475. _this._startingPointerTime = new Date().getTime();
  20476. if (!_this.pointerDownPredicate) {
  20477. _this.pointerDownPredicate = function (mesh) {
  20478. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20479. };
  20480. }
  20481. // Meshes
  20482. _this._pickedDownMesh = null;
  20483. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20484. _this._processPointerDown(pickResult, evt);
  20485. // Sprites
  20486. _this._pickedDownSprite = null;
  20487. if (_this.spriteManagers.length > 0) {
  20488. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20489. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20490. if (pickResult.pickedSprite.actionManager) {
  20491. _this._pickedDownSprite = pickResult.pickedSprite;
  20492. switch (evt.button) {
  20493. case 0:
  20494. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20495. break;
  20496. case 1:
  20497. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20498. break;
  20499. case 2:
  20500. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20501. break;
  20502. }
  20503. if (pickResult.pickedSprite.actionManager) {
  20504. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20505. }
  20506. }
  20507. }
  20508. }
  20509. };
  20510. this._onPointerUp = function (evt) {
  20511. if (_this._totalPointersPressed === 0) {
  20512. return; // So we need to test it the pointer down was pressed before.
  20513. }
  20514. _this._totalPointersPressed--;
  20515. _this._pickedUpMesh = null;
  20516. _this._meshPickProceed = false;
  20517. _this._updatePointerPosition(evt);
  20518. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20519. // PreObservable support
  20520. if (_this.onPrePointerObservable.hasObservers()) {
  20521. if (!clickInfo.ignore) {
  20522. if (!clickInfo.hasSwiped) {
  20523. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20524. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20525. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20526. _this.onPrePointerObservable.notifyObservers(pi, type);
  20527. if (pi.skipOnPointerObservable) {
  20528. return;
  20529. }
  20530. }
  20531. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20532. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20533. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20534. _this.onPrePointerObservable.notifyObservers(pi, type);
  20535. if (pi.skipOnPointerObservable) {
  20536. return;
  20537. }
  20538. }
  20539. }
  20540. }
  20541. else {
  20542. var type = BABYLON.PointerEventTypes.POINTERUP;
  20543. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20544. _this.onPrePointerObservable.notifyObservers(pi, type);
  20545. if (pi.skipOnPointerObservable) {
  20546. return;
  20547. }
  20548. }
  20549. }
  20550. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20551. return;
  20552. }
  20553. if (!_this.pointerUpPredicate) {
  20554. _this.pointerUpPredicate = function (mesh) {
  20555. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20556. };
  20557. }
  20558. // Meshes
  20559. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20560. _this._initActionManager(null, clickInfo);
  20561. }
  20562. if (!pickResult) {
  20563. pickResult = _this._currentPickResult;
  20564. }
  20565. _this._processPointerUp(pickResult, evt, clickInfo);
  20566. // Sprites
  20567. if (_this.spriteManagers.length > 0) {
  20568. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20569. if (spritePickResult) {
  20570. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20571. if (spritePickResult.pickedSprite.actionManager) {
  20572. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20573. if (spritePickResult.pickedSprite.actionManager) {
  20574. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20575. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20576. }
  20577. }
  20578. }
  20579. }
  20580. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20581. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20582. }
  20583. }
  20584. }
  20585. _this._previousPickResult = _this._currentPickResult;
  20586. });
  20587. };
  20588. this._onKeyDown = function (evt) {
  20589. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20590. if (_this.onPreKeyboardObservable.hasObservers()) {
  20591. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20592. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20593. if (pi.skipOnPointerObservable) {
  20594. return;
  20595. }
  20596. }
  20597. if (_this.onKeyboardObservable.hasObservers()) {
  20598. var pi = new BABYLON.KeyboardInfo(type, evt);
  20599. _this.onKeyboardObservable.notifyObservers(pi, type);
  20600. }
  20601. if (_this.actionManager) {
  20602. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20603. }
  20604. };
  20605. this._onKeyUp = function (evt) {
  20606. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20607. if (_this.onPreKeyboardObservable.hasObservers()) {
  20608. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20609. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20610. if (pi.skipOnPointerObservable) {
  20611. return;
  20612. }
  20613. }
  20614. if (_this.onKeyboardObservable.hasObservers()) {
  20615. var pi = new BABYLON.KeyboardInfo(type, evt);
  20616. _this.onKeyboardObservable.notifyObservers(pi, type);
  20617. }
  20618. if (_this.actionManager) {
  20619. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20620. }
  20621. };
  20622. var engine = this.getEngine();
  20623. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20624. if (!canvas) {
  20625. return;
  20626. }
  20627. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20628. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20629. });
  20630. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20631. if (!canvas) {
  20632. return;
  20633. }
  20634. canvas.removeEventListener("keydown", _this._onKeyDown);
  20635. canvas.removeEventListener("keyup", _this._onKeyUp);
  20636. });
  20637. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20638. var canvas = this._engine.getRenderingCanvas();
  20639. if (!canvas) {
  20640. return;
  20641. }
  20642. if (attachMove) {
  20643. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20644. // Wheel
  20645. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20646. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20647. }
  20648. if (attachDown) {
  20649. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20650. }
  20651. if (attachUp) {
  20652. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20653. }
  20654. canvas.tabIndex = 1;
  20655. };
  20656. Scene.prototype.detachControl = function () {
  20657. var engine = this.getEngine();
  20658. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20659. var canvas = engine.getRenderingCanvas();
  20660. if (!canvas) {
  20661. return;
  20662. }
  20663. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20664. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20665. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20666. if (this._onCanvasBlurObserver) {
  20667. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20668. }
  20669. if (this._onCanvasFocusObserver) {
  20670. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20671. }
  20672. // Wheel
  20673. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20674. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20675. // Keyboard
  20676. canvas.removeEventListener("keydown", this._onKeyDown);
  20677. canvas.removeEventListener("keyup", this._onKeyUp);
  20678. // Observables
  20679. this.onKeyboardObservable.clear();
  20680. this.onPreKeyboardObservable.clear();
  20681. this.onPointerObservable.clear();
  20682. this.onPrePointerObservable.clear();
  20683. };
  20684. // Ready
  20685. Scene.prototype.isReady = function () {
  20686. if (this._isDisposed) {
  20687. return false;
  20688. }
  20689. if (this._pendingData.length > 0) {
  20690. return false;
  20691. }
  20692. var index;
  20693. // Geometries
  20694. for (index = 0; index < this._geometries.length; index++) {
  20695. var geometry = this._geometries[index];
  20696. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20697. return false;
  20698. }
  20699. }
  20700. // Meshes
  20701. for (index = 0; index < this.meshes.length; index++) {
  20702. var mesh = this.meshes[index];
  20703. if (!mesh.isEnabled()) {
  20704. continue;
  20705. }
  20706. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20707. continue;
  20708. }
  20709. if (!mesh.isReady()) {
  20710. return false;
  20711. }
  20712. var mat = mesh.material;
  20713. if (mat) {
  20714. if (!mat.isReady(mesh)) {
  20715. return false;
  20716. }
  20717. }
  20718. }
  20719. return true;
  20720. };
  20721. Scene.prototype.resetCachedMaterial = function () {
  20722. this._cachedMaterial = null;
  20723. this._cachedEffect = null;
  20724. this._cachedVisibility = null;
  20725. };
  20726. Scene.prototype.registerBeforeRender = function (func) {
  20727. this.onBeforeRenderObservable.add(func);
  20728. };
  20729. Scene.prototype.unregisterBeforeRender = function (func) {
  20730. this.onBeforeRenderObservable.removeCallback(func);
  20731. };
  20732. Scene.prototype.registerAfterRender = function (func) {
  20733. this.onAfterRenderObservable.add(func);
  20734. };
  20735. Scene.prototype.unregisterAfterRender = function (func) {
  20736. this.onAfterRenderObservable.removeCallback(func);
  20737. };
  20738. Scene.prototype._executeOnceBeforeRender = function (func) {
  20739. var _this = this;
  20740. var execFunc = function () {
  20741. func();
  20742. setTimeout(function () {
  20743. _this.unregisterBeforeRender(execFunc);
  20744. });
  20745. };
  20746. this.registerBeforeRender(execFunc);
  20747. };
  20748. /**
  20749. * The provided function will run before render once and will be disposed afterwards.
  20750. * A timeout delay can be provided so that the function will be executed in N ms.
  20751. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20752. * @param func The function to be executed.
  20753. * @param timeout optional delay in ms
  20754. */
  20755. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20756. var _this = this;
  20757. if (timeout !== undefined) {
  20758. setTimeout(function () {
  20759. _this._executeOnceBeforeRender(func);
  20760. }, timeout);
  20761. }
  20762. else {
  20763. this._executeOnceBeforeRender(func);
  20764. }
  20765. };
  20766. Scene.prototype._addPendingData = function (data) {
  20767. this._pendingData.push(data);
  20768. };
  20769. Scene.prototype._removePendingData = function (data) {
  20770. var wasLoading = this.isLoading;
  20771. var index = this._pendingData.indexOf(data);
  20772. if (index !== -1) {
  20773. this._pendingData.splice(index, 1);
  20774. }
  20775. if (wasLoading && !this.isLoading) {
  20776. this.onDataLoadedObservable.notifyObservers(this);
  20777. }
  20778. };
  20779. Scene.prototype.getWaitingItemsCount = function () {
  20780. return this._pendingData.length;
  20781. };
  20782. Object.defineProperty(Scene.prototype, "isLoading", {
  20783. get: function () {
  20784. return this._pendingData.length > 0;
  20785. },
  20786. enumerable: true,
  20787. configurable: true
  20788. });
  20789. /**
  20790. * Registers a function to be executed when the scene is ready.
  20791. * @param {Function} func - the function to be executed.
  20792. */
  20793. Scene.prototype.executeWhenReady = function (func) {
  20794. var _this = this;
  20795. this.onReadyObservable.add(func);
  20796. if (this._executeWhenReadyTimeoutId !== -1) {
  20797. return;
  20798. }
  20799. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20800. _this._checkIsReady();
  20801. }, 150);
  20802. };
  20803. Scene.prototype._checkIsReady = function () {
  20804. var _this = this;
  20805. if (this.isReady()) {
  20806. this.onReadyObservable.notifyObservers(this);
  20807. this.onReadyObservable.clear();
  20808. this._executeWhenReadyTimeoutId = -1;
  20809. return;
  20810. }
  20811. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20812. _this._checkIsReady();
  20813. }, 150);
  20814. };
  20815. // Animations
  20816. /**
  20817. * Will start the animation sequence of a given target
  20818. * @param target - the target
  20819. * @param {number} from - from which frame should animation start
  20820. * @param {number} to - till which frame should animation run.
  20821. * @param {boolean} [loop] - should the animation loop
  20822. * @param {number} [speedRatio] - the speed in which to run the animation
  20823. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20824. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20825. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20826. * See BABYLON.Animatable
  20827. */
  20828. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20829. if (speedRatio === void 0) { speedRatio = 1.0; }
  20830. if (from > to && speedRatio > 0) {
  20831. speedRatio *= -1;
  20832. }
  20833. this.stopAnimation(target);
  20834. if (!animatable) {
  20835. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20836. }
  20837. // Local animations
  20838. if (target.animations) {
  20839. animatable.appendAnimations(target, target.animations);
  20840. }
  20841. // Children animations
  20842. if (target.getAnimatables) {
  20843. var animatables = target.getAnimatables();
  20844. for (var index = 0; index < animatables.length; index++) {
  20845. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20846. }
  20847. }
  20848. animatable.reset();
  20849. return animatable;
  20850. };
  20851. /**
  20852. * Begin a new animation on a given node
  20853. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20854. * @param {BABYLON.Animation[]} defines the list of animations to start
  20855. * @param {number} from defines the initial value
  20856. * @param {number} to defines the final value
  20857. * @param {boolean} loop defines if you want animation to loop (off by default)
  20858. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20859. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20860. * @returns the list of created animatables
  20861. */
  20862. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20863. if (speedRatio === undefined) {
  20864. speedRatio = 1.0;
  20865. }
  20866. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20867. return animatable;
  20868. };
  20869. /**
  20870. * Begin a new animation on a given node and its hierarchy
  20871. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20872. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  20873. * @param {BABYLON.Animation[]} defines the list of animations to start
  20874. * @param {number} from defines the initial value
  20875. * @param {number} to defines the final value
  20876. * @param {boolean} loop defines if you want animation to loop (off by default)
  20877. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20878. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20879. * @returns the list of animatables created for all nodes
  20880. */
  20881. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20882. var children = target.getDescendants(directDescendantsOnly);
  20883. var result = [];
  20884. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20885. var child = children_1[_i];
  20886. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20887. }
  20888. return result;
  20889. };
  20890. Scene.prototype.getAnimatableByTarget = function (target) {
  20891. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20892. if (this._activeAnimatables[index].target === target) {
  20893. return this._activeAnimatables[index];
  20894. }
  20895. }
  20896. return null;
  20897. };
  20898. Object.defineProperty(Scene.prototype, "animatables", {
  20899. get: function () {
  20900. return this._activeAnimatables;
  20901. },
  20902. enumerable: true,
  20903. configurable: true
  20904. });
  20905. /**
  20906. * Will stop the animation of the given target
  20907. * @param target - the target
  20908. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20909. * @see beginAnimation
  20910. */
  20911. Scene.prototype.stopAnimation = function (target, animationName) {
  20912. var animatable = this.getAnimatableByTarget(target);
  20913. if (animatable) {
  20914. animatable.stop(animationName);
  20915. }
  20916. };
  20917. /**
  20918. * Stops and removes all animations that have been applied to the scene
  20919. */
  20920. Scene.prototype.stopAllAnimations = function () {
  20921. if (this._activeAnimatables) {
  20922. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20923. this._activeAnimatables[i].stop();
  20924. }
  20925. this._activeAnimatables = [];
  20926. }
  20927. };
  20928. Scene.prototype._animate = function () {
  20929. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20930. return;
  20931. }
  20932. // Getting time
  20933. var now = BABYLON.Tools.Now;
  20934. if (!this._animationTimeLast) {
  20935. if (this._pendingData.length > 0) {
  20936. return;
  20937. }
  20938. this._animationTimeLast = now;
  20939. }
  20940. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20941. this._animationTime += deltaTime;
  20942. this._animationTimeLast = now;
  20943. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20944. this._activeAnimatables[index]._animate(this._animationTime);
  20945. }
  20946. };
  20947. // Matrix
  20948. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20949. this._useAlternateCameraConfiguration = active;
  20950. };
  20951. Scene.prototype.getViewMatrix = function () {
  20952. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20953. };
  20954. Scene.prototype.getProjectionMatrix = function () {
  20955. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20956. };
  20957. Scene.prototype.getTransformMatrix = function () {
  20958. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20959. };
  20960. Scene.prototype.setTransformMatrix = function (view, projection) {
  20961. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20962. return;
  20963. }
  20964. this._viewUpdateFlag = view.updateFlag;
  20965. this._projectionUpdateFlag = projection.updateFlag;
  20966. this._viewMatrix = view;
  20967. this._projectionMatrix = projection;
  20968. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20969. // Update frustum
  20970. if (!this._frustumPlanes) {
  20971. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20972. }
  20973. else {
  20974. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20975. }
  20976. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20977. var otherCamera = this.activeCamera._alternateCamera;
  20978. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20979. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20980. }
  20981. if (this._sceneUbo.useUbo) {
  20982. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20983. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20984. this._sceneUbo.update();
  20985. }
  20986. };
  20987. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20988. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20989. return;
  20990. }
  20991. this._alternateViewUpdateFlag = view.updateFlag;
  20992. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20993. this._alternateViewMatrix = view;
  20994. this._alternateProjectionMatrix = projection;
  20995. if (!this._alternateTransformMatrix) {
  20996. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20997. }
  20998. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20999. if (!this._alternateSceneUbo) {
  21000. this._createAlternateUbo();
  21001. }
  21002. if (this._alternateSceneUbo.useUbo) {
  21003. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21004. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21005. this._alternateSceneUbo.update();
  21006. }
  21007. };
  21008. Scene.prototype.getSceneUniformBuffer = function () {
  21009. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21010. };
  21011. // Methods
  21012. Scene.prototype.getUniqueId = function () {
  21013. var result = Scene._uniqueIdCounter;
  21014. Scene._uniqueIdCounter++;
  21015. return result;
  21016. };
  21017. Scene.prototype.addMesh = function (newMesh) {
  21018. this.meshes.push(newMesh);
  21019. //notify the collision coordinator
  21020. if (this.collisionCoordinator) {
  21021. this.collisionCoordinator.onMeshAdded(newMesh);
  21022. }
  21023. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21024. };
  21025. Scene.prototype.removeMesh = function (toRemove) {
  21026. var index = this.meshes.indexOf(toRemove);
  21027. if (index !== -1) {
  21028. // Remove from the scene if mesh found
  21029. this.meshes.splice(index, 1);
  21030. }
  21031. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21032. return index;
  21033. };
  21034. Scene.prototype.addTransformNode = function (newTransformNode) {
  21035. this.transformNodes.push(newTransformNode);
  21036. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21037. };
  21038. Scene.prototype.removeTransformNode = function (toRemove) {
  21039. var index = this.transformNodes.indexOf(toRemove);
  21040. if (index !== -1) {
  21041. // Remove from the scene if found
  21042. this.transformNodes.splice(index, 1);
  21043. }
  21044. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21045. return index;
  21046. };
  21047. Scene.prototype.removeSkeleton = function (toRemove) {
  21048. var index = this.skeletons.indexOf(toRemove);
  21049. if (index !== -1) {
  21050. // Remove from the scene if found
  21051. this.skeletons.splice(index, 1);
  21052. }
  21053. return index;
  21054. };
  21055. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21056. var index = this.morphTargetManagers.indexOf(toRemove);
  21057. if (index !== -1) {
  21058. // Remove from the scene if found
  21059. this.morphTargetManagers.splice(index, 1);
  21060. }
  21061. return index;
  21062. };
  21063. Scene.prototype.removeLight = function (toRemove) {
  21064. var index = this.lights.indexOf(toRemove);
  21065. if (index !== -1) {
  21066. // Remove from meshes
  21067. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21068. var mesh = _a[_i];
  21069. mesh._removeLightSource(toRemove);
  21070. }
  21071. // Remove from the scene if mesh found
  21072. this.lights.splice(index, 1);
  21073. this.sortLightsByPriority();
  21074. }
  21075. this.onLightRemovedObservable.notifyObservers(toRemove);
  21076. return index;
  21077. };
  21078. Scene.prototype.removeCamera = function (toRemove) {
  21079. var index = this.cameras.indexOf(toRemove);
  21080. if (index !== -1) {
  21081. // Remove from the scene if mesh found
  21082. this.cameras.splice(index, 1);
  21083. }
  21084. // Remove from activeCameras
  21085. var index2 = this.activeCameras.indexOf(toRemove);
  21086. if (index2 !== -1) {
  21087. // Remove from the scene if mesh found
  21088. this.activeCameras.splice(index2, 1);
  21089. }
  21090. // Reset the activeCamera
  21091. if (this.activeCamera === toRemove) {
  21092. if (this.cameras.length > 0) {
  21093. this.activeCamera = this.cameras[0];
  21094. }
  21095. else {
  21096. this.activeCamera = null;
  21097. }
  21098. }
  21099. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21100. return index;
  21101. };
  21102. Scene.prototype.addLight = function (newLight) {
  21103. this.lights.push(newLight);
  21104. this.sortLightsByPriority();
  21105. // Add light to all meshes (To support if the light is removed and then readded)
  21106. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21107. var mesh = _a[_i];
  21108. if (mesh._lightSources.indexOf(newLight) === -1) {
  21109. mesh._lightSources.push(newLight);
  21110. mesh._resyncLightSources();
  21111. }
  21112. }
  21113. this.onNewLightAddedObservable.notifyObservers(newLight);
  21114. };
  21115. Scene.prototype.sortLightsByPriority = function () {
  21116. if (this.requireLightSorting) {
  21117. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21118. }
  21119. };
  21120. Scene.prototype.addCamera = function (newCamera) {
  21121. this.cameras.push(newCamera);
  21122. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21123. };
  21124. /**
  21125. * Switch active camera
  21126. * @param {Camera} newCamera - new active camera
  21127. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21128. */
  21129. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21130. if (attachControl === void 0) { attachControl = true; }
  21131. var canvas = this._engine.getRenderingCanvas();
  21132. if (!canvas) {
  21133. return;
  21134. }
  21135. if (this.activeCamera) {
  21136. this.activeCamera.detachControl(canvas);
  21137. }
  21138. this.activeCamera = newCamera;
  21139. if (attachControl) {
  21140. newCamera.attachControl(canvas);
  21141. }
  21142. };
  21143. /**
  21144. * sets the active camera of the scene using its ID
  21145. * @param {string} id - the camera's ID
  21146. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21147. * @see activeCamera
  21148. */
  21149. Scene.prototype.setActiveCameraByID = function (id) {
  21150. var camera = this.getCameraByID(id);
  21151. if (camera) {
  21152. this.activeCamera = camera;
  21153. return camera;
  21154. }
  21155. return null;
  21156. };
  21157. /**
  21158. * sets the active camera of the scene using its name
  21159. * @param {string} name - the camera's name
  21160. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21161. * @see activeCamera
  21162. */
  21163. Scene.prototype.setActiveCameraByName = function (name) {
  21164. var camera = this.getCameraByName(name);
  21165. if (camera) {
  21166. this.activeCamera = camera;
  21167. return camera;
  21168. }
  21169. return null;
  21170. };
  21171. /**
  21172. * get an animation group using its name
  21173. * @param {string} the material's name
  21174. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21175. */
  21176. Scene.prototype.getAnimationGroupByName = function (name) {
  21177. for (var index = 0; index < this.animationGroups.length; index++) {
  21178. if (this.animationGroups[index].name === name) {
  21179. return this.animationGroups[index];
  21180. }
  21181. }
  21182. return null;
  21183. };
  21184. /**
  21185. * get a material using its id
  21186. * @param {string} the material's ID
  21187. * @return {BABYLON.Material|null} the material or null if none found.
  21188. */
  21189. Scene.prototype.getMaterialByID = function (id) {
  21190. for (var index = 0; index < this.materials.length; index++) {
  21191. if (this.materials[index].id === id) {
  21192. return this.materials[index];
  21193. }
  21194. }
  21195. return null;
  21196. };
  21197. /**
  21198. * get a material using its name
  21199. * @param {string} the material's name
  21200. * @return {BABYLON.Material|null} the material or null if none found.
  21201. */
  21202. Scene.prototype.getMaterialByName = function (name) {
  21203. for (var index = 0; index < this.materials.length; index++) {
  21204. if (this.materials[index].name === name) {
  21205. return this.materials[index];
  21206. }
  21207. }
  21208. return null;
  21209. };
  21210. Scene.prototype.getLensFlareSystemByName = function (name) {
  21211. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21212. if (this.lensFlareSystems[index].name === name) {
  21213. return this.lensFlareSystems[index];
  21214. }
  21215. }
  21216. return null;
  21217. };
  21218. Scene.prototype.getLensFlareSystemByID = function (id) {
  21219. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21220. if (this.lensFlareSystems[index].id === id) {
  21221. return this.lensFlareSystems[index];
  21222. }
  21223. }
  21224. return null;
  21225. };
  21226. Scene.prototype.getCameraByID = function (id) {
  21227. for (var index = 0; index < this.cameras.length; index++) {
  21228. if (this.cameras[index].id === id) {
  21229. return this.cameras[index];
  21230. }
  21231. }
  21232. return null;
  21233. };
  21234. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21235. for (var index = 0; index < this.cameras.length; index++) {
  21236. if (this.cameras[index].uniqueId === uniqueId) {
  21237. return this.cameras[index];
  21238. }
  21239. }
  21240. return null;
  21241. };
  21242. /**
  21243. * get a camera using its name
  21244. * @param {string} the camera's name
  21245. * @return {BABYLON.Camera|null} the camera or null if none found.
  21246. */
  21247. Scene.prototype.getCameraByName = function (name) {
  21248. for (var index = 0; index < this.cameras.length; index++) {
  21249. if (this.cameras[index].name === name) {
  21250. return this.cameras[index];
  21251. }
  21252. }
  21253. return null;
  21254. };
  21255. /**
  21256. * get a bone using its id
  21257. * @param {string} the bone's id
  21258. * @return {BABYLON.Bone|null} the bone or null if not found
  21259. */
  21260. Scene.prototype.getBoneByID = function (id) {
  21261. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21262. var skeleton = this.skeletons[skeletonIndex];
  21263. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21264. if (skeleton.bones[boneIndex].id === id) {
  21265. return skeleton.bones[boneIndex];
  21266. }
  21267. }
  21268. }
  21269. return null;
  21270. };
  21271. /**
  21272. * get a bone using its id
  21273. * @param {string} the bone's name
  21274. * @return {BABYLON.Bone|null} the bone or null if not found
  21275. */
  21276. Scene.prototype.getBoneByName = function (name) {
  21277. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21278. var skeleton = this.skeletons[skeletonIndex];
  21279. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21280. if (skeleton.bones[boneIndex].name === name) {
  21281. return skeleton.bones[boneIndex];
  21282. }
  21283. }
  21284. }
  21285. return null;
  21286. };
  21287. /**
  21288. * get a light node using its name
  21289. * @param {string} the light's name
  21290. * @return {BABYLON.Light|null} the light or null if none found.
  21291. */
  21292. Scene.prototype.getLightByName = function (name) {
  21293. for (var index = 0; index < this.lights.length; index++) {
  21294. if (this.lights[index].name === name) {
  21295. return this.lights[index];
  21296. }
  21297. }
  21298. return null;
  21299. };
  21300. /**
  21301. * get a light node using its ID
  21302. * @param {string} the light's id
  21303. * @return {BABYLON.Light|null} the light or null if none found.
  21304. */
  21305. Scene.prototype.getLightByID = function (id) {
  21306. for (var index = 0; index < this.lights.length; index++) {
  21307. if (this.lights[index].id === id) {
  21308. return this.lights[index];
  21309. }
  21310. }
  21311. return null;
  21312. };
  21313. /**
  21314. * get a light node using its scene-generated unique ID
  21315. * @param {number} the light's unique id
  21316. * @return {BABYLON.Light|null} the light or null if none found.
  21317. */
  21318. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21319. for (var index = 0; index < this.lights.length; index++) {
  21320. if (this.lights[index].uniqueId === uniqueId) {
  21321. return this.lights[index];
  21322. }
  21323. }
  21324. return null;
  21325. };
  21326. /**
  21327. * get a particle system by id
  21328. * @param id {number} the particle system id
  21329. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21330. */
  21331. Scene.prototype.getParticleSystemByID = function (id) {
  21332. for (var index = 0; index < this.particleSystems.length; index++) {
  21333. if (this.particleSystems[index].id === id) {
  21334. return this.particleSystems[index];
  21335. }
  21336. }
  21337. return null;
  21338. };
  21339. /**
  21340. * get a geometry using its ID
  21341. * @param {string} the geometry's id
  21342. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21343. */
  21344. Scene.prototype.getGeometryByID = function (id) {
  21345. for (var index = 0; index < this._geometries.length; index++) {
  21346. if (this._geometries[index].id === id) {
  21347. return this._geometries[index];
  21348. }
  21349. }
  21350. return null;
  21351. };
  21352. /**
  21353. * add a new geometry to this scene.
  21354. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21355. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21356. * @return {boolean} was the geometry added or not
  21357. */
  21358. Scene.prototype.pushGeometry = function (geometry, force) {
  21359. if (!force && this.getGeometryByID(geometry.id)) {
  21360. return false;
  21361. }
  21362. this._geometries.push(geometry);
  21363. //notify the collision coordinator
  21364. if (this.collisionCoordinator) {
  21365. this.collisionCoordinator.onGeometryAdded(geometry);
  21366. }
  21367. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21368. return true;
  21369. };
  21370. /**
  21371. * Removes an existing geometry
  21372. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21373. * @return {boolean} was the geometry removed or not
  21374. */
  21375. Scene.prototype.removeGeometry = function (geometry) {
  21376. var index = this._geometries.indexOf(geometry);
  21377. if (index > -1) {
  21378. this._geometries.splice(index, 1);
  21379. //notify the collision coordinator
  21380. if (this.collisionCoordinator) {
  21381. this.collisionCoordinator.onGeometryDeleted(geometry);
  21382. }
  21383. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21384. return true;
  21385. }
  21386. return false;
  21387. };
  21388. Scene.prototype.getGeometries = function () {
  21389. return this._geometries;
  21390. };
  21391. /**
  21392. * Get the first added mesh found of a given ID
  21393. * @param {string} id - the id to search for
  21394. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21395. */
  21396. Scene.prototype.getMeshByID = function (id) {
  21397. for (var index = 0; index < this.meshes.length; index++) {
  21398. if (this.meshes[index].id === id) {
  21399. return this.meshes[index];
  21400. }
  21401. }
  21402. return null;
  21403. };
  21404. Scene.prototype.getMeshesByID = function (id) {
  21405. return this.meshes.filter(function (m) {
  21406. return m.id === id;
  21407. });
  21408. };
  21409. /**
  21410. * Get the first added transform node found of a given ID
  21411. * @param {string} id - the id to search for
  21412. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21413. */
  21414. Scene.prototype.getTransformNodeByID = function (id) {
  21415. for (var index = 0; index < this.transformNodes.length; index++) {
  21416. if (this.transformNodes[index].id === id) {
  21417. return this.transformNodes[index];
  21418. }
  21419. }
  21420. return null;
  21421. };
  21422. Scene.prototype.getTransformNodesByID = function (id) {
  21423. return this.transformNodes.filter(function (m) {
  21424. return m.id === id;
  21425. });
  21426. };
  21427. /**
  21428. * Get a mesh with its auto-generated unique id
  21429. * @param {number} uniqueId - the unique id to search for
  21430. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21431. */
  21432. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21433. for (var index = 0; index < this.meshes.length; index++) {
  21434. if (this.meshes[index].uniqueId === uniqueId) {
  21435. return this.meshes[index];
  21436. }
  21437. }
  21438. return null;
  21439. };
  21440. /**
  21441. * Get a the last added mesh found of a given ID
  21442. * @param {string} id - the id to search for
  21443. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21444. */
  21445. Scene.prototype.getLastMeshByID = function (id) {
  21446. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21447. if (this.meshes[index].id === id) {
  21448. return this.meshes[index];
  21449. }
  21450. }
  21451. return null;
  21452. };
  21453. /**
  21454. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21455. * @param {string} id - the id to search for
  21456. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21457. */
  21458. Scene.prototype.getLastEntryByID = function (id) {
  21459. var index;
  21460. for (index = this.meshes.length - 1; index >= 0; index--) {
  21461. if (this.meshes[index].id === id) {
  21462. return this.meshes[index];
  21463. }
  21464. }
  21465. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21466. if (this.transformNodes[index].id === id) {
  21467. return this.transformNodes[index];
  21468. }
  21469. }
  21470. for (index = this.cameras.length - 1; index >= 0; index--) {
  21471. if (this.cameras[index].id === id) {
  21472. return this.cameras[index];
  21473. }
  21474. }
  21475. for (index = this.lights.length - 1; index >= 0; index--) {
  21476. if (this.lights[index].id === id) {
  21477. return this.lights[index];
  21478. }
  21479. }
  21480. return null;
  21481. };
  21482. Scene.prototype.getNodeByID = function (id) {
  21483. var mesh = this.getMeshByID(id);
  21484. if (mesh) {
  21485. return mesh;
  21486. }
  21487. var light = this.getLightByID(id);
  21488. if (light) {
  21489. return light;
  21490. }
  21491. var camera = this.getCameraByID(id);
  21492. if (camera) {
  21493. return camera;
  21494. }
  21495. var bone = this.getBoneByID(id);
  21496. return bone;
  21497. };
  21498. Scene.prototype.getNodeByName = function (name) {
  21499. var mesh = this.getMeshByName(name);
  21500. if (mesh) {
  21501. return mesh;
  21502. }
  21503. var light = this.getLightByName(name);
  21504. if (light) {
  21505. return light;
  21506. }
  21507. var camera = this.getCameraByName(name);
  21508. if (camera) {
  21509. return camera;
  21510. }
  21511. var bone = this.getBoneByName(name);
  21512. return bone;
  21513. };
  21514. Scene.prototype.getMeshByName = function (name) {
  21515. for (var index = 0; index < this.meshes.length; index++) {
  21516. if (this.meshes[index].name === name) {
  21517. return this.meshes[index];
  21518. }
  21519. }
  21520. return null;
  21521. };
  21522. Scene.prototype.getTransformNodeByName = function (name) {
  21523. for (var index = 0; index < this.transformNodes.length; index++) {
  21524. if (this.transformNodes[index].name === name) {
  21525. return this.transformNodes[index];
  21526. }
  21527. }
  21528. return null;
  21529. };
  21530. Scene.prototype.getSoundByName = function (name) {
  21531. var index;
  21532. if (BABYLON.AudioEngine) {
  21533. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21534. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21535. return this.mainSoundTrack.soundCollection[index];
  21536. }
  21537. }
  21538. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21539. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21540. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21541. return this.soundTracks[sdIndex].soundCollection[index];
  21542. }
  21543. }
  21544. }
  21545. }
  21546. return null;
  21547. };
  21548. Scene.prototype.getLastSkeletonByID = function (id) {
  21549. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21550. if (this.skeletons[index].id === id) {
  21551. return this.skeletons[index];
  21552. }
  21553. }
  21554. return null;
  21555. };
  21556. Scene.prototype.getSkeletonById = function (id) {
  21557. for (var index = 0; index < this.skeletons.length; index++) {
  21558. if (this.skeletons[index].id === id) {
  21559. return this.skeletons[index];
  21560. }
  21561. }
  21562. return null;
  21563. };
  21564. Scene.prototype.getSkeletonByName = function (name) {
  21565. for (var index = 0; index < this.skeletons.length; index++) {
  21566. if (this.skeletons[index].name === name) {
  21567. return this.skeletons[index];
  21568. }
  21569. }
  21570. return null;
  21571. };
  21572. Scene.prototype.getMorphTargetManagerById = function (id) {
  21573. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21574. if (this.morphTargetManagers[index].uniqueId === id) {
  21575. return this.morphTargetManagers[index];
  21576. }
  21577. }
  21578. return null;
  21579. };
  21580. Scene.prototype.isActiveMesh = function (mesh) {
  21581. return (this._activeMeshes.indexOf(mesh) !== -1);
  21582. };
  21583. /**
  21584. * Return a the first highlight layer of the scene with a given name.
  21585. * @param name The name of the highlight layer to look for.
  21586. * @return The highlight layer if found otherwise null.
  21587. */
  21588. Scene.prototype.getHighlightLayerByName = function (name) {
  21589. for (var index = 0; index < this.highlightLayers.length; index++) {
  21590. if (this.highlightLayers[index].name === name) {
  21591. return this.highlightLayers[index];
  21592. }
  21593. }
  21594. return null;
  21595. };
  21596. Object.defineProperty(Scene.prototype, "uid", {
  21597. /**
  21598. * Return a unique id as a string which can serve as an identifier for the scene
  21599. */
  21600. get: function () {
  21601. if (!this._uid) {
  21602. this._uid = BABYLON.Tools.RandomId();
  21603. }
  21604. return this._uid;
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. /**
  21610. * Add an externaly attached data from its key.
  21611. * This method call will fail and return false, if such key already exists.
  21612. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21613. * @param key the unique key that identifies the data
  21614. * @param data the data object to associate to the key for this Engine instance
  21615. * @return true if no such key were already present and the data was added successfully, false otherwise
  21616. */
  21617. Scene.prototype.addExternalData = function (key, data) {
  21618. if (!this._externalData) {
  21619. this._externalData = new BABYLON.StringDictionary();
  21620. }
  21621. return this._externalData.add(key, data);
  21622. };
  21623. /**
  21624. * Get an externaly attached data from its key
  21625. * @param key the unique key that identifies the data
  21626. * @return the associated data, if present (can be null), or undefined if not present
  21627. */
  21628. Scene.prototype.getExternalData = function (key) {
  21629. if (!this._externalData) {
  21630. return null;
  21631. }
  21632. return this._externalData.get(key);
  21633. };
  21634. /**
  21635. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21636. * @param key the unique key that identifies the data
  21637. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21638. * @return the associated data, can be null if the factory returned null.
  21639. */
  21640. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21641. if (!this._externalData) {
  21642. this._externalData = new BABYLON.StringDictionary();
  21643. }
  21644. return this._externalData.getOrAddWithFactory(key, factory);
  21645. };
  21646. /**
  21647. * Remove an externaly attached data from the Engine instance
  21648. * @param key the unique key that identifies the data
  21649. * @return true if the data was successfully removed, false if it doesn't exist
  21650. */
  21651. Scene.prototype.removeExternalData = function (key) {
  21652. return this._externalData.remove(key);
  21653. };
  21654. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21655. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21656. if (mesh.showSubMeshesBoundingBox) {
  21657. var boundingInfo = subMesh.getBoundingInfo();
  21658. if (boundingInfo !== null && boundingInfo !== undefined) {
  21659. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21660. }
  21661. }
  21662. var material = subMesh.getMaterial();
  21663. if (material !== null && material !== undefined) {
  21664. // Render targets
  21665. if (material.getRenderTargetTextures !== undefined) {
  21666. if (this._processedMaterials.indexOf(material) === -1) {
  21667. this._processedMaterials.push(material);
  21668. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21669. }
  21670. }
  21671. // Dispatch
  21672. this._activeIndices.addCount(subMesh.indexCount, false);
  21673. this._renderingManager.dispatch(subMesh, mesh, material);
  21674. }
  21675. }
  21676. };
  21677. Scene.prototype._isInIntermediateRendering = function () {
  21678. return this._intermediateRendering;
  21679. };
  21680. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21681. this._activeMeshCandidateProvider = provider;
  21682. };
  21683. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21684. return this._activeMeshCandidateProvider;
  21685. };
  21686. /**
  21687. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21688. */
  21689. Scene.prototype.freezeActiveMeshes = function () {
  21690. this._evaluateActiveMeshes();
  21691. this._activeMeshesFrozen = true;
  21692. return this;
  21693. };
  21694. /**
  21695. * Use this function to restart evaluating active meshes on every frame
  21696. */
  21697. Scene.prototype.unfreezeActiveMeshes = function () {
  21698. this._activeMeshesFrozen = false;
  21699. return this;
  21700. };
  21701. Scene.prototype._evaluateActiveMeshes = function () {
  21702. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21703. return;
  21704. }
  21705. if (!this.activeCamera) {
  21706. return;
  21707. }
  21708. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21709. this.activeCamera._activeMeshes.reset();
  21710. this._activeMeshes.reset();
  21711. this._renderingManager.reset();
  21712. this._processedMaterials.reset();
  21713. this._activeParticleSystems.reset();
  21714. this._activeSkeletons.reset();
  21715. this._softwareSkinnedMeshes.reset();
  21716. if (this._boundingBoxRenderer) {
  21717. this._boundingBoxRenderer.reset();
  21718. }
  21719. // Meshes
  21720. var meshes;
  21721. var len;
  21722. var checkIsEnabled = true;
  21723. // Determine mesh candidates
  21724. if (this._activeMeshCandidateProvider !== undefined) {
  21725. // Use _activeMeshCandidateProvider
  21726. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21727. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21728. if (meshes !== undefined) {
  21729. len = meshes.length;
  21730. }
  21731. else {
  21732. len = 0;
  21733. }
  21734. }
  21735. else if (this._selectionOctree !== undefined) {
  21736. // Octree
  21737. var selection = this._selectionOctree.select(this._frustumPlanes);
  21738. meshes = selection.data;
  21739. len = selection.length;
  21740. }
  21741. else {
  21742. // Full scene traversal
  21743. len = this.meshes.length;
  21744. meshes = this.meshes;
  21745. }
  21746. // Check each mesh
  21747. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21748. mesh = meshes[meshIndex];
  21749. if (mesh.isBlocked) {
  21750. continue;
  21751. }
  21752. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21753. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21754. continue;
  21755. }
  21756. mesh.computeWorldMatrix();
  21757. // Intersections
  21758. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21759. this._meshesForIntersections.pushNoDuplicate(mesh);
  21760. }
  21761. // Switch to current LOD
  21762. meshLOD = mesh.getLOD(this.activeCamera);
  21763. if (meshLOD === undefined || meshLOD === null) {
  21764. continue;
  21765. }
  21766. mesh._preActivate();
  21767. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21768. this._activeMeshes.push(mesh);
  21769. this.activeCamera._activeMeshes.push(mesh);
  21770. mesh._activate(this._renderId);
  21771. if (meshLOD !== mesh) {
  21772. meshLOD._activate(this._renderId);
  21773. }
  21774. this._activeMesh(mesh, meshLOD);
  21775. }
  21776. }
  21777. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21778. // Particle systems
  21779. if (this.particlesEnabled) {
  21780. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21781. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21782. var particleSystem = this.particleSystems[particleIndex];
  21783. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21784. continue;
  21785. }
  21786. var emitter = particleSystem.emitter;
  21787. if (!emitter.position || emitter.isEnabled()) {
  21788. this._activeParticleSystems.push(particleSystem);
  21789. particleSystem.animate();
  21790. this._renderingManager.dispatchParticles(particleSystem);
  21791. }
  21792. }
  21793. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21794. }
  21795. };
  21796. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21797. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21798. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21799. mesh.skeleton.prepare();
  21800. }
  21801. if (!mesh.computeBonesUsingShaders) {
  21802. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21803. }
  21804. }
  21805. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21806. var boundingInfo = sourceMesh.getBoundingInfo();
  21807. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21808. }
  21809. if (mesh !== undefined && mesh !== null
  21810. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21811. // Submeshes Octrees
  21812. var len;
  21813. var subMeshes;
  21814. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21815. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21816. len = intersections.length;
  21817. subMeshes = intersections.data;
  21818. }
  21819. else {
  21820. subMeshes = mesh.subMeshes;
  21821. len = subMeshes.length;
  21822. }
  21823. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21824. subMesh = subMeshes[subIndex];
  21825. this._evaluateSubMesh(subMesh, mesh);
  21826. }
  21827. }
  21828. };
  21829. Scene.prototype.updateTransformMatrix = function (force) {
  21830. if (!this.activeCamera) {
  21831. return;
  21832. }
  21833. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21834. };
  21835. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21836. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21837. };
  21838. Scene.prototype._renderForCamera = function (camera) {
  21839. if (camera && camera._skipRendering) {
  21840. return;
  21841. }
  21842. var engine = this._engine;
  21843. this.activeCamera = camera;
  21844. if (!this.activeCamera)
  21845. throw new Error("Active camera not set");
  21846. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21847. // Viewport
  21848. engine.setViewport(this.activeCamera.viewport);
  21849. // Camera
  21850. this.resetCachedMaterial();
  21851. this._renderId++;
  21852. this.activeCamera.update();
  21853. this.updateTransformMatrix();
  21854. if (camera._alternateCamera) {
  21855. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21856. this._alternateRendering = true;
  21857. }
  21858. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21859. // Meshes
  21860. this._evaluateActiveMeshes();
  21861. // Software skinning
  21862. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21863. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21864. mesh.applySkeleton(mesh.skeleton);
  21865. }
  21866. // Render targets
  21867. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21868. var needsRestoreFrameBuffer = false;
  21869. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21870. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21871. }
  21872. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21873. this._intermediateRendering = true;
  21874. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21875. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21876. var renderTarget = this._renderTargets.data[renderIndex];
  21877. if (renderTarget._shouldRender()) {
  21878. this._renderId++;
  21879. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21880. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21881. }
  21882. }
  21883. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21884. this._intermediateRendering = false;
  21885. this._renderId++;
  21886. needsRestoreFrameBuffer = true; // Restore back buffer
  21887. }
  21888. // Render HighlightLayer Texture
  21889. var stencilState = this._engine.getStencilBuffer();
  21890. var renderhighlights = false;
  21891. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21892. this._intermediateRendering = true;
  21893. for (var i = 0; i < this.highlightLayers.length; i++) {
  21894. var highlightLayer = this.highlightLayers[i];
  21895. if (highlightLayer.shouldRender() &&
  21896. (!highlightLayer.camera ||
  21897. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21898. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21899. renderhighlights = true;
  21900. var renderTarget = highlightLayer._mainTexture;
  21901. if (renderTarget._shouldRender()) {
  21902. this._renderId++;
  21903. renderTarget.render(false, false);
  21904. needsRestoreFrameBuffer = true;
  21905. }
  21906. }
  21907. }
  21908. this._intermediateRendering = false;
  21909. this._renderId++;
  21910. }
  21911. if (needsRestoreFrameBuffer) {
  21912. engine.restoreDefaultFramebuffer(); // Restore back buffer
  21913. }
  21914. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21915. // Prepare Frame
  21916. this.postProcessManager._prepareFrame();
  21917. // Backgrounds
  21918. var layerIndex;
  21919. var layer;
  21920. if (this.layers.length) {
  21921. engine.setDepthBuffer(false);
  21922. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21923. layer = this.layers[layerIndex];
  21924. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21925. layer.render();
  21926. }
  21927. }
  21928. engine.setDepthBuffer(true);
  21929. }
  21930. // Activate HighlightLayer stencil
  21931. if (renderhighlights) {
  21932. this._engine.setStencilBuffer(true);
  21933. }
  21934. // Render
  21935. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  21936. this._renderingManager.render(null, null, true, true);
  21937. this.onAfterDrawPhaseObservable.notifyObservers(this);
  21938. // Restore HighlightLayer stencil
  21939. if (renderhighlights) {
  21940. this._engine.setStencilBuffer(stencilState);
  21941. }
  21942. // Bounding boxes
  21943. if (this._boundingBoxRenderer) {
  21944. this._boundingBoxRenderer.render();
  21945. }
  21946. // Lens flares
  21947. if (this.lensFlaresEnabled) {
  21948. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21949. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21950. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21951. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21952. lensFlareSystem.render();
  21953. }
  21954. }
  21955. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21956. }
  21957. // Foregrounds
  21958. if (this.layers.length) {
  21959. engine.setDepthBuffer(false);
  21960. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21961. layer = this.layers[layerIndex];
  21962. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21963. layer.render();
  21964. }
  21965. }
  21966. engine.setDepthBuffer(true);
  21967. }
  21968. // Highlight Layer
  21969. if (renderhighlights) {
  21970. engine.setDepthBuffer(false);
  21971. for (var i = 0; i < this.highlightLayers.length; i++) {
  21972. if (this.highlightLayers[i].shouldRender()) {
  21973. this.highlightLayers[i].render();
  21974. }
  21975. }
  21976. engine.setDepthBuffer(true);
  21977. }
  21978. // Finalize frame
  21979. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21980. // Reset some special arrays
  21981. this._renderTargets.reset();
  21982. this._alternateRendering = false;
  21983. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21984. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21985. };
  21986. Scene.prototype._processSubCameras = function (camera) {
  21987. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21988. this._renderForCamera(camera);
  21989. return;
  21990. }
  21991. // Update camera
  21992. if (this.activeCamera) {
  21993. this.activeCamera.update();
  21994. }
  21995. // rig cameras
  21996. for (var index = 0; index < camera._rigCameras.length; index++) {
  21997. this._renderForCamera(camera._rigCameras[index]);
  21998. }
  21999. this.activeCamera = camera;
  22000. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22001. };
  22002. Scene.prototype._checkIntersections = function () {
  22003. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22004. var sourceMesh = this._meshesForIntersections.data[index];
  22005. if (!sourceMesh.actionManager) {
  22006. continue;
  22007. }
  22008. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22009. var action = sourceMesh.actionManager.actions[actionIndex];
  22010. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22011. var parameters = action.getTriggerParameter();
  22012. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22013. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22014. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22015. if (areIntersecting && currentIntersectionInProgress === -1) {
  22016. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22017. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22018. sourceMesh._intersectionsInProgress.push(otherMesh);
  22019. }
  22020. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22021. sourceMesh._intersectionsInProgress.push(otherMesh);
  22022. }
  22023. }
  22024. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22025. //They intersected, and now they don't.
  22026. //is this trigger an exit trigger? execute an event.
  22027. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22028. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22029. }
  22030. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22031. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22032. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22033. }
  22034. }
  22035. }
  22036. }
  22037. }
  22038. };
  22039. Scene.prototype.render = function () {
  22040. if (this.isDisposed) {
  22041. return;
  22042. }
  22043. this._activeParticles.fetchNewFrame();
  22044. this._totalVertices.fetchNewFrame();
  22045. this._activeIndices.fetchNewFrame();
  22046. this._activeBones.fetchNewFrame();
  22047. this._meshesForIntersections.reset();
  22048. this.resetCachedMaterial();
  22049. this.onBeforeAnimationsObservable.notifyObservers(this);
  22050. // Actions
  22051. if (this.actionManager) {
  22052. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22053. }
  22054. //Simplification Queue
  22055. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22056. this.simplificationQueue.executeNext();
  22057. }
  22058. if (this._engine.isDeterministicLockStep()) {
  22059. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22060. var defaultFPS = (60.0 / 1000.0);
  22061. var defaultFrameTime = 1000 / 60; // frame time in MS
  22062. if (this._physicsEngine) {
  22063. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22064. }
  22065. var stepsTaken = 0;
  22066. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22067. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22068. internalSteps = Math.min(internalSteps, maxSubSteps);
  22069. do {
  22070. this.onBeforeStepObservable.notifyObservers(this);
  22071. // Animations
  22072. this._animationRatio = defaultFrameTime * defaultFPS;
  22073. this._animate();
  22074. this.onAfterAnimationsObservable.notifyObservers(this);
  22075. // Physics
  22076. if (this._physicsEngine) {
  22077. this.onBeforePhysicsObservable.notifyObservers(this);
  22078. this._physicsEngine._step(defaultFrameTime / 1000);
  22079. this.onAfterPhysicsObservable.notifyObservers(this);
  22080. }
  22081. this.onAfterStepObservable.notifyObservers(this);
  22082. this._currentStepId++;
  22083. stepsTaken++;
  22084. deltaTime -= defaultFrameTime;
  22085. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22086. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22087. }
  22088. else {
  22089. // Animations
  22090. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22091. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22092. this._animate();
  22093. this.onAfterAnimationsObservable.notifyObservers(this);
  22094. // Physics
  22095. if (this._physicsEngine) {
  22096. this.onBeforePhysicsObservable.notifyObservers(this);
  22097. this._physicsEngine._step(deltaTime / 1000.0);
  22098. this.onAfterPhysicsObservable.notifyObservers(this);
  22099. }
  22100. }
  22101. // update gamepad manager
  22102. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22103. this._gamepadManager._checkGamepadsStatus();
  22104. }
  22105. // Before render
  22106. this.onBeforeRenderObservable.notifyObservers(this);
  22107. // Customs render targets
  22108. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22109. var engine = this.getEngine();
  22110. var currentActiveCamera = this.activeCamera;
  22111. if (this.renderTargetsEnabled) {
  22112. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22113. this._intermediateRendering = true;
  22114. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22115. var renderTarget = this.customRenderTargets[customIndex];
  22116. if (renderTarget._shouldRender()) {
  22117. this._renderId++;
  22118. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22119. if (!this.activeCamera)
  22120. throw new Error("Active camera not set");
  22121. // Viewport
  22122. engine.setViewport(this.activeCamera.viewport);
  22123. // Camera
  22124. this.updateTransformMatrix();
  22125. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22126. }
  22127. }
  22128. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22129. this._intermediateRendering = false;
  22130. this._renderId++;
  22131. }
  22132. // Restore back buffer
  22133. if (this.customRenderTargets.length > 0) {
  22134. engine.restoreDefaultFramebuffer();
  22135. }
  22136. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22137. this.activeCamera = currentActiveCamera;
  22138. // Procedural textures
  22139. if (this.proceduralTexturesEnabled) {
  22140. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22141. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22142. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22143. if (proceduralTexture._shouldRender()) {
  22144. proceduralTexture.render();
  22145. }
  22146. }
  22147. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22148. }
  22149. // Clear
  22150. if (this.autoClearDepthAndStencil || this.autoClear) {
  22151. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22152. }
  22153. // Shadows
  22154. if (this.shadowsEnabled) {
  22155. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22156. var light = this.lights[lightIndex];
  22157. var shadowGenerator = light.getShadowGenerator();
  22158. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22159. var shadowMap = (shadowGenerator.getShadowMap());
  22160. if (this.textures.indexOf(shadowMap) !== -1) {
  22161. this._renderTargets.push(shadowMap);
  22162. }
  22163. }
  22164. }
  22165. }
  22166. // Depth renderer
  22167. if (this._depthRenderer) {
  22168. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22169. }
  22170. // Geometry renderer
  22171. if (this._geometryBufferRenderer) {
  22172. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22173. }
  22174. // RenderPipeline
  22175. if (this._postProcessRenderPipelineManager) {
  22176. this._postProcessRenderPipelineManager.update();
  22177. }
  22178. // Multi-cameras?
  22179. if (this.activeCameras.length > 0) {
  22180. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22181. if (cameraIndex > 0) {
  22182. this._engine.clear(null, false, true, true);
  22183. }
  22184. this._processSubCameras(this.activeCameras[cameraIndex]);
  22185. }
  22186. }
  22187. else {
  22188. if (!this.activeCamera) {
  22189. throw new Error("No camera defined");
  22190. }
  22191. this._processSubCameras(this.activeCamera);
  22192. }
  22193. // Intersection checks
  22194. this._checkIntersections();
  22195. // Update the audio listener attached to the camera
  22196. if (BABYLON.AudioEngine) {
  22197. this._updateAudioParameters();
  22198. }
  22199. // After render
  22200. if (this.afterRender) {
  22201. this.afterRender();
  22202. }
  22203. this.onAfterRenderObservable.notifyObservers(this);
  22204. // Cleaning
  22205. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22206. var data = this._toBeDisposed.data[index];
  22207. if (data) {
  22208. data.dispose();
  22209. }
  22210. this._toBeDisposed[index] = null;
  22211. }
  22212. this._toBeDisposed.reset();
  22213. if (this.dumpNextRenderTargets) {
  22214. this.dumpNextRenderTargets = false;
  22215. }
  22216. this._activeBones.addCount(0, true);
  22217. this._activeIndices.addCount(0, true);
  22218. this._activeParticles.addCount(0, true);
  22219. };
  22220. Scene.prototype._updateAudioParameters = function () {
  22221. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22222. return;
  22223. }
  22224. var listeningCamera;
  22225. var audioEngine = BABYLON.Engine.audioEngine;
  22226. if (this.activeCameras.length > 0) {
  22227. listeningCamera = this.activeCameras[0];
  22228. }
  22229. else {
  22230. listeningCamera = this.activeCamera;
  22231. }
  22232. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22233. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22234. // for VR cameras
  22235. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22236. listeningCamera = listeningCamera.rigCameras[0];
  22237. }
  22238. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22239. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22240. cameraDirection.normalize();
  22241. // To avoid some errors on GearVR
  22242. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22243. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22244. }
  22245. var i;
  22246. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22247. var sound = this.mainSoundTrack.soundCollection[i];
  22248. if (sound.useCustomAttenuation) {
  22249. sound.updateDistanceFromListener();
  22250. }
  22251. }
  22252. for (i = 0; i < this.soundTracks.length; i++) {
  22253. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22254. sound = this.soundTracks[i].soundCollection[j];
  22255. if (sound.useCustomAttenuation) {
  22256. sound.updateDistanceFromListener();
  22257. }
  22258. }
  22259. }
  22260. }
  22261. };
  22262. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22263. // Audio
  22264. get: function () {
  22265. return this._audioEnabled;
  22266. },
  22267. set: function (value) {
  22268. this._audioEnabled = value;
  22269. if (BABYLON.AudioEngine) {
  22270. if (this._audioEnabled) {
  22271. this._enableAudio();
  22272. }
  22273. else {
  22274. this._disableAudio();
  22275. }
  22276. }
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Scene.prototype._disableAudio = function () {
  22282. var i;
  22283. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22284. this.mainSoundTrack.soundCollection[i].pause();
  22285. }
  22286. for (i = 0; i < this.soundTracks.length; i++) {
  22287. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22288. this.soundTracks[i].soundCollection[j].pause();
  22289. }
  22290. }
  22291. };
  22292. Scene.prototype._enableAudio = function () {
  22293. var i;
  22294. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22295. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22296. this.mainSoundTrack.soundCollection[i].play();
  22297. }
  22298. }
  22299. for (i = 0; i < this.soundTracks.length; i++) {
  22300. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22301. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22302. this.soundTracks[i].soundCollection[j].play();
  22303. }
  22304. }
  22305. }
  22306. };
  22307. Object.defineProperty(Scene.prototype, "headphone", {
  22308. get: function () {
  22309. return this._headphone;
  22310. },
  22311. set: function (value) {
  22312. this._headphone = value;
  22313. if (BABYLON.AudioEngine) {
  22314. if (this._headphone) {
  22315. this._switchAudioModeForHeadphones();
  22316. }
  22317. else {
  22318. this._switchAudioModeForNormalSpeakers();
  22319. }
  22320. }
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Scene.prototype._switchAudioModeForHeadphones = function () {
  22326. this.mainSoundTrack.switchPanningModelToHRTF();
  22327. for (var i = 0; i < this.soundTracks.length; i++) {
  22328. this.soundTracks[i].switchPanningModelToHRTF();
  22329. }
  22330. };
  22331. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22332. this.mainSoundTrack.switchPanningModelToEqualPower();
  22333. for (var i = 0; i < this.soundTracks.length; i++) {
  22334. this.soundTracks[i].switchPanningModelToEqualPower();
  22335. }
  22336. };
  22337. Scene.prototype.enableDepthRenderer = function () {
  22338. if (this._depthRenderer) {
  22339. return this._depthRenderer;
  22340. }
  22341. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22342. return this._depthRenderer;
  22343. };
  22344. Scene.prototype.disableDepthRenderer = function () {
  22345. if (!this._depthRenderer) {
  22346. return;
  22347. }
  22348. this._depthRenderer.dispose();
  22349. this._depthRenderer = null;
  22350. };
  22351. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22352. if (ratio === void 0) { ratio = 1; }
  22353. if (this._geometryBufferRenderer) {
  22354. return this._geometryBufferRenderer;
  22355. }
  22356. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22357. if (!this._geometryBufferRenderer.isSupported) {
  22358. this._geometryBufferRenderer = null;
  22359. }
  22360. return this._geometryBufferRenderer;
  22361. };
  22362. Scene.prototype.disableGeometryBufferRenderer = function () {
  22363. if (!this._geometryBufferRenderer) {
  22364. return;
  22365. }
  22366. this._geometryBufferRenderer.dispose();
  22367. this._geometryBufferRenderer = null;
  22368. };
  22369. Scene.prototype.freezeMaterials = function () {
  22370. for (var i = 0; i < this.materials.length; i++) {
  22371. this.materials[i].freeze();
  22372. }
  22373. };
  22374. Scene.prototype.unfreezeMaterials = function () {
  22375. for (var i = 0; i < this.materials.length; i++) {
  22376. this.materials[i].unfreeze();
  22377. }
  22378. };
  22379. Scene.prototype.dispose = function () {
  22380. this.beforeRender = null;
  22381. this.afterRender = null;
  22382. this.skeletons = [];
  22383. this.morphTargetManagers = [];
  22384. this.importedMeshesFiles = new Array();
  22385. this.stopAllAnimations();
  22386. this.resetCachedMaterial();
  22387. if (this._depthRenderer) {
  22388. this._depthRenderer.dispose();
  22389. }
  22390. if (this._gamepadManager) {
  22391. this._gamepadManager.dispose();
  22392. this._gamepadManager = null;
  22393. }
  22394. // Smart arrays
  22395. if (this.activeCamera) {
  22396. this.activeCamera._activeMeshes.dispose();
  22397. this.activeCamera = null;
  22398. }
  22399. this._activeMeshes.dispose();
  22400. this._renderingManager.dispose();
  22401. this._processedMaterials.dispose();
  22402. this._activeParticleSystems.dispose();
  22403. this._activeSkeletons.dispose();
  22404. this._softwareSkinnedMeshes.dispose();
  22405. this._renderTargets.dispose();
  22406. if (this._boundingBoxRenderer) {
  22407. this._boundingBoxRenderer.dispose();
  22408. }
  22409. this._meshesForIntersections.dispose();
  22410. this._toBeDisposed.dispose();
  22411. // Abort active requests
  22412. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22413. var request = _a[_i];
  22414. request.abort();
  22415. }
  22416. // Debug layer
  22417. if (this._debugLayer) {
  22418. this._debugLayer.hide();
  22419. }
  22420. // Events
  22421. this.onDisposeObservable.notifyObservers(this);
  22422. this.onDisposeObservable.clear();
  22423. this.onBeforeRenderObservable.clear();
  22424. this.onAfterRenderObservable.clear();
  22425. this.OnBeforeRenderTargetsRenderObservable.clear();
  22426. this.OnAfterRenderTargetsRenderObservable.clear();
  22427. this.onAfterStepObservable.clear();
  22428. this.onBeforeStepObservable.clear();
  22429. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22430. this.onAfterActiveMeshesEvaluationObservable.clear();
  22431. this.onBeforeParticlesRenderingObservable.clear();
  22432. this.onAfterParticlesRenderingObservable.clear();
  22433. this.onBeforeSpritesRenderingObservable.clear();
  22434. this.onAfterSpritesRenderingObservable.clear();
  22435. this.onBeforeDrawPhaseObservable.clear();
  22436. this.onAfterDrawPhaseObservable.clear();
  22437. this.onBeforePhysicsObservable.clear();
  22438. this.onAfterPhysicsObservable.clear();
  22439. this.onBeforeAnimationsObservable.clear();
  22440. this.onAfterAnimationsObservable.clear();
  22441. this.onDataLoadedObservable.clear();
  22442. this.detachControl();
  22443. // Release sounds & sounds tracks
  22444. if (BABYLON.AudioEngine) {
  22445. this.disposeSounds();
  22446. }
  22447. // VR Helper
  22448. if (this.VRHelper) {
  22449. this.VRHelper.dispose();
  22450. }
  22451. // Detach cameras
  22452. var canvas = this._engine.getRenderingCanvas();
  22453. if (canvas) {
  22454. var index;
  22455. for (index = 0; index < this.cameras.length; index++) {
  22456. this.cameras[index].detachControl(canvas);
  22457. }
  22458. }
  22459. // Release animation groups
  22460. while (this.animationGroups.length) {
  22461. this.animationGroups[0].dispose();
  22462. }
  22463. // Release lights
  22464. while (this.lights.length) {
  22465. this.lights[0].dispose();
  22466. }
  22467. // Release meshes
  22468. while (this.meshes.length) {
  22469. this.meshes[0].dispose(true);
  22470. }
  22471. while (this.transformNodes.length) {
  22472. this.removeTransformNode(this.transformNodes[0]);
  22473. }
  22474. // Release cameras
  22475. while (this.cameras.length) {
  22476. this.cameras[0].dispose();
  22477. }
  22478. // Release materials
  22479. if (this.defaultMaterial) {
  22480. this.defaultMaterial.dispose();
  22481. }
  22482. while (this.multiMaterials.length) {
  22483. this.multiMaterials[0].dispose();
  22484. }
  22485. while (this.materials.length) {
  22486. this.materials[0].dispose();
  22487. }
  22488. // Release particles
  22489. while (this.particleSystems.length) {
  22490. this.particleSystems[0].dispose();
  22491. }
  22492. // Release sprites
  22493. while (this.spriteManagers.length) {
  22494. this.spriteManagers[0].dispose();
  22495. }
  22496. // Release postProcesses
  22497. while (this.postProcesses.length) {
  22498. this.postProcesses[0].dispose();
  22499. }
  22500. // Release layers
  22501. while (this.layers.length) {
  22502. this.layers[0].dispose();
  22503. }
  22504. while (this.highlightLayers.length) {
  22505. this.highlightLayers[0].dispose();
  22506. }
  22507. // Release textures
  22508. while (this.textures.length) {
  22509. this.textures[0].dispose();
  22510. }
  22511. // Release UBO
  22512. this._sceneUbo.dispose();
  22513. if (this._alternateSceneUbo) {
  22514. this._alternateSceneUbo.dispose();
  22515. }
  22516. // Post-processes
  22517. this.postProcessManager.dispose();
  22518. if (this._postProcessRenderPipelineManager) {
  22519. this._postProcessRenderPipelineManager.dispose();
  22520. }
  22521. // Physics
  22522. if (this._physicsEngine) {
  22523. this.disablePhysicsEngine();
  22524. }
  22525. // Remove from engine
  22526. index = this._engine.scenes.indexOf(this);
  22527. if (index > -1) {
  22528. this._engine.scenes.splice(index, 1);
  22529. }
  22530. this._engine.wipeCaches(true);
  22531. this._isDisposed = true;
  22532. };
  22533. Object.defineProperty(Scene.prototype, "isDisposed", {
  22534. get: function () {
  22535. return this._isDisposed;
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. // Release sounds & sounds tracks
  22541. Scene.prototype.disposeSounds = function () {
  22542. if (!this._mainSoundTrack) {
  22543. return;
  22544. }
  22545. this.mainSoundTrack.dispose();
  22546. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22547. this.soundTracks[scIndex].dispose();
  22548. }
  22549. };
  22550. // Octrees
  22551. Scene.prototype.getWorldExtends = function () {
  22552. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22553. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22554. for (var index = 0; index < this.meshes.length; index++) {
  22555. var mesh = this.meshes[index];
  22556. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22557. continue;
  22558. }
  22559. mesh.computeWorldMatrix(true);
  22560. var boundingInfo = mesh.getBoundingInfo();
  22561. var minBox = boundingInfo.boundingBox.minimumWorld;
  22562. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22563. BABYLON.Tools.CheckExtends(minBox, min, max);
  22564. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22565. }
  22566. return {
  22567. min: min,
  22568. max: max
  22569. };
  22570. };
  22571. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22572. if (maxCapacity === void 0) { maxCapacity = 64; }
  22573. if (maxDepth === void 0) { maxDepth = 2; }
  22574. if (!this._selectionOctree) {
  22575. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22576. }
  22577. var worldExtends = this.getWorldExtends();
  22578. // Update octree
  22579. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22580. return this._selectionOctree;
  22581. };
  22582. // Picking
  22583. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22584. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22585. var result = BABYLON.Ray.Zero();
  22586. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22587. return result;
  22588. };
  22589. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22590. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22591. var engine = this._engine;
  22592. if (!camera) {
  22593. if (!this.activeCamera)
  22594. throw new Error("Active camera not set");
  22595. camera = this.activeCamera;
  22596. }
  22597. var cameraViewport = camera.viewport;
  22598. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22599. // Moving coordinates to local viewport world
  22600. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22601. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22602. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22603. return this;
  22604. };
  22605. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22606. var result = BABYLON.Ray.Zero();
  22607. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22608. return result;
  22609. };
  22610. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22611. if (!BABYLON.PickingInfo) {
  22612. return this;
  22613. }
  22614. var engine = this._engine;
  22615. if (!camera) {
  22616. if (!this.activeCamera)
  22617. throw new Error("Active camera not set");
  22618. camera = this.activeCamera;
  22619. }
  22620. var cameraViewport = camera.viewport;
  22621. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22622. var identity = BABYLON.Matrix.Identity();
  22623. // Moving coordinates to local viewport world
  22624. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22625. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22626. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22627. return this;
  22628. };
  22629. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22630. if (!BABYLON.PickingInfo) {
  22631. return null;
  22632. }
  22633. var pickingInfo = null;
  22634. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22635. var mesh = this.meshes[meshIndex];
  22636. if (predicate) {
  22637. if (!predicate(mesh)) {
  22638. continue;
  22639. }
  22640. }
  22641. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22642. continue;
  22643. }
  22644. var world = mesh.getWorldMatrix();
  22645. var ray = rayFunction(world);
  22646. var result = mesh.intersects(ray, fastCheck);
  22647. if (!result || !result.hit)
  22648. continue;
  22649. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22650. continue;
  22651. pickingInfo = result;
  22652. if (fastCheck) {
  22653. break;
  22654. }
  22655. }
  22656. return pickingInfo || new BABYLON.PickingInfo();
  22657. };
  22658. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22659. if (!BABYLON.PickingInfo) {
  22660. return null;
  22661. }
  22662. var pickingInfos = new Array();
  22663. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22664. var mesh = this.meshes[meshIndex];
  22665. if (predicate) {
  22666. if (!predicate(mesh)) {
  22667. continue;
  22668. }
  22669. }
  22670. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22671. continue;
  22672. }
  22673. var world = mesh.getWorldMatrix();
  22674. var ray = rayFunction(world);
  22675. var result = mesh.intersects(ray, false);
  22676. if (!result || !result.hit)
  22677. continue;
  22678. pickingInfos.push(result);
  22679. }
  22680. return pickingInfos;
  22681. };
  22682. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22683. if (!BABYLON.PickingInfo) {
  22684. return null;
  22685. }
  22686. var pickingInfo = null;
  22687. if (!camera) {
  22688. if (!this.activeCamera) {
  22689. return null;
  22690. }
  22691. camera = this.activeCamera;
  22692. }
  22693. if (this.spriteManagers.length > 0) {
  22694. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22695. var spriteManager = this.spriteManagers[spriteIndex];
  22696. if (!spriteManager.isPickable) {
  22697. continue;
  22698. }
  22699. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22700. if (!result || !result.hit)
  22701. continue;
  22702. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22703. continue;
  22704. pickingInfo = result;
  22705. if (fastCheck) {
  22706. break;
  22707. }
  22708. }
  22709. }
  22710. return pickingInfo || new BABYLON.PickingInfo();
  22711. };
  22712. /** Launch a ray to try to pick a mesh in the scene
  22713. * @param x position on screen
  22714. * @param y position on screen
  22715. * @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
  22716. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22717. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22718. */
  22719. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22720. var _this = this;
  22721. if (!BABYLON.PickingInfo) {
  22722. return null;
  22723. }
  22724. return this._internalPick(function (world) {
  22725. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22726. return _this._tempPickingRay;
  22727. }, predicate, fastCheck);
  22728. };
  22729. /** Launch a ray to try to pick a sprite in the scene
  22730. * @param x position on screen
  22731. * @param y position on screen
  22732. * @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
  22733. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22734. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22735. */
  22736. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22737. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22738. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22739. };
  22740. /** Use the given ray to pick a mesh in the scene
  22741. * @param ray The ray to use to pick meshes
  22742. * @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
  22743. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22744. */
  22745. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22746. var _this = this;
  22747. return this._internalPick(function (world) {
  22748. if (!_this._pickWithRayInverseMatrix) {
  22749. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22750. }
  22751. world.invertToRef(_this._pickWithRayInverseMatrix);
  22752. if (!_this._cachedRayForTransform) {
  22753. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22754. }
  22755. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22756. return _this._cachedRayForTransform;
  22757. }, predicate, fastCheck);
  22758. };
  22759. /**
  22760. * Launch a ray to try to pick a mesh in the scene
  22761. * @param x X position on screen
  22762. * @param y Y position on screen
  22763. * @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
  22764. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22765. */
  22766. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22767. var _this = this;
  22768. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22769. };
  22770. /**
  22771. * Launch a ray to try to pick a mesh in the scene
  22772. * @param ray Ray to use
  22773. * @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
  22774. */
  22775. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22776. var _this = this;
  22777. return this._internalMultiPick(function (world) {
  22778. if (!_this._pickWithRayInverseMatrix) {
  22779. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22780. }
  22781. world.invertToRef(_this._pickWithRayInverseMatrix);
  22782. if (!_this._cachedRayForTransform) {
  22783. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22784. }
  22785. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22786. return _this._cachedRayForTransform;
  22787. }, predicate);
  22788. };
  22789. Scene.prototype.setPointerOverMesh = function (mesh) {
  22790. if (this._pointerOverMesh === mesh) {
  22791. return;
  22792. }
  22793. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22794. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22795. }
  22796. this._pointerOverMesh = mesh;
  22797. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22798. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22799. }
  22800. };
  22801. Scene.prototype.getPointerOverMesh = function () {
  22802. return this._pointerOverMesh;
  22803. };
  22804. Scene.prototype.setPointerOverSprite = function (sprite) {
  22805. if (this._pointerOverSprite === sprite) {
  22806. return;
  22807. }
  22808. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22809. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22810. }
  22811. this._pointerOverSprite = sprite;
  22812. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22813. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22814. }
  22815. };
  22816. Scene.prototype.getPointerOverSprite = function () {
  22817. return this._pointerOverSprite;
  22818. };
  22819. // Physics
  22820. Scene.prototype.getPhysicsEngine = function () {
  22821. return this._physicsEngine;
  22822. };
  22823. /**
  22824. * Enables physics to the current scene
  22825. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22826. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22827. * @return {boolean} was the physics engine initialized
  22828. */
  22829. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22830. if (gravity === void 0) { gravity = null; }
  22831. if (this._physicsEngine) {
  22832. return true;
  22833. }
  22834. try {
  22835. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22836. return true;
  22837. }
  22838. catch (e) {
  22839. BABYLON.Tools.Error(e.message);
  22840. return false;
  22841. }
  22842. };
  22843. Scene.prototype.disablePhysicsEngine = function () {
  22844. if (!this._physicsEngine) {
  22845. return;
  22846. }
  22847. this._physicsEngine.dispose();
  22848. this._physicsEngine = null;
  22849. };
  22850. Scene.prototype.isPhysicsEnabled = function () {
  22851. return this._physicsEngine !== undefined;
  22852. };
  22853. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22854. var mesh = compound.parts[0].mesh;
  22855. if (mesh.physicsImpostor) {
  22856. mesh.physicsImpostor.dispose();
  22857. mesh.physicsImpostor = null;
  22858. }
  22859. };
  22860. // Misc.
  22861. Scene.prototype._rebuildGeometries = function () {
  22862. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22863. var geometry = _a[_i];
  22864. geometry._rebuild();
  22865. }
  22866. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22867. var mesh = _c[_b];
  22868. mesh._rebuild();
  22869. }
  22870. if (this.postProcessManager) {
  22871. this.postProcessManager._rebuild();
  22872. }
  22873. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22874. var layer = _e[_d];
  22875. layer._rebuild();
  22876. }
  22877. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22878. var highlightLayer = _g[_f];
  22879. highlightLayer._rebuild();
  22880. }
  22881. if (this._boundingBoxRenderer) {
  22882. this._boundingBoxRenderer._rebuild();
  22883. }
  22884. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22885. var system = _j[_h];
  22886. system.rebuild();
  22887. }
  22888. if (this._postProcessRenderPipelineManager) {
  22889. this._postProcessRenderPipelineManager._rebuild();
  22890. }
  22891. };
  22892. Scene.prototype._rebuildTextures = function () {
  22893. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22894. var texture = _a[_i];
  22895. texture._rebuild();
  22896. }
  22897. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22898. };
  22899. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  22900. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22901. if (replace === void 0) { replace = false; }
  22902. if (attachCameraControls === void 0) { attachCameraControls = false; }
  22903. // Dispose existing camera or light in replace mode.
  22904. if (replace) {
  22905. if (this.activeCamera) {
  22906. this.activeCamera.dispose();
  22907. this.activeCamera = null;
  22908. }
  22909. if (this.lights) {
  22910. for (var i = 0; i < this.lights.length; i++) {
  22911. this.lights[i].dispose();
  22912. }
  22913. }
  22914. }
  22915. // Light
  22916. if (this.lights.length === 0) {
  22917. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22918. }
  22919. // Camera
  22920. if (!this.activeCamera) {
  22921. var worldExtends = this.getWorldExtends();
  22922. var worldSize = worldExtends.max.subtract(worldExtends.min);
  22923. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  22924. var camera;
  22925. var radius = worldSize.length() * 1.5;
  22926. if (createArcRotateCamera) {
  22927. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  22928. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  22929. arcRotateCamera.wheelPrecision = 100 / radius;
  22930. camera = arcRotateCamera;
  22931. }
  22932. else {
  22933. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  22934. freeCamera.setTarget(worldCenter);
  22935. camera = freeCamera;
  22936. }
  22937. camera.minZ = radius * 0.01;
  22938. camera.maxZ = radius * 1000;
  22939. camera.speed = radius * 0.2;
  22940. this.activeCamera = camera;
  22941. var canvas = this.getEngine().getRenderingCanvas();
  22942. if (attachCameraControls && canvas) {
  22943. camera.attachControl(canvas);
  22944. }
  22945. }
  22946. };
  22947. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  22948. if (pbr === void 0) { pbr = false; }
  22949. if (scale === void 0) { scale = 1000; }
  22950. if (blur === void 0) { blur = 0; }
  22951. if (environmentTexture) {
  22952. this.environmentTexture = environmentTexture;
  22953. }
  22954. if (!this.environmentTexture) {
  22955. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  22956. return null;
  22957. }
  22958. // Skybox
  22959. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  22960. if (pbr) {
  22961. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22962. hdrSkyboxMaterial.backFaceCulling = false;
  22963. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22964. if (hdrSkyboxMaterial.reflectionTexture) {
  22965. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22966. }
  22967. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22968. hdrSkyboxMaterial.disableLighting = true;
  22969. hdrSkyboxMaterial.twoSidedLighting = true;
  22970. hdrSkybox.infiniteDistance = true;
  22971. hdrSkybox.material = hdrSkyboxMaterial;
  22972. }
  22973. else {
  22974. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22975. skyboxMaterial.backFaceCulling = false;
  22976. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22977. if (skyboxMaterial.reflectionTexture) {
  22978. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22979. }
  22980. skyboxMaterial.disableLighting = true;
  22981. hdrSkybox.infiniteDistance = true;
  22982. hdrSkybox.material = skyboxMaterial;
  22983. }
  22984. return hdrSkybox;
  22985. };
  22986. Scene.prototype.createDefaultEnvironment = function (options) {
  22987. if (BABYLON.EnvironmentHelper) {
  22988. return new BABYLON.EnvironmentHelper(options, this);
  22989. }
  22990. return null;
  22991. };
  22992. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22993. if (webVROptions === void 0) { webVROptions = {}; }
  22994. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22995. };
  22996. // Tags
  22997. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22998. if (tagsQuery === undefined) {
  22999. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23000. return list;
  23001. }
  23002. var listByTags = [];
  23003. forEach = forEach || (function (item) { return; });
  23004. for (var i in list) {
  23005. var item = list[i];
  23006. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23007. listByTags.push(item);
  23008. forEach(item);
  23009. }
  23010. }
  23011. return listByTags;
  23012. };
  23013. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23014. return this._getByTags(this.meshes, tagsQuery, forEach);
  23015. };
  23016. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23017. return this._getByTags(this.cameras, tagsQuery, forEach);
  23018. };
  23019. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23020. return this._getByTags(this.lights, tagsQuery, forEach);
  23021. };
  23022. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23023. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23024. };
  23025. /**
  23026. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23027. * This allowed control for front to back rendering or reversly depending of the special needs.
  23028. *
  23029. * @param renderingGroupId The rendering group id corresponding to its index
  23030. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23031. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23032. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23033. */
  23034. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23035. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23036. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23037. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23038. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23039. };
  23040. /**
  23041. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23042. *
  23043. * @param renderingGroupId The rendering group id corresponding to its index
  23044. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23045. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23046. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23047. */
  23048. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23049. if (depth === void 0) { depth = true; }
  23050. if (stencil === void 0) { stencil = true; }
  23051. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23052. };
  23053. /**
  23054. * Will flag all materials as dirty to trigger new shader compilation
  23055. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23056. */
  23057. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23058. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23059. var material = _a[_i];
  23060. if (predicate && !predicate(material)) {
  23061. continue;
  23062. }
  23063. material.markAsDirty(flag);
  23064. }
  23065. };
  23066. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23067. var _this = this;
  23068. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23069. this._activeRequests.push(request);
  23070. request.onCompleteObservable.add(function (request) {
  23071. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23072. });
  23073. return request;
  23074. };
  23075. // Statics
  23076. Scene._FOGMODE_NONE = 0;
  23077. Scene._FOGMODE_EXP = 1;
  23078. Scene._FOGMODE_EXP2 = 2;
  23079. Scene._FOGMODE_LINEAR = 3;
  23080. Scene._uniqueIdCounter = 0;
  23081. Scene.MinDeltaTime = 1.0;
  23082. Scene.MaxDeltaTime = 1000.0;
  23083. /** The distance in pixel that you have to move to prevent some events */
  23084. Scene.DragMovementThreshold = 10; // in pixels
  23085. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23086. Scene.LongPressDelay = 500; // in milliseconds
  23087. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23088. Scene.DoubleClickDelay = 300; // in milliseconds
  23089. /** If you need to check double click without raising a single click at first click, enable this flag */
  23090. Scene.ExclusiveDoubleClickMode = false;
  23091. return Scene;
  23092. }());
  23093. BABYLON.Scene = Scene;
  23094. })(BABYLON || (BABYLON = {}));
  23095. //# sourceMappingURL=babylon.scene.js.map
  23096. var BABYLON;
  23097. (function (BABYLON) {
  23098. var Buffer = /** @class */ (function () {
  23099. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23100. if (instanced === void 0) { instanced = false; }
  23101. if (engine instanceof BABYLON.Mesh) {
  23102. this._engine = engine.getScene().getEngine();
  23103. }
  23104. else {
  23105. this._engine = engine;
  23106. }
  23107. this._updatable = updatable;
  23108. this._data = data;
  23109. this._strideSize = stride;
  23110. if (!postponeInternalCreation) {
  23111. this.create();
  23112. }
  23113. this._instanced = instanced;
  23114. this._instanceDivisor = instanced ? 1 : 0;
  23115. }
  23116. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23117. // a lot of these parameters are ignored as they are overriden by the buffer
  23118. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23119. };
  23120. // Properties
  23121. Buffer.prototype.isUpdatable = function () {
  23122. return this._updatable;
  23123. };
  23124. Buffer.prototype.getData = function () {
  23125. return this._data;
  23126. };
  23127. Buffer.prototype.getBuffer = function () {
  23128. return this._buffer;
  23129. };
  23130. Buffer.prototype.getStrideSize = function () {
  23131. return this._strideSize;
  23132. };
  23133. Buffer.prototype.getIsInstanced = function () {
  23134. return this._instanced;
  23135. };
  23136. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23137. get: function () {
  23138. return this._instanceDivisor;
  23139. },
  23140. set: function (value) {
  23141. this._instanceDivisor = value;
  23142. if (value == 0) {
  23143. this._instanced = false;
  23144. }
  23145. else {
  23146. this._instanced = true;
  23147. }
  23148. },
  23149. enumerable: true,
  23150. configurable: true
  23151. });
  23152. // Methods
  23153. Buffer.prototype.create = function (data) {
  23154. if (data === void 0) { data = null; }
  23155. if (!data && this._buffer) {
  23156. return; // nothing to do
  23157. }
  23158. data = data || this._data;
  23159. if (!data) {
  23160. return;
  23161. }
  23162. if (!this._buffer) {
  23163. if (this._updatable) {
  23164. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23165. this._data = data;
  23166. }
  23167. else {
  23168. this._buffer = this._engine.createVertexBuffer(data);
  23169. }
  23170. }
  23171. else if (this._updatable) {
  23172. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23173. this._data = data;
  23174. }
  23175. };
  23176. Buffer.prototype._rebuild = function () {
  23177. this._buffer = null;
  23178. this.create(this._data);
  23179. };
  23180. Buffer.prototype.update = function (data) {
  23181. this.create(data);
  23182. };
  23183. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23184. if (!this._buffer) {
  23185. return;
  23186. }
  23187. if (this._updatable) {
  23188. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23189. this._data = null;
  23190. }
  23191. };
  23192. Buffer.prototype.dispose = function () {
  23193. if (!this._buffer) {
  23194. return;
  23195. }
  23196. if (this._engine._releaseBuffer(this._buffer)) {
  23197. this._buffer = null;
  23198. }
  23199. };
  23200. return Buffer;
  23201. }());
  23202. BABYLON.Buffer = Buffer;
  23203. })(BABYLON || (BABYLON = {}));
  23204. //# sourceMappingURL=babylon.buffer.js.map
  23205. var BABYLON;
  23206. (function (BABYLON) {
  23207. var VertexBuffer = /** @class */ (function () {
  23208. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23209. if (!stride) {
  23210. // Deduce stride from kind
  23211. switch (kind) {
  23212. case VertexBuffer.PositionKind:
  23213. stride = 3;
  23214. break;
  23215. case VertexBuffer.NormalKind:
  23216. stride = 3;
  23217. break;
  23218. case VertexBuffer.UVKind:
  23219. case VertexBuffer.UV2Kind:
  23220. case VertexBuffer.UV3Kind:
  23221. case VertexBuffer.UV4Kind:
  23222. case VertexBuffer.UV5Kind:
  23223. case VertexBuffer.UV6Kind:
  23224. stride = 2;
  23225. break;
  23226. case VertexBuffer.TangentKind:
  23227. case VertexBuffer.ColorKind:
  23228. stride = 4;
  23229. break;
  23230. case VertexBuffer.MatricesIndicesKind:
  23231. case VertexBuffer.MatricesIndicesExtraKind:
  23232. stride = 4;
  23233. break;
  23234. case VertexBuffer.MatricesWeightsKind:
  23235. case VertexBuffer.MatricesWeightsExtraKind:
  23236. default:
  23237. stride = 4;
  23238. break;
  23239. }
  23240. }
  23241. if (data instanceof BABYLON.Buffer) {
  23242. if (!stride) {
  23243. stride = data.getStrideSize();
  23244. }
  23245. this._buffer = data;
  23246. this._ownsBuffer = false;
  23247. }
  23248. else {
  23249. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23250. this._ownsBuffer = true;
  23251. }
  23252. this._stride = stride;
  23253. this._offset = offset ? offset : 0;
  23254. this._size = size ? size : stride;
  23255. this._kind = kind;
  23256. }
  23257. VertexBuffer.prototype._rebuild = function () {
  23258. if (!this._buffer) {
  23259. return;
  23260. }
  23261. this._buffer._rebuild();
  23262. };
  23263. /**
  23264. * Returns the kind of the VertexBuffer (string).
  23265. */
  23266. VertexBuffer.prototype.getKind = function () {
  23267. return this._kind;
  23268. };
  23269. // Properties
  23270. /**
  23271. * Boolean : is the VertexBuffer updatable ?
  23272. */
  23273. VertexBuffer.prototype.isUpdatable = function () {
  23274. return this._buffer.isUpdatable();
  23275. };
  23276. /**
  23277. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23278. */
  23279. VertexBuffer.prototype.getData = function () {
  23280. return this._buffer.getData();
  23281. };
  23282. /**
  23283. * Returns the WebGLBuffer associated to the VertexBuffer.
  23284. */
  23285. VertexBuffer.prototype.getBuffer = function () {
  23286. return this._buffer.getBuffer();
  23287. };
  23288. /**
  23289. * Returns the stride of the VertexBuffer (integer).
  23290. */
  23291. VertexBuffer.prototype.getStrideSize = function () {
  23292. return this._stride;
  23293. };
  23294. /**
  23295. * Returns the offset (integer).
  23296. */
  23297. VertexBuffer.prototype.getOffset = function () {
  23298. return this._offset;
  23299. };
  23300. /**
  23301. * Returns the VertexBuffer total size (integer).
  23302. */
  23303. VertexBuffer.prototype.getSize = function () {
  23304. return this._size;
  23305. };
  23306. /**
  23307. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23308. */
  23309. VertexBuffer.prototype.getIsInstanced = function () {
  23310. return this._buffer.getIsInstanced();
  23311. };
  23312. /**
  23313. * Returns the instancing divisor, zero for non-instanced (integer).
  23314. */
  23315. VertexBuffer.prototype.getInstanceDivisor = function () {
  23316. return this._buffer.instanceDivisor;
  23317. };
  23318. // Methods
  23319. /**
  23320. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23321. * Returns the created WebGLBuffer.
  23322. */
  23323. VertexBuffer.prototype.create = function (data) {
  23324. return this._buffer.create(data);
  23325. };
  23326. /**
  23327. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23328. * Returns the updated WebGLBuffer.
  23329. */
  23330. VertexBuffer.prototype.update = function (data) {
  23331. return this._buffer.update(data);
  23332. };
  23333. /**
  23334. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23335. * Returns the directly updated WebGLBuffer.
  23336. */
  23337. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23338. return this._buffer.updateDirectly(data, offset);
  23339. };
  23340. /**
  23341. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23342. */
  23343. VertexBuffer.prototype.dispose = function () {
  23344. if (this._ownsBuffer) {
  23345. this._buffer.dispose();
  23346. }
  23347. };
  23348. Object.defineProperty(VertexBuffer, "PositionKind", {
  23349. get: function () {
  23350. return VertexBuffer._PositionKind;
  23351. },
  23352. enumerable: true,
  23353. configurable: true
  23354. });
  23355. Object.defineProperty(VertexBuffer, "NormalKind", {
  23356. get: function () {
  23357. return VertexBuffer._NormalKind;
  23358. },
  23359. enumerable: true,
  23360. configurable: true
  23361. });
  23362. Object.defineProperty(VertexBuffer, "TangentKind", {
  23363. get: function () {
  23364. return VertexBuffer._TangentKind;
  23365. },
  23366. enumerable: true,
  23367. configurable: true
  23368. });
  23369. Object.defineProperty(VertexBuffer, "UVKind", {
  23370. get: function () {
  23371. return VertexBuffer._UVKind;
  23372. },
  23373. enumerable: true,
  23374. configurable: true
  23375. });
  23376. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23377. get: function () {
  23378. return VertexBuffer._UV2Kind;
  23379. },
  23380. enumerable: true,
  23381. configurable: true
  23382. });
  23383. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23384. get: function () {
  23385. return VertexBuffer._UV3Kind;
  23386. },
  23387. enumerable: true,
  23388. configurable: true
  23389. });
  23390. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23391. get: function () {
  23392. return VertexBuffer._UV4Kind;
  23393. },
  23394. enumerable: true,
  23395. configurable: true
  23396. });
  23397. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23398. get: function () {
  23399. return VertexBuffer._UV5Kind;
  23400. },
  23401. enumerable: true,
  23402. configurable: true
  23403. });
  23404. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23405. get: function () {
  23406. return VertexBuffer._UV6Kind;
  23407. },
  23408. enumerable: true,
  23409. configurable: true
  23410. });
  23411. Object.defineProperty(VertexBuffer, "ColorKind", {
  23412. get: function () {
  23413. return VertexBuffer._ColorKind;
  23414. },
  23415. enumerable: true,
  23416. configurable: true
  23417. });
  23418. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23419. get: function () {
  23420. return VertexBuffer._MatricesIndicesKind;
  23421. },
  23422. enumerable: true,
  23423. configurable: true
  23424. });
  23425. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23426. get: function () {
  23427. return VertexBuffer._MatricesWeightsKind;
  23428. },
  23429. enumerable: true,
  23430. configurable: true
  23431. });
  23432. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23433. get: function () {
  23434. return VertexBuffer._MatricesIndicesExtraKind;
  23435. },
  23436. enumerable: true,
  23437. configurable: true
  23438. });
  23439. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23440. get: function () {
  23441. return VertexBuffer._MatricesWeightsExtraKind;
  23442. },
  23443. enumerable: true,
  23444. configurable: true
  23445. });
  23446. // Enums
  23447. VertexBuffer._PositionKind = "position";
  23448. VertexBuffer._NormalKind = "normal";
  23449. VertexBuffer._TangentKind = "tangent";
  23450. VertexBuffer._UVKind = "uv";
  23451. VertexBuffer._UV2Kind = "uv2";
  23452. VertexBuffer._UV3Kind = "uv3";
  23453. VertexBuffer._UV4Kind = "uv4";
  23454. VertexBuffer._UV5Kind = "uv5";
  23455. VertexBuffer._UV6Kind = "uv6";
  23456. VertexBuffer._ColorKind = "color";
  23457. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23458. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23459. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23460. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23461. return VertexBuffer;
  23462. }());
  23463. BABYLON.VertexBuffer = VertexBuffer;
  23464. })(BABYLON || (BABYLON = {}));
  23465. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23466. var BABYLON;
  23467. (function (BABYLON) {
  23468. var InternalTexture = /** @class */ (function () {
  23469. function InternalTexture(engine, dataSource) {
  23470. this.onLoadedObservable = new BABYLON.Observable();
  23471. // Private
  23472. this._initialSlot = -1;
  23473. this._designatedSlot = -1;
  23474. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23475. this._references = 1;
  23476. this._engine = engine;
  23477. this._dataSource = dataSource;
  23478. this._webGLTexture = engine._createTexture();
  23479. }
  23480. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23481. get: function () {
  23482. return this._dataSource;
  23483. },
  23484. enumerable: true,
  23485. configurable: true
  23486. });
  23487. InternalTexture.prototype.incrementReferences = function () {
  23488. this._references++;
  23489. };
  23490. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23491. if (depth === void 0) { depth = 1; }
  23492. this.width = width;
  23493. this.height = height;
  23494. this.depth = depth;
  23495. this.baseWidth = width;
  23496. this.baseHeight = height;
  23497. this.baseDepth = depth;
  23498. this._size = width * height * depth;
  23499. };
  23500. InternalTexture.prototype._rebuild = function () {
  23501. var _this = this;
  23502. var proxy;
  23503. this.isReady = false;
  23504. this._cachedCoordinatesMode = null;
  23505. this._cachedWrapU = null;
  23506. this._cachedWrapV = null;
  23507. this._cachedAnisotropicFilteringLevel = null;
  23508. switch (this._dataSource) {
  23509. case InternalTexture.DATASOURCE_TEMP:
  23510. return;
  23511. case InternalTexture.DATASOURCE_URL:
  23512. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23513. _this.isReady = true;
  23514. }, null, this._buffer, undefined, this.format);
  23515. proxy._swapAndDie(this);
  23516. return;
  23517. case InternalTexture.DATASOURCE_RAW:
  23518. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23519. proxy._swapAndDie(this);
  23520. this.isReady = true;
  23521. return;
  23522. case InternalTexture.DATASOURCE_RAW3D:
  23523. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23524. proxy._swapAndDie(this);
  23525. this.isReady = true;
  23526. return;
  23527. case InternalTexture.DATASOURCE_DYNAMIC:
  23528. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23529. proxy._swapAndDie(this);
  23530. // The engine will make sure to update content so no need to flag it as isReady = true
  23531. return;
  23532. case InternalTexture.DATASOURCE_RENDERTARGET:
  23533. var options = new BABYLON.RenderTargetCreationOptions();
  23534. options.generateDepthBuffer = this._generateDepthBuffer;
  23535. options.generateMipMaps = this.generateMipMaps;
  23536. options.generateStencilBuffer = this._generateStencilBuffer;
  23537. options.samplingMode = this.samplingMode;
  23538. options.type = this.type;
  23539. if (this.isCube) {
  23540. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23541. }
  23542. else {
  23543. var size = {
  23544. width: this.width,
  23545. height: this.height
  23546. };
  23547. proxy = this._engine.createRenderTargetTexture(size, options);
  23548. }
  23549. proxy._swapAndDie(this);
  23550. this.isReady = true;
  23551. return;
  23552. case InternalTexture.DATASOURCE_CUBE:
  23553. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23554. _this.isReady = true;
  23555. }, null, this.format, this._extension);
  23556. proxy._swapAndDie(this);
  23557. return;
  23558. case InternalTexture.DATASOURCE_CUBERAW:
  23559. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23560. proxy._swapAndDie(this);
  23561. this.isReady = true;
  23562. return;
  23563. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23564. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23565. if (proxy) {
  23566. proxy._swapAndDie(_this);
  23567. }
  23568. _this.isReady = true;
  23569. }, null, this.format, this._extension);
  23570. return;
  23571. }
  23572. };
  23573. InternalTexture.prototype._swapAndDie = function (target) {
  23574. target._webGLTexture = this._webGLTexture;
  23575. if (this._framebuffer) {
  23576. target._framebuffer = this._framebuffer;
  23577. }
  23578. if (this._depthStencilBuffer) {
  23579. target._depthStencilBuffer = this._depthStencilBuffer;
  23580. }
  23581. if (this._lodTextureHigh) {
  23582. if (target._lodTextureHigh) {
  23583. target._lodTextureHigh.dispose();
  23584. }
  23585. target._lodTextureHigh = this._lodTextureHigh;
  23586. }
  23587. if (this._lodTextureMid) {
  23588. if (target._lodTextureMid) {
  23589. target._lodTextureMid.dispose();
  23590. }
  23591. target._lodTextureMid = this._lodTextureMid;
  23592. }
  23593. if (this._lodTextureLow) {
  23594. if (target._lodTextureLow) {
  23595. target._lodTextureLow.dispose();
  23596. }
  23597. target._lodTextureLow = this._lodTextureLow;
  23598. }
  23599. var cache = this._engine.getLoadedTexturesCache();
  23600. var index = cache.indexOf(this);
  23601. if (index !== -1) {
  23602. cache.splice(index, 1);
  23603. }
  23604. };
  23605. InternalTexture.prototype.dispose = function () {
  23606. if (!this._webGLTexture) {
  23607. return;
  23608. }
  23609. this._references--;
  23610. if (this._references === 0) {
  23611. this._engine._releaseTexture(this);
  23612. this._webGLTexture = null;
  23613. }
  23614. };
  23615. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23616. InternalTexture.DATASOURCE_URL = 1;
  23617. InternalTexture.DATASOURCE_TEMP = 2;
  23618. InternalTexture.DATASOURCE_RAW = 3;
  23619. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23620. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23621. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23622. InternalTexture.DATASOURCE_CUBE = 7;
  23623. InternalTexture.DATASOURCE_CUBERAW = 8;
  23624. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23625. InternalTexture.DATASOURCE_RAW3D = 10;
  23626. return InternalTexture;
  23627. }());
  23628. BABYLON.InternalTexture = InternalTexture;
  23629. })(BABYLON || (BABYLON = {}));
  23630. //# sourceMappingURL=babylon.internalTexture.js.map
  23631. var BABYLON;
  23632. (function (BABYLON) {
  23633. var BaseTexture = /** @class */ (function () {
  23634. function BaseTexture(scene) {
  23635. this._hasAlpha = false;
  23636. this.getAlphaFromRGB = false;
  23637. this.level = 1;
  23638. this.coordinatesIndex = 0;
  23639. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23640. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23641. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23642. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23643. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23644. this.isCube = false;
  23645. this.is3D = false;
  23646. this.gammaSpace = true;
  23647. this.invertZ = false;
  23648. this.lodLevelInAlpha = false;
  23649. this.lodGenerationOffset = 0.0;
  23650. this.lodGenerationScale = 0.8;
  23651. this.isRenderTarget = false;
  23652. this.animations = new Array();
  23653. /**
  23654. * An event triggered when the texture is disposed.
  23655. * @type {BABYLON.Observable}
  23656. */
  23657. this.onDisposeObservable = new BABYLON.Observable();
  23658. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23659. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23660. if (this._scene) {
  23661. this._scene.textures.push(this);
  23662. }
  23663. this._uid = null;
  23664. }
  23665. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23666. get: function () {
  23667. return this._hasAlpha;
  23668. },
  23669. set: function (value) {
  23670. if (this._hasAlpha === value) {
  23671. return;
  23672. }
  23673. this._hasAlpha = value;
  23674. if (this._scene) {
  23675. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23676. }
  23677. },
  23678. enumerable: true,
  23679. configurable: true
  23680. });
  23681. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23682. get: function () {
  23683. return this._coordinatesMode;
  23684. },
  23685. set: function (value) {
  23686. if (this._coordinatesMode === value) {
  23687. return;
  23688. }
  23689. this._coordinatesMode = value;
  23690. if (this._scene) {
  23691. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23692. }
  23693. },
  23694. enumerable: true,
  23695. configurable: true
  23696. });
  23697. Object.defineProperty(BaseTexture.prototype, "uid", {
  23698. get: function () {
  23699. if (!this._uid) {
  23700. this._uid = BABYLON.Tools.RandomId();
  23701. }
  23702. return this._uid;
  23703. },
  23704. enumerable: true,
  23705. configurable: true
  23706. });
  23707. BaseTexture.prototype.toString = function () {
  23708. return this.name;
  23709. };
  23710. BaseTexture.prototype.getClassName = function () {
  23711. return "BaseTexture";
  23712. };
  23713. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23714. set: function (callback) {
  23715. if (this._onDisposeObserver) {
  23716. this.onDisposeObservable.remove(this._onDisposeObserver);
  23717. }
  23718. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23724. get: function () {
  23725. return true;
  23726. },
  23727. enumerable: true,
  23728. configurable: true
  23729. });
  23730. BaseTexture.prototype.getScene = function () {
  23731. return this._scene;
  23732. };
  23733. BaseTexture.prototype.getTextureMatrix = function () {
  23734. return BABYLON.Matrix.IdentityReadOnly;
  23735. };
  23736. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23737. return BABYLON.Matrix.IdentityReadOnly;
  23738. };
  23739. BaseTexture.prototype.getInternalTexture = function () {
  23740. return this._texture;
  23741. };
  23742. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23743. return !this.isBlocking || this.isReady();
  23744. };
  23745. BaseTexture.prototype.isReady = function () {
  23746. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23747. this.delayLoad();
  23748. return false;
  23749. }
  23750. if (this._texture) {
  23751. return this._texture.isReady;
  23752. }
  23753. return false;
  23754. };
  23755. BaseTexture.prototype.getSize = function () {
  23756. if (this._texture && this._texture.width) {
  23757. return new BABYLON.Size(this._texture.width, this._texture.height);
  23758. }
  23759. if (this._texture && this._texture._size) {
  23760. return new BABYLON.Size(this._texture._size, this._texture._size);
  23761. }
  23762. return BABYLON.Size.Zero();
  23763. };
  23764. BaseTexture.prototype.getBaseSize = function () {
  23765. if (!this.isReady() || !this._texture)
  23766. return BABYLON.Size.Zero();
  23767. if (this._texture._size) {
  23768. return new BABYLON.Size(this._texture._size, this._texture._size);
  23769. }
  23770. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23771. };
  23772. BaseTexture.prototype.scale = function (ratio) {
  23773. };
  23774. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23775. get: function () {
  23776. return false;
  23777. },
  23778. enumerable: true,
  23779. configurable: true
  23780. });
  23781. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23782. if (!this._scene) {
  23783. return null;
  23784. }
  23785. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23786. for (var index = 0; index < texturesCache.length; index++) {
  23787. var texturesCacheEntry = texturesCache[index];
  23788. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  23789. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23790. texturesCacheEntry.incrementReferences();
  23791. return texturesCacheEntry;
  23792. }
  23793. }
  23794. }
  23795. return null;
  23796. };
  23797. BaseTexture.prototype._rebuild = function () {
  23798. };
  23799. BaseTexture.prototype.delayLoad = function () {
  23800. };
  23801. BaseTexture.prototype.clone = function () {
  23802. return null;
  23803. };
  23804. Object.defineProperty(BaseTexture.prototype, "textureType", {
  23805. get: function () {
  23806. if (!this._texture) {
  23807. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23808. }
  23809. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  23810. },
  23811. enumerable: true,
  23812. configurable: true
  23813. });
  23814. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  23815. get: function () {
  23816. if (!this._texture) {
  23817. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23818. }
  23819. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  23820. },
  23821. enumerable: true,
  23822. configurable: true
  23823. });
  23824. BaseTexture.prototype.readPixels = function (faceIndex) {
  23825. if (faceIndex === void 0) { faceIndex = 0; }
  23826. if (!this._texture) {
  23827. return null;
  23828. }
  23829. var size = this.getSize();
  23830. var scene = this.getScene();
  23831. if (!scene) {
  23832. return null;
  23833. }
  23834. var engine = scene.getEngine();
  23835. if (this._texture.isCube) {
  23836. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  23837. }
  23838. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  23839. };
  23840. BaseTexture.prototype.releaseInternalTexture = function () {
  23841. if (this._texture) {
  23842. this._texture.dispose();
  23843. this._texture = null;
  23844. }
  23845. };
  23846. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  23847. get: function () {
  23848. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  23849. return null;
  23850. }
  23851. if (!this._texture._sphericalPolynomial) {
  23852. this._texture._sphericalPolynomial =
  23853. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  23854. }
  23855. return this._texture._sphericalPolynomial;
  23856. },
  23857. set: function (value) {
  23858. if (this._texture) {
  23859. this._texture._sphericalPolynomial = value;
  23860. }
  23861. },
  23862. enumerable: true,
  23863. configurable: true
  23864. });
  23865. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  23866. get: function () {
  23867. if (this._texture) {
  23868. return this._texture._lodTextureHigh;
  23869. }
  23870. return null;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  23876. get: function () {
  23877. if (this._texture) {
  23878. return this._texture._lodTextureMid;
  23879. }
  23880. return null;
  23881. },
  23882. enumerable: true,
  23883. configurable: true
  23884. });
  23885. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  23886. get: function () {
  23887. if (this._texture) {
  23888. return this._texture._lodTextureLow;
  23889. }
  23890. return null;
  23891. },
  23892. enumerable: true,
  23893. configurable: true
  23894. });
  23895. BaseTexture.prototype.dispose = function () {
  23896. if (!this._scene) {
  23897. return;
  23898. }
  23899. // Animations
  23900. this._scene.stopAnimation(this);
  23901. // Remove from scene
  23902. this._scene._removePendingData(this);
  23903. var index = this._scene.textures.indexOf(this);
  23904. if (index >= 0) {
  23905. this._scene.textures.splice(index, 1);
  23906. }
  23907. if (this._texture === undefined) {
  23908. return;
  23909. }
  23910. // Release
  23911. this.releaseInternalTexture();
  23912. // Callback
  23913. this.onDisposeObservable.notifyObservers(this);
  23914. this.onDisposeObservable.clear();
  23915. };
  23916. BaseTexture.prototype.serialize = function () {
  23917. if (!this.name) {
  23918. return null;
  23919. }
  23920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23921. // Animations
  23922. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23923. return serializationObject;
  23924. };
  23925. BaseTexture.WhenAllReady = function (textures, callback) {
  23926. var numRemaining = textures.length;
  23927. if (numRemaining === 0) {
  23928. callback();
  23929. return;
  23930. }
  23931. var _loop_1 = function () {
  23932. texture = textures[i];
  23933. if (texture.isReady()) {
  23934. if (--numRemaining === 0) {
  23935. callback();
  23936. }
  23937. }
  23938. else {
  23939. onLoadObservable = texture.onLoadObservable;
  23940. var onLoadCallback_1 = function () {
  23941. onLoadObservable.removeCallback(onLoadCallback_1);
  23942. if (--numRemaining === 0) {
  23943. callback();
  23944. }
  23945. };
  23946. onLoadObservable.add(onLoadCallback_1);
  23947. }
  23948. };
  23949. var texture, onLoadObservable;
  23950. for (var i = 0; i < textures.length; i++) {
  23951. _loop_1();
  23952. }
  23953. };
  23954. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  23955. __decorate([
  23956. BABYLON.serialize()
  23957. ], BaseTexture.prototype, "name", void 0);
  23958. __decorate([
  23959. BABYLON.serialize("hasAlpha")
  23960. ], BaseTexture.prototype, "_hasAlpha", void 0);
  23961. __decorate([
  23962. BABYLON.serialize()
  23963. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23964. __decorate([
  23965. BABYLON.serialize()
  23966. ], BaseTexture.prototype, "level", void 0);
  23967. __decorate([
  23968. BABYLON.serialize()
  23969. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23970. __decorate([
  23971. BABYLON.serialize("coordinatesMode")
  23972. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23973. __decorate([
  23974. BABYLON.serialize()
  23975. ], BaseTexture.prototype, "wrapU", void 0);
  23976. __decorate([
  23977. BABYLON.serialize()
  23978. ], BaseTexture.prototype, "wrapV", void 0);
  23979. __decorate([
  23980. BABYLON.serialize()
  23981. ], BaseTexture.prototype, "wrapR", void 0);
  23982. __decorate([
  23983. BABYLON.serialize()
  23984. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23985. __decorate([
  23986. BABYLON.serialize()
  23987. ], BaseTexture.prototype, "isCube", void 0);
  23988. __decorate([
  23989. BABYLON.serialize()
  23990. ], BaseTexture.prototype, "is3D", void 0);
  23991. __decorate([
  23992. BABYLON.serialize()
  23993. ], BaseTexture.prototype, "gammaSpace", void 0);
  23994. __decorate([
  23995. BABYLON.serialize()
  23996. ], BaseTexture.prototype, "invertZ", void 0);
  23997. __decorate([
  23998. BABYLON.serialize()
  23999. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24000. __decorate([
  24001. BABYLON.serialize()
  24002. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24003. __decorate([
  24004. BABYLON.serialize()
  24005. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24006. __decorate([
  24007. BABYLON.serialize()
  24008. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24009. return BaseTexture;
  24010. }());
  24011. BABYLON.BaseTexture = BaseTexture;
  24012. })(BABYLON || (BABYLON = {}));
  24013. //# sourceMappingURL=babylon.baseTexture.js.map
  24014. var BABYLON;
  24015. (function (BABYLON) {
  24016. var Texture = /** @class */ (function (_super) {
  24017. __extends(Texture, _super);
  24018. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24019. if (noMipmap === void 0) { noMipmap = false; }
  24020. if (invertY === void 0) { invertY = true; }
  24021. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24022. if (onLoad === void 0) { onLoad = null; }
  24023. if (onError === void 0) { onError = null; }
  24024. if (buffer === void 0) { buffer = null; }
  24025. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24026. var _this = _super.call(this, scene) || this;
  24027. _this.uOffset = 0;
  24028. _this.vOffset = 0;
  24029. _this.uScale = 1.0;
  24030. _this.vScale = 1.0;
  24031. _this.uAng = 0;
  24032. _this.vAng = 0;
  24033. _this.wAng = 0;
  24034. _this._isBlocking = true;
  24035. _this.name = url || "";
  24036. _this.url = url;
  24037. _this._noMipmap = noMipmap;
  24038. _this._invertY = invertY;
  24039. _this._samplingMode = samplingMode;
  24040. _this._buffer = buffer;
  24041. _this._deleteBuffer = deleteBuffer;
  24042. if (format) {
  24043. _this._format = format;
  24044. }
  24045. scene = _this.getScene();
  24046. if (!scene) {
  24047. return _this;
  24048. }
  24049. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24050. var load = function () {
  24051. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24052. _this.onLoadObservable.notifyObservers(_this);
  24053. }
  24054. if (onLoad) {
  24055. onLoad();
  24056. }
  24057. if (!_this.isBlocking && scene) {
  24058. scene.resetCachedMaterial();
  24059. }
  24060. };
  24061. if (!_this.url) {
  24062. _this._delayedOnLoad = load;
  24063. _this._delayedOnError = onError;
  24064. return _this;
  24065. }
  24066. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24067. if (!_this._texture) {
  24068. if (!scene.useDelayedTextureLoading) {
  24069. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24070. if (deleteBuffer) {
  24071. delete _this._buffer;
  24072. }
  24073. }
  24074. else {
  24075. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24076. _this._delayedOnLoad = load;
  24077. _this._delayedOnError = onError;
  24078. }
  24079. }
  24080. else {
  24081. if (_this._texture.isReady) {
  24082. BABYLON.Tools.SetImmediate(function () { return load(); });
  24083. }
  24084. else {
  24085. _this._texture.onLoadedObservable.add(load);
  24086. }
  24087. }
  24088. return _this;
  24089. }
  24090. Object.defineProperty(Texture.prototype, "noMipmap", {
  24091. get: function () {
  24092. return this._noMipmap;
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. Object.defineProperty(Texture.prototype, "isBlocking", {
  24098. get: function () {
  24099. return this._isBlocking;
  24100. },
  24101. set: function (value) {
  24102. this._isBlocking = value;
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(Texture.prototype, "samplingMode", {
  24108. get: function () {
  24109. return this._samplingMode;
  24110. },
  24111. enumerable: true,
  24112. configurable: true
  24113. });
  24114. Texture.prototype.updateURL = function (url) {
  24115. this.url = url;
  24116. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24117. this.delayLoad();
  24118. };
  24119. Texture.prototype.delayLoad = function () {
  24120. var _this = this;
  24121. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24122. return;
  24123. }
  24124. var scene = this.getScene();
  24125. if (!scene) {
  24126. return;
  24127. }
  24128. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24129. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24130. if (!this._texture) {
  24131. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24132. if (this._deleteBuffer) {
  24133. delete this._buffer;
  24134. }
  24135. }
  24136. else {
  24137. if (this._texture.isReady) {
  24138. BABYLON.Tools.SetImmediate(function () {
  24139. if (!_this._delayedOnLoad) {
  24140. return;
  24141. }
  24142. _this._delayedOnLoad();
  24143. });
  24144. }
  24145. else {
  24146. if (this._delayedOnLoad) {
  24147. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24148. }
  24149. }
  24150. }
  24151. };
  24152. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24153. if (!this._texture) {
  24154. return;
  24155. }
  24156. var scene = this.getScene();
  24157. if (!scene) {
  24158. return;
  24159. }
  24160. this._samplingMode = samplingMode;
  24161. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24162. };
  24163. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24164. x *= this.uScale;
  24165. y *= this.vScale;
  24166. x -= 0.5 * this.uScale;
  24167. y -= 0.5 * this.vScale;
  24168. z -= 0.5;
  24169. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24170. t.x += 0.5 * this.uScale + this.uOffset;
  24171. t.y += 0.5 * this.vScale + this.vOffset;
  24172. t.z += 0.5;
  24173. };
  24174. Texture.prototype.getTextureMatrix = function () {
  24175. var _this = this;
  24176. if (this.uOffset === this._cachedUOffset &&
  24177. this.vOffset === this._cachedVOffset &&
  24178. this.uScale === this._cachedUScale &&
  24179. this.vScale === this._cachedVScale &&
  24180. this.uAng === this._cachedUAng &&
  24181. this.vAng === this._cachedVAng &&
  24182. this.wAng === this._cachedWAng) {
  24183. return this._cachedTextureMatrix;
  24184. }
  24185. this._cachedUOffset = this.uOffset;
  24186. this._cachedVOffset = this.vOffset;
  24187. this._cachedUScale = this.uScale;
  24188. this._cachedVScale = this.vScale;
  24189. this._cachedUAng = this.uAng;
  24190. this._cachedVAng = this.vAng;
  24191. this._cachedWAng = this.wAng;
  24192. if (!this._cachedTextureMatrix) {
  24193. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24194. this._rowGenerationMatrix = new BABYLON.Matrix();
  24195. this._t0 = BABYLON.Vector3.Zero();
  24196. this._t1 = BABYLON.Vector3.Zero();
  24197. this._t2 = BABYLON.Vector3.Zero();
  24198. }
  24199. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24200. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24201. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24202. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24203. this._t1.subtractInPlace(this._t0);
  24204. this._t2.subtractInPlace(this._t0);
  24205. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24206. this._cachedTextureMatrix.m[0] = this._t1.x;
  24207. this._cachedTextureMatrix.m[1] = this._t1.y;
  24208. this._cachedTextureMatrix.m[2] = this._t1.z;
  24209. this._cachedTextureMatrix.m[4] = this._t2.x;
  24210. this._cachedTextureMatrix.m[5] = this._t2.y;
  24211. this._cachedTextureMatrix.m[6] = this._t2.z;
  24212. this._cachedTextureMatrix.m[8] = this._t0.x;
  24213. this._cachedTextureMatrix.m[9] = this._t0.y;
  24214. this._cachedTextureMatrix.m[10] = this._t0.z;
  24215. var scene = this.getScene();
  24216. if (!scene) {
  24217. return this._cachedTextureMatrix;
  24218. }
  24219. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24220. return mat.hasTexture(_this);
  24221. });
  24222. return this._cachedTextureMatrix;
  24223. };
  24224. Texture.prototype.getReflectionTextureMatrix = function () {
  24225. var _this = this;
  24226. var scene = this.getScene();
  24227. if (!scene) {
  24228. return this._cachedTextureMatrix;
  24229. }
  24230. if (this.uOffset === this._cachedUOffset &&
  24231. this.vOffset === this._cachedVOffset &&
  24232. this.uScale === this._cachedUScale &&
  24233. this.vScale === this._cachedVScale &&
  24234. this.coordinatesMode === this._cachedCoordinatesMode) {
  24235. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24236. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24237. return this._cachedTextureMatrix;
  24238. }
  24239. }
  24240. else {
  24241. return this._cachedTextureMatrix;
  24242. }
  24243. }
  24244. if (!this._cachedTextureMatrix) {
  24245. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24246. }
  24247. if (!this._projectionModeMatrix) {
  24248. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24249. }
  24250. this._cachedUOffset = this.uOffset;
  24251. this._cachedVOffset = this.vOffset;
  24252. this._cachedUScale = this.uScale;
  24253. this._cachedVScale = this.vScale;
  24254. this._cachedCoordinatesMode = this.coordinatesMode;
  24255. switch (this.coordinatesMode) {
  24256. case Texture.PLANAR_MODE:
  24257. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24258. this._cachedTextureMatrix[0] = this.uScale;
  24259. this._cachedTextureMatrix[5] = this.vScale;
  24260. this._cachedTextureMatrix[12] = this.uOffset;
  24261. this._cachedTextureMatrix[13] = this.vOffset;
  24262. break;
  24263. case Texture.PROJECTION_MODE:
  24264. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24265. this._projectionModeMatrix.m[0] = 0.5;
  24266. this._projectionModeMatrix.m[5] = -0.5;
  24267. this._projectionModeMatrix.m[10] = 0.0;
  24268. this._projectionModeMatrix.m[12] = 0.5;
  24269. this._projectionModeMatrix.m[13] = 0.5;
  24270. this._projectionModeMatrix.m[14] = 1.0;
  24271. this._projectionModeMatrix.m[15] = 1.0;
  24272. var projectionMatrix = scene.getProjectionMatrix();
  24273. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24274. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24275. break;
  24276. default:
  24277. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24278. break;
  24279. }
  24280. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24281. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24282. });
  24283. return this._cachedTextureMatrix;
  24284. };
  24285. Texture.prototype.clone = function () {
  24286. var _this = this;
  24287. return BABYLON.SerializationHelper.Clone(function () {
  24288. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24289. }, this);
  24290. };
  24291. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24292. get: function () {
  24293. if (!this._onLoadObservable) {
  24294. this._onLoadObservable = new BABYLON.Observable();
  24295. }
  24296. return this._onLoadObservable;
  24297. },
  24298. enumerable: true,
  24299. configurable: true
  24300. });
  24301. Texture.prototype.serialize = function () {
  24302. var serializationObject = _super.prototype.serialize.call(this);
  24303. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24304. serializationObject.base64String = this._buffer;
  24305. serializationObject.name = serializationObject.name.replace("data:", "");
  24306. }
  24307. return serializationObject;
  24308. };
  24309. Texture.prototype.getClassName = function () {
  24310. return "Texture";
  24311. };
  24312. Texture.prototype.dispose = function () {
  24313. _super.prototype.dispose.call(this);
  24314. if (this.onLoadObservable) {
  24315. this.onLoadObservable.clear();
  24316. this._onLoadObservable = null;
  24317. }
  24318. this._delayedOnLoad = null;
  24319. this._delayedOnError = null;
  24320. };
  24321. // Statics
  24322. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24323. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24324. if (onLoad === void 0) { onLoad = null; }
  24325. if (onError === void 0) { onError = null; }
  24326. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24327. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24328. };
  24329. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24330. if (parsedTexture.customType) {
  24331. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24332. // Update Sampling Mode
  24333. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24334. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24335. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24336. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24337. }
  24338. }
  24339. return parsedCustomTexture;
  24340. }
  24341. if (parsedTexture.isCube) {
  24342. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24343. }
  24344. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24345. return null;
  24346. }
  24347. var texture = BABYLON.SerializationHelper.Parse(function () {
  24348. var generateMipMaps = true;
  24349. if (parsedTexture.noMipmap) {
  24350. generateMipMaps = false;
  24351. }
  24352. if (parsedTexture.mirrorPlane) {
  24353. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24354. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24355. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24356. return mirrorTexture;
  24357. }
  24358. else if (parsedTexture.isRenderTarget) {
  24359. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24360. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24361. return renderTargetTexture;
  24362. }
  24363. else {
  24364. var texture;
  24365. if (parsedTexture.base64String) {
  24366. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24367. }
  24368. else {
  24369. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24370. }
  24371. return texture;
  24372. }
  24373. }, parsedTexture, scene);
  24374. // Update Sampling Mode
  24375. if (parsedTexture.samplingMode) {
  24376. var sampling = parsedTexture.samplingMode;
  24377. if (texture._samplingMode !== sampling) {
  24378. texture.updateSamplingMode(sampling);
  24379. }
  24380. }
  24381. // Animations
  24382. if (parsedTexture.animations) {
  24383. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24384. var parsedAnimation = parsedTexture.animations[animationIndex];
  24385. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24386. }
  24387. }
  24388. return texture;
  24389. };
  24390. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24391. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24392. if (noMipmap === void 0) { noMipmap = false; }
  24393. if (invertY === void 0) { invertY = true; }
  24394. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24395. if (onLoad === void 0) { onLoad = null; }
  24396. if (onError === void 0) { onError = null; }
  24397. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24398. if (name.substr(0, 5) !== "data:") {
  24399. name = "data:" + name;
  24400. }
  24401. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24402. };
  24403. // Constants
  24404. Texture.NEAREST_SAMPLINGMODE = 1;
  24405. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24406. Texture.BILINEAR_SAMPLINGMODE = 2;
  24407. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24408. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24409. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24410. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24411. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24412. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24413. Texture.NEAREST_LINEAR = 7;
  24414. Texture.NEAREST_NEAREST = 8;
  24415. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24416. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24417. Texture.LINEAR_LINEAR = 11;
  24418. Texture.LINEAR_NEAREST = 12;
  24419. Texture.EXPLICIT_MODE = 0;
  24420. Texture.SPHERICAL_MODE = 1;
  24421. Texture.PLANAR_MODE = 2;
  24422. Texture.CUBIC_MODE = 3;
  24423. Texture.PROJECTION_MODE = 4;
  24424. Texture.SKYBOX_MODE = 5;
  24425. Texture.INVCUBIC_MODE = 6;
  24426. Texture.EQUIRECTANGULAR_MODE = 7;
  24427. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24428. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24429. Texture.CLAMP_ADDRESSMODE = 0;
  24430. Texture.WRAP_ADDRESSMODE = 1;
  24431. Texture.MIRROR_ADDRESSMODE = 2;
  24432. __decorate([
  24433. BABYLON.serialize()
  24434. ], Texture.prototype, "url", void 0);
  24435. __decorate([
  24436. BABYLON.serialize()
  24437. ], Texture.prototype, "uOffset", void 0);
  24438. __decorate([
  24439. BABYLON.serialize()
  24440. ], Texture.prototype, "vOffset", void 0);
  24441. __decorate([
  24442. BABYLON.serialize()
  24443. ], Texture.prototype, "uScale", void 0);
  24444. __decorate([
  24445. BABYLON.serialize()
  24446. ], Texture.prototype, "vScale", void 0);
  24447. __decorate([
  24448. BABYLON.serialize()
  24449. ], Texture.prototype, "uAng", void 0);
  24450. __decorate([
  24451. BABYLON.serialize()
  24452. ], Texture.prototype, "vAng", void 0);
  24453. __decorate([
  24454. BABYLON.serialize()
  24455. ], Texture.prototype, "wAng", void 0);
  24456. __decorate([
  24457. BABYLON.serialize()
  24458. ], Texture.prototype, "isBlocking", null);
  24459. return Texture;
  24460. }(BABYLON.BaseTexture));
  24461. BABYLON.Texture = Texture;
  24462. })(BABYLON || (BABYLON = {}));
  24463. //# sourceMappingURL=babylon.texture.js.map
  24464. var BABYLON;
  24465. (function (BABYLON) {
  24466. var _InstancesBatch = /** @class */ (function () {
  24467. function _InstancesBatch() {
  24468. this.mustReturn = false;
  24469. this.visibleInstances = new Array();
  24470. this.renderSelf = new Array();
  24471. }
  24472. return _InstancesBatch;
  24473. }());
  24474. BABYLON._InstancesBatch = _InstancesBatch;
  24475. var Mesh = /** @class */ (function (_super) {
  24476. __extends(Mesh, _super);
  24477. /**
  24478. * @constructor
  24479. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24480. * @param {Scene} scene The scene to add this mesh to.
  24481. * @param {Node} parent The parent of this mesh, if it has one
  24482. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24483. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24484. * When false, achieved by calling a clone(), also passing False.
  24485. * This will make creation of children, recursive.
  24486. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24487. */
  24488. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24489. if (scene === void 0) { scene = null; }
  24490. if (parent === void 0) { parent = null; }
  24491. if (source === void 0) { source = null; }
  24492. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24493. var _this = _super.call(this, name, scene) || this;
  24494. // Events
  24495. /**
  24496. * An event triggered before rendering the mesh
  24497. * @type {BABYLON.Observable}
  24498. */
  24499. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24500. /**
  24501. * An event triggered after rendering the mesh
  24502. * @type {BABYLON.Observable}
  24503. */
  24504. _this.onAfterRenderObservable = new BABYLON.Observable();
  24505. /**
  24506. * An event triggered before drawing the mesh
  24507. * @type {BABYLON.Observable}
  24508. */
  24509. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24510. // Members
  24511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24512. _this.instances = new Array();
  24513. _this._LODLevels = new Array();
  24514. _this._visibleInstances = {};
  24515. _this._renderIdForInstances = new Array();
  24516. _this._batchCache = new _InstancesBatch();
  24517. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24518. // Use by builder only to know what orientation were the mesh build in.
  24519. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24520. _this.overrideMaterialSideOrientation = null;
  24521. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24522. // Will be used to save a source mesh reference, If any
  24523. _this._source = null;
  24524. scene = _this.getScene();
  24525. if (source) {
  24526. // Source mesh
  24527. _this._source = source;
  24528. // Geometry
  24529. if (source._geometry) {
  24530. source._geometry.applyToMesh(_this);
  24531. }
  24532. // Deep copy
  24533. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24534. // Metadata
  24535. if (source.metadata && source.metadata.clone) {
  24536. _this.metadata = source.metadata.clone();
  24537. }
  24538. else {
  24539. _this.metadata = source.metadata;
  24540. }
  24541. // Tags
  24542. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24543. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24544. }
  24545. // Parent
  24546. _this.parent = source.parent;
  24547. // Pivot
  24548. _this.setPivotMatrix(source.getPivotMatrix());
  24549. _this.id = name + "." + source.id;
  24550. // Material
  24551. _this.material = source.material;
  24552. var index;
  24553. if (!doNotCloneChildren) {
  24554. // Children
  24555. var directDescendants = source.getDescendants(true);
  24556. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24557. var child = directDescendants[index_1];
  24558. if (child.clone) {
  24559. child.clone(name + "." + child.name, _this);
  24560. }
  24561. }
  24562. }
  24563. // Physics clone
  24564. var physicsEngine = _this.getScene().getPhysicsEngine();
  24565. if (clonePhysicsImpostor && physicsEngine) {
  24566. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24567. if (impostor) {
  24568. _this.physicsImpostor = impostor.clone(_this);
  24569. }
  24570. }
  24571. // Particles
  24572. for (index = 0; index < scene.particleSystems.length; index++) {
  24573. var system = scene.particleSystems[index];
  24574. if (system.emitter === source) {
  24575. system.clone(system.name, _this);
  24576. }
  24577. }
  24578. _this.computeWorldMatrix(true);
  24579. }
  24580. // Parent
  24581. if (parent !== null) {
  24582. _this.parent = parent;
  24583. }
  24584. return _this;
  24585. }
  24586. Object.defineProperty(Mesh, "FRONTSIDE", {
  24587. /**
  24588. * Mesh side orientation : usually the external or front surface
  24589. */
  24590. get: function () {
  24591. return Mesh._FRONTSIDE;
  24592. },
  24593. enumerable: true,
  24594. configurable: true
  24595. });
  24596. Object.defineProperty(Mesh, "BACKSIDE", {
  24597. /**
  24598. * Mesh side orientation : usually the internal or back surface
  24599. */
  24600. get: function () {
  24601. return Mesh._BACKSIDE;
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24607. /**
  24608. * Mesh side orientation : both internal and external or front and back surfaces
  24609. */
  24610. get: function () {
  24611. return Mesh._DOUBLESIDE;
  24612. },
  24613. enumerable: true,
  24614. configurable: true
  24615. });
  24616. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24617. /**
  24618. * Mesh side orientation : by default, `FRONTSIDE`
  24619. */
  24620. get: function () {
  24621. return Mesh._DEFAULTSIDE;
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Mesh, "NO_CAP", {
  24627. /**
  24628. * Mesh cap setting : no cap
  24629. */
  24630. get: function () {
  24631. return Mesh._NO_CAP;
  24632. },
  24633. enumerable: true,
  24634. configurable: true
  24635. });
  24636. Object.defineProperty(Mesh, "CAP_START", {
  24637. /**
  24638. * Mesh cap setting : one cap at the beginning of the mesh
  24639. */
  24640. get: function () {
  24641. return Mesh._CAP_START;
  24642. },
  24643. enumerable: true,
  24644. configurable: true
  24645. });
  24646. Object.defineProperty(Mesh, "CAP_END", {
  24647. /**
  24648. * Mesh cap setting : one cap at the end of the mesh
  24649. */
  24650. get: function () {
  24651. return Mesh._CAP_END;
  24652. },
  24653. enumerable: true,
  24654. configurable: true
  24655. });
  24656. Object.defineProperty(Mesh, "CAP_ALL", {
  24657. /**
  24658. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24659. */
  24660. get: function () {
  24661. return Mesh._CAP_ALL;
  24662. },
  24663. enumerable: true,
  24664. configurable: true
  24665. });
  24666. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24667. set: function (callback) {
  24668. if (this._onBeforeDrawObserver) {
  24669. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24670. }
  24671. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24672. },
  24673. enumerable: true,
  24674. configurable: true
  24675. });
  24676. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24677. get: function () {
  24678. return this._morphTargetManager;
  24679. },
  24680. set: function (value) {
  24681. if (this._morphTargetManager === value) {
  24682. return;
  24683. }
  24684. this._morphTargetManager = value;
  24685. this._syncGeometryWithMorphTargetManager();
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. Object.defineProperty(Mesh.prototype, "source", {
  24691. get: function () {
  24692. return this._source;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24698. get: function () {
  24699. return this._unIndexed;
  24700. },
  24701. set: function (value) {
  24702. if (this._unIndexed !== value) {
  24703. this._unIndexed = value;
  24704. this._markSubMeshesAsAttributesDirty();
  24705. }
  24706. },
  24707. enumerable: true,
  24708. configurable: true
  24709. });
  24710. // Methods
  24711. /**
  24712. * Returns the string "Mesh".
  24713. */
  24714. Mesh.prototype.getClassName = function () {
  24715. return "Mesh";
  24716. };
  24717. /**
  24718. * Returns a string.
  24719. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24720. */
  24721. Mesh.prototype.toString = function (fullDetails) {
  24722. var ret = _super.prototype.toString.call(this, fullDetails);
  24723. ret += ", n vertices: " + this.getTotalVertices();
  24724. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24725. if (this.animations) {
  24726. for (var i = 0; i < this.animations.length; i++) {
  24727. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24728. }
  24729. }
  24730. if (fullDetails) {
  24731. if (this._geometry) {
  24732. var ib = this.getIndices();
  24733. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24734. if (vb && ib) {
  24735. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24736. }
  24737. }
  24738. else {
  24739. ret += ", flat shading: UNKNOWN";
  24740. }
  24741. }
  24742. return ret;
  24743. };
  24744. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24745. /**
  24746. * True if the mesh has some Levels Of Details (LOD).
  24747. * Returns a boolean.
  24748. */
  24749. get: function () {
  24750. return this._LODLevels.length > 0;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Mesh.prototype._sortLODLevels = function () {
  24756. this._LODLevels.sort(function (a, b) {
  24757. if (a.distance < b.distance) {
  24758. return 1;
  24759. }
  24760. if (a.distance > b.distance) {
  24761. return -1;
  24762. }
  24763. return 0;
  24764. });
  24765. };
  24766. /**
  24767. * Add a mesh as LOD level triggered at the given distance.
  24768. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24769. * @param {number} distance The distance from the center of the object to show this level
  24770. * @param {Mesh} mesh The mesh to be added as LOD level
  24771. * @return {Mesh} This mesh (for chaining)
  24772. */
  24773. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24774. if (mesh && mesh._masterMesh) {
  24775. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24776. return this;
  24777. }
  24778. var level = new BABYLON.MeshLODLevel(distance, mesh);
  24779. this._LODLevels.push(level);
  24780. if (mesh) {
  24781. mesh._masterMesh = this;
  24782. }
  24783. this._sortLODLevels();
  24784. return this;
  24785. };
  24786. /**
  24787. * Returns the LOD level mesh at the passed distance or null if not found.
  24788. * It is related to the method `addLODLevel(distance, mesh)`.
  24789. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24790. * Returns an object Mesh or `null`.
  24791. */
  24792. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  24793. for (var index = 0; index < this._LODLevels.length; index++) {
  24794. var level = this._LODLevels[index];
  24795. if (level.distance === distance) {
  24796. return level.mesh;
  24797. }
  24798. }
  24799. return null;
  24800. };
  24801. /**
  24802. * Remove a mesh from the LOD array
  24803. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24804. * @param {Mesh} mesh The mesh to be removed.
  24805. * @return {Mesh} This mesh (for chaining)
  24806. */
  24807. Mesh.prototype.removeLODLevel = function (mesh) {
  24808. for (var index = 0; index < this._LODLevels.length; index++) {
  24809. if (this._LODLevels[index].mesh === mesh) {
  24810. this._LODLevels.splice(index, 1);
  24811. if (mesh) {
  24812. mesh._masterMesh = null;
  24813. }
  24814. }
  24815. }
  24816. this._sortLODLevels();
  24817. return this;
  24818. };
  24819. /**
  24820. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  24821. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24822. */
  24823. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  24824. if (!this._LODLevels || this._LODLevels.length === 0) {
  24825. return this;
  24826. }
  24827. var bSphere;
  24828. if (boundingSphere) {
  24829. bSphere = boundingSphere;
  24830. }
  24831. else {
  24832. var boundingInfo = this.getBoundingInfo();
  24833. bSphere = boundingInfo.boundingSphere;
  24834. }
  24835. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  24836. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  24837. if (this.onLODLevelSelection) {
  24838. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  24839. }
  24840. return this;
  24841. }
  24842. for (var index = 0; index < this._LODLevels.length; index++) {
  24843. var level = this._LODLevels[index];
  24844. if (level.distance < distanceToCamera) {
  24845. if (level.mesh) {
  24846. level.mesh._preActivate();
  24847. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  24848. }
  24849. if (this.onLODLevelSelection) {
  24850. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  24851. }
  24852. return level.mesh;
  24853. }
  24854. }
  24855. if (this.onLODLevelSelection) {
  24856. this.onLODLevelSelection(distanceToCamera, this, this);
  24857. }
  24858. return this;
  24859. };
  24860. Object.defineProperty(Mesh.prototype, "geometry", {
  24861. /**
  24862. * Returns the mesh internal Geometry object.
  24863. */
  24864. get: function () {
  24865. return this._geometry;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. /**
  24871. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  24872. */
  24873. Mesh.prototype.getTotalVertices = function () {
  24874. if (this._geometry === null || this._geometry === undefined) {
  24875. return 0;
  24876. }
  24877. return this._geometry.getTotalVertices();
  24878. };
  24879. /**
  24880. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  24881. * 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.
  24882. * You can force the copy with forceCopy === true
  24883. * Returns null if the mesh has no geometry or no vertex buffer.
  24884. * Possible `kind` values :
  24885. * - BABYLON.VertexBuffer.PositionKind
  24886. * - BABYLON.VertexBuffer.UVKind
  24887. * - BABYLON.VertexBuffer.UV2Kind
  24888. * - BABYLON.VertexBuffer.UV3Kind
  24889. * - BABYLON.VertexBuffer.UV4Kind
  24890. * - BABYLON.VertexBuffer.UV5Kind
  24891. * - BABYLON.VertexBuffer.UV6Kind
  24892. * - BABYLON.VertexBuffer.ColorKind
  24893. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24894. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24895. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24896. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24897. */
  24898. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  24899. if (!this._geometry) {
  24900. return null;
  24901. }
  24902. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  24903. };
  24904. /**
  24905. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  24906. * Returns `null` if the mesh has no geometry.
  24907. * Possible `kind` values :
  24908. * - BABYLON.VertexBuffer.PositionKind
  24909. * - BABYLON.VertexBuffer.UVKind
  24910. * - BABYLON.VertexBuffer.UV2Kind
  24911. * - BABYLON.VertexBuffer.UV3Kind
  24912. * - BABYLON.VertexBuffer.UV4Kind
  24913. * - BABYLON.VertexBuffer.UV5Kind
  24914. * - BABYLON.VertexBuffer.UV6Kind
  24915. * - BABYLON.VertexBuffer.ColorKind
  24916. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24917. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24918. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24919. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24920. */
  24921. Mesh.prototype.getVertexBuffer = function (kind) {
  24922. if (!this._geometry) {
  24923. return null;
  24924. }
  24925. return this._geometry.getVertexBuffer(kind);
  24926. };
  24927. /**
  24928. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  24929. * Possible `kind` values :
  24930. * - BABYLON.VertexBuffer.PositionKind
  24931. * - BABYLON.VertexBuffer.UVKind
  24932. * - BABYLON.VertexBuffer.UV2Kind
  24933. * - BABYLON.VertexBuffer.UV3Kind
  24934. * - BABYLON.VertexBuffer.UV4Kind
  24935. * - BABYLON.VertexBuffer.UV5Kind
  24936. * - BABYLON.VertexBuffer.UV6Kind
  24937. * - BABYLON.VertexBuffer.ColorKind
  24938. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24939. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24940. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24941. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24942. */
  24943. Mesh.prototype.isVerticesDataPresent = function (kind) {
  24944. if (!this._geometry) {
  24945. if (this._delayInfo) {
  24946. return this._delayInfo.indexOf(kind) !== -1;
  24947. }
  24948. return false;
  24949. }
  24950. return this._geometry.isVerticesDataPresent(kind);
  24951. };
  24952. /**
  24953. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  24954. * Possible `kind` values :
  24955. * - BABYLON.VertexBuffer.PositionKind
  24956. * - BABYLON.VertexBuffer.UVKind
  24957. * - BABYLON.VertexBuffer.UV2Kind
  24958. * - BABYLON.VertexBuffer.UV3Kind
  24959. * - BABYLON.VertexBuffer.UV4Kind
  24960. * - BABYLON.VertexBuffer.UV5Kind
  24961. * - BABYLON.VertexBuffer.UV6Kind
  24962. * - BABYLON.VertexBuffer.ColorKind
  24963. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24964. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24965. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24966. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24967. */
  24968. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24969. if (!this._geometry) {
  24970. if (this._delayInfo) {
  24971. return this._delayInfo.indexOf(kind) !== -1;
  24972. }
  24973. return false;
  24974. }
  24975. return this._geometry.isVertexBufferUpdatable(kind);
  24976. };
  24977. /**
  24978. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24979. * Possible `kind` values :
  24980. * - BABYLON.VertexBuffer.PositionKind
  24981. * - BABYLON.VertexBuffer.UVKind
  24982. * - BABYLON.VertexBuffer.UV2Kind
  24983. * - BABYLON.VertexBuffer.UV3Kind
  24984. * - BABYLON.VertexBuffer.UV4Kind
  24985. * - BABYLON.VertexBuffer.UV5Kind
  24986. * - BABYLON.VertexBuffer.UV6Kind
  24987. * - BABYLON.VertexBuffer.ColorKind
  24988. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24989. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24990. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24991. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24992. */
  24993. Mesh.prototype.getVerticesDataKinds = function () {
  24994. if (!this._geometry) {
  24995. var result = new Array();
  24996. if (this._delayInfo) {
  24997. this._delayInfo.forEach(function (kind, index, array) {
  24998. result.push(kind);
  24999. });
  25000. }
  25001. return result;
  25002. }
  25003. return this._geometry.getVerticesDataKinds();
  25004. };
  25005. /**
  25006. * Returns a positive integer : the total number of indices in this mesh geometry.
  25007. * Returns zero if the mesh has no geometry.
  25008. */
  25009. Mesh.prototype.getTotalIndices = function () {
  25010. if (!this._geometry) {
  25011. return 0;
  25012. }
  25013. return this._geometry.getTotalIndices();
  25014. };
  25015. /**
  25016. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25017. * 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.
  25018. * Returns an empty array if the mesh has no geometry.
  25019. */
  25020. Mesh.prototype.getIndices = function (copyWhenShared) {
  25021. if (!this._geometry) {
  25022. return [];
  25023. }
  25024. return this._geometry.getIndices(copyWhenShared);
  25025. };
  25026. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25027. get: function () {
  25028. return this._masterMesh !== null && this._masterMesh !== undefined;
  25029. },
  25030. enumerable: true,
  25031. configurable: true
  25032. });
  25033. /**
  25034. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  25035. */
  25036. Mesh.prototype.isReady = function () {
  25037. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25038. return false;
  25039. }
  25040. return _super.prototype.isReady.call(this);
  25041. };
  25042. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25043. /**
  25044. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25045. * This property is pertinent only for updatable parametric shapes.
  25046. */
  25047. get: function () {
  25048. return this._areNormalsFrozen;
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. /**
  25054. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25055. * It has no effect at all on other shapes.
  25056. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25057. * Returns the Mesh.
  25058. */
  25059. Mesh.prototype.freezeNormals = function () {
  25060. this._areNormalsFrozen = true;
  25061. return this;
  25062. };
  25063. /**
  25064. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25065. * It has no effect at all on other shapes.
  25066. * It reactivates the mesh normals computation if it was previously frozen.
  25067. * Returns the Mesh.
  25068. */
  25069. Mesh.prototype.unfreezeNormals = function () {
  25070. this._areNormalsFrozen = false;
  25071. return this;
  25072. };
  25073. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25074. /**
  25075. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25076. */
  25077. set: function (count) {
  25078. this._overridenInstanceCount = count;
  25079. },
  25080. enumerable: true,
  25081. configurable: true
  25082. });
  25083. // Methods
  25084. Mesh.prototype._preActivate = function () {
  25085. var sceneRenderId = this.getScene().getRenderId();
  25086. if (this._preActivateId === sceneRenderId) {
  25087. return this;
  25088. }
  25089. this._preActivateId = sceneRenderId;
  25090. this._visibleInstances = null;
  25091. return this;
  25092. };
  25093. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25094. if (this._visibleInstances) {
  25095. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25096. }
  25097. return this;
  25098. };
  25099. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25100. if (!this._visibleInstances) {
  25101. this._visibleInstances = {};
  25102. this._visibleInstances.defaultRenderId = renderId;
  25103. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25104. }
  25105. if (!this._visibleInstances[renderId]) {
  25106. this._visibleInstances[renderId] = new Array();
  25107. }
  25108. this._visibleInstances[renderId].push(instance);
  25109. return this;
  25110. };
  25111. /**
  25112. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25113. * This means the mesh underlying bounding box and sphere are recomputed.
  25114. * Returns the Mesh.
  25115. */
  25116. Mesh.prototype.refreshBoundingInfo = function () {
  25117. return this._refreshBoundingInfo(false);
  25118. };
  25119. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25120. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25121. return this;
  25122. }
  25123. var data = this._getPositionData(applySkeleton);
  25124. if (data) {
  25125. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25126. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25127. }
  25128. if (this.subMeshes) {
  25129. for (var index = 0; index < this.subMeshes.length; index++) {
  25130. this.subMeshes[index].refreshBoundingInfo();
  25131. }
  25132. }
  25133. this._updateBoundingInfo();
  25134. return this;
  25135. };
  25136. Mesh.prototype._getPositionData = function (applySkeleton) {
  25137. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25138. if (data && applySkeleton && this.skeleton) {
  25139. data = data.slice();
  25140. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25141. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25142. if (matricesWeightsData && matricesIndicesData) {
  25143. var needExtras = this.numBoneInfluencers > 4;
  25144. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25145. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25146. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25147. var tempVector = BABYLON.Tmp.Vector3[0];
  25148. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25149. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25150. var matWeightIdx = 0;
  25151. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25152. finalMatrix.reset();
  25153. var inf;
  25154. var weight;
  25155. for (inf = 0; inf < 4; inf++) {
  25156. weight = matricesWeightsData[matWeightIdx + inf];
  25157. if (weight <= 0)
  25158. break;
  25159. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25160. finalMatrix.addToSelf(tempMatrix);
  25161. }
  25162. if (needExtras) {
  25163. for (inf = 0; inf < 4; inf++) {
  25164. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25165. if (weight <= 0)
  25166. break;
  25167. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25168. finalMatrix.addToSelf(tempMatrix);
  25169. }
  25170. }
  25171. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25172. tempVector.toArray(data, index);
  25173. }
  25174. }
  25175. }
  25176. return data;
  25177. };
  25178. Mesh.prototype._createGlobalSubMesh = function (force) {
  25179. var totalVertices = this.getTotalVertices();
  25180. if (!totalVertices || !this.getIndices()) {
  25181. return null;
  25182. }
  25183. // Check if we need to recreate the submeshes
  25184. if (this.subMeshes && this.subMeshes.length > 0) {
  25185. var ib = this.getIndices();
  25186. if (!ib) {
  25187. return null;
  25188. }
  25189. var totalIndices = ib.length;
  25190. var needToRecreate = false;
  25191. if (force) {
  25192. needToRecreate = true;
  25193. }
  25194. else {
  25195. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25196. var submesh = _a[_i];
  25197. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25198. needToRecreate = true;
  25199. break;
  25200. }
  25201. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25202. needToRecreate = true;
  25203. break;
  25204. }
  25205. }
  25206. }
  25207. if (!needToRecreate) {
  25208. return this.subMeshes[0];
  25209. }
  25210. }
  25211. this.releaseSubMeshes();
  25212. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25213. };
  25214. Mesh.prototype.subdivide = function (count) {
  25215. if (count < 1) {
  25216. return;
  25217. }
  25218. var totalIndices = this.getTotalIndices();
  25219. var subdivisionSize = (totalIndices / count) | 0;
  25220. var offset = 0;
  25221. // Ensure that subdivisionSize is a multiple of 3
  25222. while (subdivisionSize % 3 !== 0) {
  25223. subdivisionSize++;
  25224. }
  25225. this.releaseSubMeshes();
  25226. for (var index = 0; index < count; index++) {
  25227. if (offset >= totalIndices) {
  25228. break;
  25229. }
  25230. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25231. offset += subdivisionSize;
  25232. }
  25233. this.synchronizeInstances();
  25234. };
  25235. /**
  25236. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25237. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25238. * The `data` are either a numeric array either a Float32Array.
  25239. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25240. * 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).
  25241. * Note that a new underlying VertexBuffer object is created each call.
  25242. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25243. *
  25244. * Possible `kind` values :
  25245. * - BABYLON.VertexBuffer.PositionKind
  25246. * - BABYLON.VertexBuffer.UVKind
  25247. * - BABYLON.VertexBuffer.UV2Kind
  25248. * - BABYLON.VertexBuffer.UV3Kind
  25249. * - BABYLON.VertexBuffer.UV4Kind
  25250. * - BABYLON.VertexBuffer.UV5Kind
  25251. * - BABYLON.VertexBuffer.UV6Kind
  25252. * - BABYLON.VertexBuffer.ColorKind
  25253. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25254. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25255. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25256. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25257. *
  25258. * Returns the Mesh.
  25259. */
  25260. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25261. if (updatable === void 0) { updatable = false; }
  25262. if (!this._geometry) {
  25263. var vertexData = new BABYLON.VertexData();
  25264. vertexData.set(data, kind);
  25265. var scene = this.getScene();
  25266. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25267. }
  25268. else {
  25269. this._geometry.setVerticesData(kind, data, updatable, stride);
  25270. }
  25271. return this;
  25272. };
  25273. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25274. if (updatable === void 0) { updatable = true; }
  25275. var vb = this.getVertexBuffer(kind);
  25276. if (!vb || vb.isUpdatable() === updatable) {
  25277. return;
  25278. }
  25279. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25280. };
  25281. /**
  25282. * Sets the mesh VertexBuffer.
  25283. * Returns the Mesh.
  25284. */
  25285. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25286. if (!this._geometry) {
  25287. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25288. }
  25289. this._geometry.setVerticesBuffer(buffer);
  25290. return this;
  25291. };
  25292. /**
  25293. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25294. * If the mesh has no geometry, it is simply returned as it is.
  25295. * The `data` are either a numeric array either a Float32Array.
  25296. * No new underlying VertexBuffer object is created.
  25297. * 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.
  25298. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25299. *
  25300. * Possible `kind` values :
  25301. * - BABYLON.VertexBuffer.PositionKind
  25302. * - BABYLON.VertexBuffer.UVKind
  25303. * - BABYLON.VertexBuffer.UV2Kind
  25304. * - BABYLON.VertexBuffer.UV3Kind
  25305. * - BABYLON.VertexBuffer.UV4Kind
  25306. * - BABYLON.VertexBuffer.UV5Kind
  25307. * - BABYLON.VertexBuffer.UV6Kind
  25308. * - BABYLON.VertexBuffer.ColorKind
  25309. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25310. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25311. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25312. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25313. *
  25314. * Returns the Mesh.
  25315. */
  25316. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25317. if (!this._geometry) {
  25318. return this;
  25319. }
  25320. if (!makeItUnique) {
  25321. this._geometry.updateVerticesData(kind, data, updateExtends);
  25322. }
  25323. else {
  25324. this.makeGeometryUnique();
  25325. this.updateVerticesData(kind, data, updateExtends, false);
  25326. }
  25327. return this;
  25328. };
  25329. /**
  25330. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25331. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25332. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25333. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25334. * Returns the Mesh.
  25335. */
  25336. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25337. if (computeNormals === void 0) { computeNormals = true; }
  25338. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25339. if (!positions) {
  25340. return this;
  25341. }
  25342. positionFunction(positions);
  25343. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25344. if (computeNormals) {
  25345. var indices = this.getIndices();
  25346. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25347. if (!normals) {
  25348. return this;
  25349. }
  25350. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25351. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25352. }
  25353. return this;
  25354. };
  25355. /**
  25356. * Creates a un-shared specific occurence of the geometry for the mesh.
  25357. * Returns the Mesh.
  25358. */
  25359. Mesh.prototype.makeGeometryUnique = function () {
  25360. if (!this._geometry) {
  25361. return this;
  25362. }
  25363. var oldGeometry = this._geometry;
  25364. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25365. oldGeometry.releaseForMesh(this, true);
  25366. geometry.applyToMesh(this);
  25367. return this;
  25368. };
  25369. /**
  25370. * Sets the mesh indices.
  25371. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25372. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25373. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25374. * This method creates a new index buffer each call.
  25375. * Returns the Mesh.
  25376. */
  25377. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25378. if (totalVertices === void 0) { totalVertices = null; }
  25379. if (updatable === void 0) { updatable = false; }
  25380. if (!this._geometry) {
  25381. var vertexData = new BABYLON.VertexData();
  25382. vertexData.indices = indices;
  25383. var scene = this.getScene();
  25384. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25385. }
  25386. else {
  25387. this._geometry.setIndices(indices, totalVertices, updatable);
  25388. }
  25389. return this;
  25390. };
  25391. /**
  25392. * Update the current index buffer
  25393. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25394. * Returns the Mesh.
  25395. */
  25396. Mesh.prototype.updateIndices = function (indices, offset) {
  25397. if (!this._geometry) {
  25398. return this;
  25399. }
  25400. this._geometry.updateIndices(indices, offset);
  25401. return this;
  25402. };
  25403. /**
  25404. * Invert the geometry to move from a right handed system to a left handed one.
  25405. * Returns the Mesh.
  25406. */
  25407. Mesh.prototype.toLeftHanded = function () {
  25408. if (!this._geometry) {
  25409. return this;
  25410. }
  25411. this._geometry.toLeftHanded();
  25412. return this;
  25413. };
  25414. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25415. if (!this._geometry) {
  25416. return this;
  25417. }
  25418. var engine = this.getScene().getEngine();
  25419. // Wireframe
  25420. var indexToBind;
  25421. if (this._unIndexed) {
  25422. indexToBind = null;
  25423. }
  25424. else {
  25425. switch (fillMode) {
  25426. case BABYLON.Material.PointFillMode:
  25427. indexToBind = null;
  25428. break;
  25429. case BABYLON.Material.WireFrameFillMode:
  25430. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25431. break;
  25432. default:
  25433. case BABYLON.Material.TriangleFillMode:
  25434. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25435. break;
  25436. }
  25437. }
  25438. // VBOs
  25439. this._geometry._bind(effect, indexToBind);
  25440. return this;
  25441. };
  25442. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25443. if (alternate === void 0) { alternate = false; }
  25444. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25445. return this;
  25446. }
  25447. this.onBeforeDrawObservable.notifyObservers(this);
  25448. var scene = this.getScene();
  25449. var engine = scene.getEngine();
  25450. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25451. // or triangles as points
  25452. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25453. }
  25454. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25455. // Triangles as wireframe
  25456. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25457. }
  25458. else {
  25459. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25460. }
  25461. if (scene._isAlternateRenderingEnabled && !alternate) {
  25462. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25463. if (!effect || !scene.activeCamera) {
  25464. return this;
  25465. }
  25466. scene._switchToAlternateCameraConfiguration(true);
  25467. this._effectiveMaterial.bindView(effect);
  25468. this._effectiveMaterial.bindViewProjection(effect);
  25469. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25470. this._draw(subMesh, fillMode, instancesCount, true);
  25471. engine.setViewport(scene.activeCamera.viewport);
  25472. scene._switchToAlternateCameraConfiguration(false);
  25473. this._effectiveMaterial.bindView(effect);
  25474. this._effectiveMaterial.bindViewProjection(effect);
  25475. }
  25476. return this;
  25477. };
  25478. /**
  25479. * Registers for this mesh a javascript function called just before the rendering process.
  25480. * This function is passed the current mesh.
  25481. * Return the Mesh.
  25482. */
  25483. Mesh.prototype.registerBeforeRender = function (func) {
  25484. this.onBeforeRenderObservable.add(func);
  25485. return this;
  25486. };
  25487. /**
  25488. * Disposes a previously registered javascript function called before the rendering.
  25489. * This function is passed the current mesh.
  25490. * Returns the Mesh.
  25491. */
  25492. Mesh.prototype.unregisterBeforeRender = function (func) {
  25493. this.onBeforeRenderObservable.removeCallback(func);
  25494. return this;
  25495. };
  25496. /**
  25497. * Registers for this mesh a javascript function called just after the rendering is complete.
  25498. * This function is passed the current mesh.
  25499. * Returns the Mesh.
  25500. */
  25501. Mesh.prototype.registerAfterRender = function (func) {
  25502. this.onAfterRenderObservable.add(func);
  25503. return this;
  25504. };
  25505. /**
  25506. * Disposes a previously registered javascript function called after the rendering.
  25507. * This function is passed the current mesh.
  25508. * Return the Mesh.
  25509. */
  25510. Mesh.prototype.unregisterAfterRender = function (func) {
  25511. this.onAfterRenderObservable.removeCallback(func);
  25512. return this;
  25513. };
  25514. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25515. var scene = this.getScene();
  25516. this._batchCache.mustReturn = false;
  25517. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25518. this._batchCache.visibleInstances[subMeshId] = null;
  25519. if (this._visibleInstances) {
  25520. var currentRenderId = scene.getRenderId();
  25521. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25522. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25523. var selfRenderId = this._renderId;
  25524. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25525. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25526. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25527. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25528. }
  25529. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25530. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25531. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25532. this._batchCache.mustReturn = true;
  25533. return this._batchCache;
  25534. }
  25535. if (currentRenderId !== selfRenderId) {
  25536. this._batchCache.renderSelf[subMeshId] = false;
  25537. }
  25538. }
  25539. this._renderIdForInstances[subMeshId] = currentRenderId;
  25540. }
  25541. return this._batchCache;
  25542. };
  25543. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25544. var visibleInstances = batch.visibleInstances[subMesh._id];
  25545. if (!visibleInstances) {
  25546. return this;
  25547. }
  25548. var matricesCount = visibleInstances.length + 1;
  25549. var bufferSize = matricesCount * 16 * 4;
  25550. var currentInstancesBufferSize = this._instancesBufferSize;
  25551. var instancesBuffer = this._instancesBuffer;
  25552. while (this._instancesBufferSize < bufferSize) {
  25553. this._instancesBufferSize *= 2;
  25554. }
  25555. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25556. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25557. }
  25558. var offset = 0;
  25559. var instancesCount = 0;
  25560. var world = this.getWorldMatrix();
  25561. if (batch.renderSelf[subMesh._id]) {
  25562. world.copyToArray(this._instancesData, offset);
  25563. offset += 16;
  25564. instancesCount++;
  25565. }
  25566. if (visibleInstances) {
  25567. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25568. var instance = visibleInstances[instanceIndex];
  25569. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25570. offset += 16;
  25571. instancesCount++;
  25572. }
  25573. }
  25574. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25575. if (instancesBuffer) {
  25576. instancesBuffer.dispose();
  25577. }
  25578. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25579. this._instancesBuffer = instancesBuffer;
  25580. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25581. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25582. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25583. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25584. }
  25585. else {
  25586. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25587. }
  25588. this._bind(subMesh, effect, fillMode);
  25589. this._draw(subMesh, fillMode, instancesCount);
  25590. engine.unbindInstanceAttributes();
  25591. return this;
  25592. };
  25593. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25594. var scene = this.getScene();
  25595. var engine = scene.getEngine();
  25596. if (hardwareInstancedRendering) {
  25597. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25598. }
  25599. else {
  25600. if (batch.renderSelf[subMesh._id]) {
  25601. // Draw
  25602. if (onBeforeDraw) {
  25603. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25604. }
  25605. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25606. }
  25607. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25608. if (visibleInstancesForSubMesh) {
  25609. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25610. var instance = visibleInstancesForSubMesh[instanceIndex];
  25611. // World
  25612. var world = instance.getWorldMatrix();
  25613. if (onBeforeDraw) {
  25614. onBeforeDraw(true, world, effectiveMaterial);
  25615. }
  25616. // Draw
  25617. this._draw(subMesh, fillMode);
  25618. }
  25619. }
  25620. }
  25621. return this;
  25622. };
  25623. /**
  25624. * Triggers the draw call for the mesh.
  25625. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25626. * Returns the Mesh.
  25627. */
  25628. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25629. this.checkOcclusionQuery();
  25630. if (this._isOccluded) {
  25631. return this;
  25632. }
  25633. var scene = this.getScene();
  25634. // Managing instances
  25635. var batch = this._getInstancesRenderList(subMesh._id);
  25636. if (batch.mustReturn) {
  25637. return this;
  25638. }
  25639. // Checking geometry state
  25640. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25641. return this;
  25642. }
  25643. this.onBeforeRenderObservable.notifyObservers(this);
  25644. var engine = scene.getEngine();
  25645. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25646. // Material
  25647. var material = subMesh.getMaterial();
  25648. if (!material) {
  25649. return this;
  25650. }
  25651. this._effectiveMaterial = material;
  25652. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25653. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25654. return this;
  25655. }
  25656. }
  25657. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25658. return this;
  25659. }
  25660. // Alpha mode
  25661. if (enableAlphaMode) {
  25662. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25663. }
  25664. // Outline - step 1
  25665. var savedDepthWrite = engine.getDepthWrite();
  25666. if (this.renderOutline) {
  25667. engine.setDepthWrite(false);
  25668. scene.getOutlineRenderer().render(subMesh, batch);
  25669. engine.setDepthWrite(savedDepthWrite);
  25670. }
  25671. var effect;
  25672. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25673. effect = subMesh.effect;
  25674. }
  25675. else {
  25676. effect = this._effectiveMaterial.getEffect();
  25677. }
  25678. if (!effect) {
  25679. return this;
  25680. }
  25681. var sideOrientation = this.overrideMaterialSideOrientation;
  25682. if (sideOrientation == null) {
  25683. sideOrientation = this._effectiveMaterial.sideOrientation;
  25684. if (this._getWorldMatrixDeterminant() < 0) {
  25685. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25686. }
  25687. }
  25688. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25689. if (this._effectiveMaterial.forceDepthWrite) {
  25690. engine.setDepthWrite(true);
  25691. }
  25692. // Bind
  25693. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25694. if (!hardwareInstancedRendering) {
  25695. this._bind(subMesh, effect, fillMode);
  25696. }
  25697. var world = this.getWorldMatrix();
  25698. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25699. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25700. }
  25701. else {
  25702. this._effectiveMaterial.bind(world, this);
  25703. }
  25704. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25705. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25706. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25707. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25708. }
  25709. // Draw
  25710. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25711. // Unbind
  25712. this._effectiveMaterial.unbind();
  25713. // Outline - step 2
  25714. if (this.renderOutline && savedDepthWrite) {
  25715. engine.setDepthWrite(true);
  25716. engine.setColorWrite(false);
  25717. scene.getOutlineRenderer().render(subMesh, batch);
  25718. engine.setColorWrite(true);
  25719. }
  25720. // Overlay
  25721. if (this.renderOverlay) {
  25722. var currentMode = engine.getAlphaMode();
  25723. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25724. scene.getOutlineRenderer().render(subMesh, batch, true);
  25725. engine.setAlphaMode(currentMode);
  25726. }
  25727. this.onAfterRenderObservable.notifyObservers(this);
  25728. return this;
  25729. };
  25730. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  25731. if (isInstance && effectiveMaterial) {
  25732. effectiveMaterial.bindOnlyWorldMatrix(world);
  25733. }
  25734. };
  25735. /**
  25736. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  25737. */
  25738. Mesh.prototype.getEmittedParticleSystems = function () {
  25739. var results = new Array();
  25740. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25741. var particleSystem = this.getScene().particleSystems[index];
  25742. if (particleSystem.emitter === this) {
  25743. results.push(particleSystem);
  25744. }
  25745. }
  25746. return results;
  25747. };
  25748. /**
  25749. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  25750. */
  25751. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  25752. var results = new Array();
  25753. var descendants = this.getDescendants();
  25754. descendants.push(this);
  25755. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  25756. var particleSystem = this.getScene().particleSystems[index];
  25757. var emitter = particleSystem.emitter;
  25758. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  25759. results.push(particleSystem);
  25760. }
  25761. }
  25762. return results;
  25763. };
  25764. Mesh.prototype._checkDelayState = function () {
  25765. var scene = this.getScene();
  25766. if (this._geometry) {
  25767. this._geometry.load(scene);
  25768. }
  25769. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25771. this._queueLoad(scene);
  25772. }
  25773. return this;
  25774. };
  25775. Mesh.prototype._queueLoad = function (scene) {
  25776. var _this = this;
  25777. scene._addPendingData(this);
  25778. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  25779. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25780. if (data instanceof ArrayBuffer) {
  25781. _this._delayLoadingFunction(data, _this);
  25782. }
  25783. else {
  25784. _this._delayLoadingFunction(JSON.parse(data), _this);
  25785. }
  25786. _this.instances.forEach(function (instance) {
  25787. instance._syncSubMeshes();
  25788. });
  25789. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25790. scene._removePendingData(_this);
  25791. }, function () { }, scene.database, getBinaryData);
  25792. return this;
  25793. };
  25794. /**
  25795. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  25796. */
  25797. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  25798. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25799. return false;
  25800. }
  25801. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  25802. return false;
  25803. }
  25804. this._checkDelayState();
  25805. return true;
  25806. };
  25807. /**
  25808. * Sets the mesh material by the material or multiMaterial `id` property.
  25809. * The material `id` is a string identifying the material or the multiMaterial.
  25810. * This method returns the Mesh.
  25811. */
  25812. Mesh.prototype.setMaterialByID = function (id) {
  25813. var materials = this.getScene().materials;
  25814. var index;
  25815. for (index = materials.length - 1; index > -1; index--) {
  25816. if (materials[index].id === id) {
  25817. this.material = materials[index];
  25818. return this;
  25819. }
  25820. }
  25821. // Multi
  25822. var multiMaterials = this.getScene().multiMaterials;
  25823. for (index = multiMaterials.length - 1; index > -1; index--) {
  25824. if (multiMaterials[index].id === id) {
  25825. this.material = multiMaterials[index];
  25826. return this;
  25827. }
  25828. }
  25829. return this;
  25830. };
  25831. /**
  25832. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  25833. */
  25834. Mesh.prototype.getAnimatables = function () {
  25835. var results = new Array();
  25836. if (this.material) {
  25837. results.push(this.material);
  25838. }
  25839. if (this.skeleton) {
  25840. results.push(this.skeleton);
  25841. }
  25842. return results;
  25843. };
  25844. /**
  25845. * Modifies the mesh geometry according to the passed transformation matrix.
  25846. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  25847. * The mesh normals are modified accordingly the same transformation.
  25848. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  25849. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25850. * Returns the Mesh.
  25851. */
  25852. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  25853. // Position
  25854. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25855. return this;
  25856. }
  25857. var submeshes = this.subMeshes.splice(0);
  25858. this._resetPointsArrayCache();
  25859. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25860. var temp = new Array();
  25861. var index;
  25862. for (index = 0; index < data.length; index += 3) {
  25863. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  25864. }
  25865. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  25866. // Normals
  25867. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25868. return this;
  25869. }
  25870. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25871. temp = [];
  25872. for (index = 0; index < data.length; index += 3) {
  25873. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  25874. }
  25875. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  25876. // flip faces?
  25877. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  25878. this.flipFaces();
  25879. }
  25880. // Restore submeshes
  25881. this.releaseSubMeshes();
  25882. this.subMeshes = submeshes;
  25883. return this;
  25884. };
  25885. /**
  25886. * Modifies the mesh geometry according to its own current World Matrix.
  25887. * The mesh World Matrix is then reset.
  25888. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  25889. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  25890. * Note that, under the hood, this method sets a new VertexBuffer each call.
  25891. * Returns the Mesh.
  25892. */
  25893. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  25894. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  25895. this.scaling.copyFromFloats(1, 1, 1);
  25896. this.position.copyFromFloats(0, 0, 0);
  25897. this.rotation.copyFromFloats(0, 0, 0);
  25898. //only if quaternion is already set
  25899. if (this.rotationQuaternion) {
  25900. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  25901. }
  25902. this._worldMatrix = BABYLON.Matrix.Identity();
  25903. return this;
  25904. };
  25905. Object.defineProperty(Mesh.prototype, "_positions", {
  25906. // Cache
  25907. get: function () {
  25908. if (this._geometry) {
  25909. return this._geometry._positions;
  25910. }
  25911. return null;
  25912. },
  25913. enumerable: true,
  25914. configurable: true
  25915. });
  25916. Mesh.prototype._resetPointsArrayCache = function () {
  25917. if (this._geometry) {
  25918. this._geometry._resetPointsArrayCache();
  25919. }
  25920. return this;
  25921. };
  25922. Mesh.prototype._generatePointsArray = function () {
  25923. if (this._geometry) {
  25924. return this._geometry._generatePointsArray();
  25925. }
  25926. return false;
  25927. };
  25928. /**
  25929. * Returns a new Mesh object generated from the current mesh properties.
  25930. * This method must not get confused with createInstance().
  25931. * The parameter `name` is a string, the name given to the new mesh.
  25932. * The optional parameter `newParent` can be any Node object (default `null`).
  25933. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  25934. * 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.
  25935. */
  25936. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  25937. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25938. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  25939. };
  25940. /**
  25941. * Disposes the Mesh.
  25942. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  25943. * Returns nothing.
  25944. */
  25945. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  25946. var _this = this;
  25947. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  25948. this.morphTargetManager = null;
  25949. if (this._geometry) {
  25950. this._geometry.releaseForMesh(this, true);
  25951. }
  25952. // Sources
  25953. var meshes = this.getScene().meshes;
  25954. meshes.forEach(function (abstractMesh) {
  25955. var mesh = abstractMesh;
  25956. if (mesh._source && mesh._source === _this) {
  25957. mesh._source = null;
  25958. }
  25959. });
  25960. this._source = null;
  25961. // Instances
  25962. if (this._instancesBuffer) {
  25963. this._instancesBuffer.dispose();
  25964. this._instancesBuffer = null;
  25965. }
  25966. while (this.instances.length) {
  25967. this.instances[0].dispose();
  25968. }
  25969. // Highlight layers.
  25970. var highlightLayers = this.getScene().highlightLayers;
  25971. for (var i = 0; i < highlightLayers.length; i++) {
  25972. var highlightLayer = highlightLayers[i];
  25973. if (highlightLayer) {
  25974. highlightLayer.removeMesh(this);
  25975. highlightLayer.removeExcludedMesh(this);
  25976. }
  25977. }
  25978. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25979. };
  25980. /**
  25981. * Modifies the mesh geometry according to a displacement map.
  25982. * 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.
  25983. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25984. * This method returns nothing.
  25985. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25986. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25987. * 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.
  25988. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25989. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25990. *
  25991. * Returns the Mesh.
  25992. */
  25993. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25994. var _this = this;
  25995. var scene = this.getScene();
  25996. var onload = function (img) {
  25997. // Getting height map data
  25998. var canvas = document.createElement("canvas");
  25999. var context = canvas.getContext("2d");
  26000. var heightMapWidth = img.width;
  26001. var heightMapHeight = img.height;
  26002. canvas.width = heightMapWidth;
  26003. canvas.height = heightMapHeight;
  26004. context.drawImage(img, 0, 0);
  26005. // Create VertexData from map data
  26006. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26007. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26008. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26009. //execute success callback, if set
  26010. if (onSuccess) {
  26011. onSuccess(_this);
  26012. }
  26013. };
  26014. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26015. return this;
  26016. };
  26017. /**
  26018. * Modifies the mesh geometry according to a displacementMap buffer.
  26019. * 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.
  26020. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26021. * This method returns nothing.
  26022. * 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.
  26023. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26024. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26025. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26026. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26027. *
  26028. * Returns the Mesh.
  26029. */
  26030. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26031. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26032. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26033. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26034. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26035. return this;
  26036. }
  26037. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26038. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26039. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26040. var position = BABYLON.Vector3.Zero();
  26041. var normal = BABYLON.Vector3.Zero();
  26042. var uv = BABYLON.Vector2.Zero();
  26043. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26044. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26045. for (var index = 0; index < positions.length; index += 3) {
  26046. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26047. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26048. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26049. // Compute height
  26050. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26051. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26052. var pos = (u + v * heightMapWidth) * 4;
  26053. var r = buffer[pos] / 255.0;
  26054. var g = buffer[pos + 1] / 255.0;
  26055. var b = buffer[pos + 2] / 255.0;
  26056. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26057. normal.normalize();
  26058. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26059. position = position.add(normal);
  26060. position.toArray(positions, index);
  26061. }
  26062. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26063. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26064. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26065. return this;
  26066. };
  26067. /**
  26068. * Modify the mesh to get a flat shading rendering.
  26069. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26070. * This method returns the Mesh.
  26071. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26072. */
  26073. Mesh.prototype.convertToFlatShadedMesh = function () {
  26074. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26075. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26076. var kinds = this.getVerticesDataKinds();
  26077. var vbs = {};
  26078. var data = {};
  26079. var newdata = {};
  26080. var updatableNormals = false;
  26081. var kindIndex;
  26082. var kind;
  26083. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26084. kind = kinds[kindIndex];
  26085. var vertexBuffer = this.getVertexBuffer(kind);
  26086. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26087. updatableNormals = vertexBuffer.isUpdatable();
  26088. kinds.splice(kindIndex, 1);
  26089. kindIndex--;
  26090. continue;
  26091. }
  26092. vbs[kind] = vertexBuffer;
  26093. data[kind] = vbs[kind].getData();
  26094. newdata[kind] = [];
  26095. }
  26096. // Save previous submeshes
  26097. var previousSubmeshes = this.subMeshes.slice(0);
  26098. var indices = this.getIndices();
  26099. var totalIndices = this.getTotalIndices();
  26100. // Generating unique vertices per face
  26101. var index;
  26102. for (index = 0; index < totalIndices; index++) {
  26103. var vertexIndex = indices[index];
  26104. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26105. kind = kinds[kindIndex];
  26106. var stride = vbs[kind].getStrideSize();
  26107. for (var offset = 0; offset < stride; offset++) {
  26108. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26109. }
  26110. }
  26111. }
  26112. // Updating faces & normal
  26113. var normals = [];
  26114. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26115. for (index = 0; index < totalIndices; index += 3) {
  26116. indices[index] = index;
  26117. indices[index + 1] = index + 1;
  26118. indices[index + 2] = index + 2;
  26119. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26120. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26121. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26122. var p1p2 = p1.subtract(p2);
  26123. var p3p2 = p3.subtract(p2);
  26124. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26125. // Store same normals for every vertex
  26126. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26127. normals.push(normal.x);
  26128. normals.push(normal.y);
  26129. normals.push(normal.z);
  26130. }
  26131. }
  26132. this.setIndices(indices);
  26133. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26134. // Updating vertex buffers
  26135. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26136. kind = kinds[kindIndex];
  26137. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26138. }
  26139. // Updating submeshes
  26140. this.releaseSubMeshes();
  26141. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26142. var previousOne = previousSubmeshes[submeshIndex];
  26143. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26144. }
  26145. this.synchronizeInstances();
  26146. return this;
  26147. };
  26148. /**
  26149. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26150. * In other words, more vertices, no more indices and a single bigger VBO.
  26151. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26152. * Returns the Mesh.
  26153. */
  26154. Mesh.prototype.convertToUnIndexedMesh = function () {
  26155. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26156. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26157. var kinds = this.getVerticesDataKinds();
  26158. var vbs = {};
  26159. var data = {};
  26160. var newdata = {};
  26161. var kindIndex;
  26162. var kind;
  26163. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26164. kind = kinds[kindIndex];
  26165. var vertexBuffer = this.getVertexBuffer(kind);
  26166. vbs[kind] = vertexBuffer;
  26167. data[kind] = vbs[kind].getData();
  26168. newdata[kind] = [];
  26169. }
  26170. // Save previous submeshes
  26171. var previousSubmeshes = this.subMeshes.slice(0);
  26172. var indices = this.getIndices();
  26173. var totalIndices = this.getTotalIndices();
  26174. // Generating unique vertices per face
  26175. var index;
  26176. for (index = 0; index < totalIndices; index++) {
  26177. var vertexIndex = indices[index];
  26178. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26179. kind = kinds[kindIndex];
  26180. var stride = vbs[kind].getStrideSize();
  26181. for (var offset = 0; offset < stride; offset++) {
  26182. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26183. }
  26184. }
  26185. }
  26186. // Updating indices
  26187. for (index = 0; index < totalIndices; index += 3) {
  26188. indices[index] = index;
  26189. indices[index + 1] = index + 1;
  26190. indices[index + 2] = index + 2;
  26191. }
  26192. this.setIndices(indices);
  26193. // Updating vertex buffers
  26194. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26195. kind = kinds[kindIndex];
  26196. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26197. }
  26198. // Updating submeshes
  26199. this.releaseSubMeshes();
  26200. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26201. var previousOne = previousSubmeshes[submeshIndex];
  26202. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26203. }
  26204. this._unIndexed = true;
  26205. this.synchronizeInstances();
  26206. return this;
  26207. };
  26208. /**
  26209. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26210. * This method returns the Mesh.
  26211. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26212. */
  26213. Mesh.prototype.flipFaces = function (flipNormals) {
  26214. if (flipNormals === void 0) { flipNormals = false; }
  26215. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26216. var i;
  26217. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26218. for (i = 0; i < vertex_data.normals.length; i++) {
  26219. vertex_data.normals[i] *= -1;
  26220. }
  26221. }
  26222. if (vertex_data.indices) {
  26223. var temp;
  26224. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26225. // reassign indices
  26226. temp = vertex_data.indices[i + 1];
  26227. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26228. vertex_data.indices[i + 2] = temp;
  26229. }
  26230. }
  26231. vertex_data.applyToMesh(this);
  26232. return this;
  26233. };
  26234. // Instances
  26235. /**
  26236. * Creates a new InstancedMesh object from the mesh model.
  26237. * An instance shares the same properties and the same material than its model.
  26238. * Only these properties of each instance can then be set individually :
  26239. * - position
  26240. * - rotation
  26241. * - rotationQuaternion
  26242. * - setPivotMatrix
  26243. * - scaling
  26244. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26245. * Warning : this method is not supported for Line mesh and LineSystem
  26246. */
  26247. Mesh.prototype.createInstance = function (name) {
  26248. return new BABYLON.InstancedMesh(name, this);
  26249. };
  26250. /**
  26251. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26252. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26253. * This method returns the Mesh.
  26254. */
  26255. Mesh.prototype.synchronizeInstances = function () {
  26256. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26257. var instance = this.instances[instanceIndex];
  26258. instance._syncSubMeshes();
  26259. }
  26260. return this;
  26261. };
  26262. /**
  26263. * Simplify the mesh according to the given array of settings.
  26264. * Function will return immediately and will simplify async. It returns the Mesh.
  26265. * @param settings a collection of simplification settings.
  26266. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26267. * @param type the type of simplification to run.
  26268. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26269. */
  26270. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26271. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26272. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26273. this.getScene().simplificationQueue.addTask({
  26274. settings: settings,
  26275. parallelProcessing: parallelProcessing,
  26276. mesh: this,
  26277. simplificationType: simplificationType,
  26278. successCallback: successCallback
  26279. });
  26280. return this;
  26281. };
  26282. /**
  26283. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26284. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26285. * This should be used together with the simplification to avoid disappearing triangles.
  26286. * Returns the Mesh.
  26287. * @param successCallback an optional success callback to be called after the optimization finished.
  26288. */
  26289. Mesh.prototype.optimizeIndices = function (successCallback) {
  26290. var _this = this;
  26291. var indices = this.getIndices();
  26292. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26293. if (!positions || !indices) {
  26294. return this;
  26295. }
  26296. var vectorPositions = new Array();
  26297. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26298. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26299. }
  26300. var dupes = new Array();
  26301. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26302. var realPos = vectorPositions.length - 1 - iteration;
  26303. var testedPosition = vectorPositions[realPos];
  26304. for (var j = 0; j < realPos; ++j) {
  26305. var againstPosition = vectorPositions[j];
  26306. if (testedPosition.equals(againstPosition)) {
  26307. dupes[realPos] = j;
  26308. break;
  26309. }
  26310. }
  26311. }, function () {
  26312. for (var i = 0; i < indices.length; ++i) {
  26313. indices[i] = dupes[indices[i]] || indices[i];
  26314. }
  26315. //indices are now reordered
  26316. var originalSubMeshes = _this.subMeshes.slice(0);
  26317. _this.setIndices(indices);
  26318. _this.subMeshes = originalSubMeshes;
  26319. if (successCallback) {
  26320. successCallback(_this);
  26321. }
  26322. });
  26323. return this;
  26324. };
  26325. Mesh.prototype.serialize = function (serializationObject) {
  26326. serializationObject.name = this.name;
  26327. serializationObject.id = this.id;
  26328. serializationObject.type = this.getClassName();
  26329. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26330. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26331. }
  26332. serializationObject.position = this.position.asArray();
  26333. if (this.rotationQuaternion) {
  26334. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26335. }
  26336. else if (this.rotation) {
  26337. serializationObject.rotation = this.rotation.asArray();
  26338. }
  26339. serializationObject.scaling = this.scaling.asArray();
  26340. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26341. serializationObject.isEnabled = this.isEnabled(false);
  26342. serializationObject.isVisible = this.isVisible;
  26343. serializationObject.infiniteDistance = this.infiniteDistance;
  26344. serializationObject.pickable = this.isPickable;
  26345. serializationObject.receiveShadows = this.receiveShadows;
  26346. serializationObject.billboardMode = this.billboardMode;
  26347. serializationObject.visibility = this.visibility;
  26348. serializationObject.checkCollisions = this.checkCollisions;
  26349. serializationObject.isBlocker = this.isBlocker;
  26350. // Parent
  26351. if (this.parent) {
  26352. serializationObject.parentId = this.parent.id;
  26353. }
  26354. // Geometry
  26355. serializationObject.isUnIndexed = this.isUnIndexed;
  26356. var geometry = this._geometry;
  26357. if (geometry) {
  26358. var geometryId = geometry.id;
  26359. serializationObject.geometryId = geometryId;
  26360. // SubMeshes
  26361. serializationObject.subMeshes = [];
  26362. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26363. var subMesh = this.subMeshes[subIndex];
  26364. serializationObject.subMeshes.push({
  26365. materialIndex: subMesh.materialIndex,
  26366. verticesStart: subMesh.verticesStart,
  26367. verticesCount: subMesh.verticesCount,
  26368. indexStart: subMesh.indexStart,
  26369. indexCount: subMesh.indexCount
  26370. });
  26371. }
  26372. }
  26373. // Material
  26374. if (this.material) {
  26375. serializationObject.materialId = this.material.id;
  26376. }
  26377. else {
  26378. this.material = null;
  26379. }
  26380. // Morph targets
  26381. if (this.morphTargetManager) {
  26382. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26383. }
  26384. // Skeleton
  26385. if (this.skeleton) {
  26386. serializationObject.skeletonId = this.skeleton.id;
  26387. }
  26388. // Physics
  26389. //TODO implement correct serialization for physics impostors.
  26390. var impostor = this.getPhysicsImpostor();
  26391. if (impostor) {
  26392. serializationObject.physicsMass = impostor.getParam("mass");
  26393. serializationObject.physicsFriction = impostor.getParam("friction");
  26394. serializationObject.physicsRestitution = impostor.getParam("mass");
  26395. serializationObject.physicsImpostor = impostor.type;
  26396. }
  26397. // Metadata
  26398. if (this.metadata) {
  26399. serializationObject.metadata = this.metadata;
  26400. }
  26401. // Instances
  26402. serializationObject.instances = [];
  26403. for (var index = 0; index < this.instances.length; index++) {
  26404. var instance = this.instances[index];
  26405. var serializationInstance = {
  26406. name: instance.name,
  26407. id: instance.id,
  26408. position: instance.position.asArray(),
  26409. scaling: instance.scaling.asArray()
  26410. };
  26411. if (instance.rotationQuaternion) {
  26412. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26413. }
  26414. else if (instance.rotation) {
  26415. serializationInstance.rotation = instance.rotation.asArray();
  26416. }
  26417. serializationObject.instances.push(serializationInstance);
  26418. // Animations
  26419. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26420. serializationInstance.ranges = instance.serializeAnimationRanges();
  26421. }
  26422. //
  26423. // Animations
  26424. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26425. serializationObject.ranges = this.serializeAnimationRanges();
  26426. // Layer mask
  26427. serializationObject.layerMask = this.layerMask;
  26428. // Alpha
  26429. serializationObject.alphaIndex = this.alphaIndex;
  26430. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26431. // Overlay
  26432. serializationObject.overlayAlpha = this.overlayAlpha;
  26433. serializationObject.overlayColor = this.overlayColor.asArray();
  26434. serializationObject.renderOverlay = this.renderOverlay;
  26435. // Fog
  26436. serializationObject.applyFog = this.applyFog;
  26437. // Action Manager
  26438. if (this.actionManager) {
  26439. serializationObject.actions = this.actionManager.serialize(this.name);
  26440. }
  26441. };
  26442. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26443. if (!this.geometry) {
  26444. return;
  26445. }
  26446. this._markSubMeshesAsAttributesDirty();
  26447. var morphTargetManager = this._morphTargetManager;
  26448. if (morphTargetManager && morphTargetManager.vertexCount) {
  26449. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26450. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26451. this.morphTargetManager = null;
  26452. return;
  26453. }
  26454. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26455. var morphTarget = morphTargetManager.getActiveTarget(index);
  26456. var positions = morphTarget.getPositions();
  26457. if (!positions) {
  26458. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26459. return;
  26460. }
  26461. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26462. var normals = morphTarget.getNormals();
  26463. if (normals) {
  26464. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26465. }
  26466. var tangents = morphTarget.getTangents();
  26467. if (tangents) {
  26468. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26469. }
  26470. }
  26471. }
  26472. else {
  26473. var index = 0;
  26474. // Positions
  26475. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26476. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26477. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26478. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26479. }
  26480. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26481. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26482. }
  26483. index++;
  26484. }
  26485. }
  26486. };
  26487. // Statics
  26488. /**
  26489. * Returns a new Mesh object parsed from the source provided.
  26490. * The parameter `parsedMesh` is the source.
  26491. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26492. */
  26493. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26494. var mesh;
  26495. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26496. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26497. }
  26498. else {
  26499. mesh = new Mesh(parsedMesh.name, scene);
  26500. }
  26501. mesh.id = parsedMesh.id;
  26502. if (BABYLON.Tags) {
  26503. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26504. }
  26505. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26506. if (parsedMesh.metadata !== undefined) {
  26507. mesh.metadata = parsedMesh.metadata;
  26508. }
  26509. if (parsedMesh.rotationQuaternion) {
  26510. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26511. }
  26512. else if (parsedMesh.rotation) {
  26513. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26514. }
  26515. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26516. if (parsedMesh.localMatrix) {
  26517. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26518. }
  26519. else if (parsedMesh.pivotMatrix) {
  26520. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26521. }
  26522. mesh.setEnabled(parsedMesh.isEnabled);
  26523. mesh.isVisible = parsedMesh.isVisible;
  26524. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26525. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26526. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26527. if (parsedMesh.applyFog !== undefined) {
  26528. mesh.applyFog = parsedMesh.applyFog;
  26529. }
  26530. if (parsedMesh.pickable !== undefined) {
  26531. mesh.isPickable = parsedMesh.pickable;
  26532. }
  26533. if (parsedMesh.alphaIndex !== undefined) {
  26534. mesh.alphaIndex = parsedMesh.alphaIndex;
  26535. }
  26536. mesh.receiveShadows = parsedMesh.receiveShadows;
  26537. mesh.billboardMode = parsedMesh.billboardMode;
  26538. if (parsedMesh.visibility !== undefined) {
  26539. mesh.visibility = parsedMesh.visibility;
  26540. }
  26541. mesh.checkCollisions = parsedMesh.checkCollisions;
  26542. if (parsedMesh.isBlocker !== undefined) {
  26543. mesh.isBlocker = parsedMesh.isBlocker;
  26544. }
  26545. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26546. // freezeWorldMatrix
  26547. if (parsedMesh.freezeWorldMatrix) {
  26548. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26549. }
  26550. // Parent
  26551. if (parsedMesh.parentId) {
  26552. mesh._waitingParentId = parsedMesh.parentId;
  26553. }
  26554. // Actions
  26555. if (parsedMesh.actions !== undefined) {
  26556. mesh._waitingActions = parsedMesh.actions;
  26557. }
  26558. // Overlay
  26559. if (parsedMesh.overlayAlpha !== undefined) {
  26560. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26561. }
  26562. if (parsedMesh.overlayColor !== undefined) {
  26563. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26564. }
  26565. if (parsedMesh.renderOverlay !== undefined) {
  26566. mesh.renderOverlay = parsedMesh.renderOverlay;
  26567. }
  26568. // Geometry
  26569. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26570. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26571. if (parsedMesh.delayLoadingFile) {
  26572. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26573. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26574. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26575. if (parsedMesh._binaryInfo) {
  26576. mesh._binaryInfo = parsedMesh._binaryInfo;
  26577. }
  26578. mesh._delayInfo = [];
  26579. if (parsedMesh.hasUVs) {
  26580. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26581. }
  26582. if (parsedMesh.hasUVs2) {
  26583. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26584. }
  26585. if (parsedMesh.hasUVs3) {
  26586. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26587. }
  26588. if (parsedMesh.hasUVs4) {
  26589. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26590. }
  26591. if (parsedMesh.hasUVs5) {
  26592. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26593. }
  26594. if (parsedMesh.hasUVs6) {
  26595. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26596. }
  26597. if (parsedMesh.hasColors) {
  26598. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26599. }
  26600. if (parsedMesh.hasMatricesIndices) {
  26601. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26602. }
  26603. if (parsedMesh.hasMatricesWeights) {
  26604. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26605. }
  26606. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26607. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26608. mesh._checkDelayState();
  26609. }
  26610. }
  26611. else {
  26612. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26613. }
  26614. // Material
  26615. if (parsedMesh.materialId) {
  26616. mesh.setMaterialByID(parsedMesh.materialId);
  26617. }
  26618. else {
  26619. mesh.material = null;
  26620. }
  26621. // Morph targets
  26622. if (parsedMesh.morphTargetManagerId > -1) {
  26623. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26624. }
  26625. // Skeleton
  26626. if (parsedMesh.skeletonId > -1) {
  26627. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26628. if (parsedMesh.numBoneInfluencers) {
  26629. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26630. }
  26631. }
  26632. // Animations
  26633. if (parsedMesh.animations) {
  26634. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26635. var parsedAnimation = parsedMesh.animations[animationIndex];
  26636. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26637. }
  26638. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26639. }
  26640. if (parsedMesh.autoAnimate) {
  26641. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26642. }
  26643. // Layer Mask
  26644. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26645. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26646. }
  26647. else {
  26648. mesh.layerMask = 0x0FFFFFFF;
  26649. }
  26650. // Physics
  26651. if (parsedMesh.physicsImpostor) {
  26652. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26653. mass: parsedMesh.physicsMass,
  26654. friction: parsedMesh.physicsFriction,
  26655. restitution: parsedMesh.physicsRestitution
  26656. }, scene);
  26657. }
  26658. // Instances
  26659. if (parsedMesh.instances) {
  26660. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26661. var parsedInstance = parsedMesh.instances[index];
  26662. var instance = mesh.createInstance(parsedInstance.name);
  26663. if (parsedInstance.id) {
  26664. instance.id = parsedInstance.id;
  26665. }
  26666. if (BABYLON.Tags) {
  26667. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26668. }
  26669. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26670. if (parsedInstance.parentId) {
  26671. instance._waitingParentId = parsedInstance.parentId;
  26672. }
  26673. if (parsedInstance.rotationQuaternion) {
  26674. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26675. }
  26676. else if (parsedInstance.rotation) {
  26677. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26678. }
  26679. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26680. instance.checkCollisions = mesh.checkCollisions;
  26681. if (parsedMesh.animations) {
  26682. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26683. parsedAnimation = parsedMesh.animations[animationIndex];
  26684. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26685. }
  26686. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26687. }
  26688. }
  26689. }
  26690. return mesh;
  26691. };
  26692. /**
  26693. * Creates a ribbon mesh.
  26694. * Please consider using the same method from the MeshBuilder class instead.
  26695. * 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.
  26696. *
  26697. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26698. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26699. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26700. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26701. * 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.
  26702. * 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.
  26703. * 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
  26704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26705. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26707. */
  26708. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26709. if (closeArray === void 0) { closeArray = false; }
  26710. if (updatable === void 0) { updatable = false; }
  26711. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26712. pathArray: pathArray,
  26713. closeArray: closeArray,
  26714. closePath: closePath,
  26715. offset: offset,
  26716. updatable: updatable,
  26717. sideOrientation: sideOrientation,
  26718. instance: instance
  26719. }, scene);
  26720. };
  26721. /**
  26722. * Creates a plane polygonal mesh. By default, this is a disc.
  26723. * Please consider using the same method from the MeshBuilder class instead.
  26724. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  26725. * 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.
  26726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26727. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26729. */
  26730. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  26731. if (scene === void 0) { scene = null; }
  26732. var options = {
  26733. radius: radius,
  26734. tessellation: tessellation,
  26735. sideOrientation: sideOrientation,
  26736. updatable: updatable
  26737. };
  26738. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  26739. };
  26740. /**
  26741. * Creates a box mesh.
  26742. * Please consider using the same method from the MeshBuilder class instead.
  26743. * The parameter `size` sets the size (float) of each box side (default 1).
  26744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26747. */
  26748. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  26749. if (scene === void 0) { scene = null; }
  26750. var options = {
  26751. size: size,
  26752. sideOrientation: sideOrientation,
  26753. updatable: updatable
  26754. };
  26755. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  26756. };
  26757. /**
  26758. * Creates a sphere mesh.
  26759. * Please consider using the same method from the MeshBuilder class instead.
  26760. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  26761. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  26762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26765. */
  26766. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  26767. var options = {
  26768. segments: segments,
  26769. diameterX: diameter,
  26770. diameterY: diameter,
  26771. diameterZ: diameter,
  26772. sideOrientation: sideOrientation,
  26773. updatable: updatable
  26774. };
  26775. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  26776. };
  26777. /**
  26778. * Creates a cylinder or a cone mesh.
  26779. * Please consider using the same method from the MeshBuilder class instead.
  26780. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  26781. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  26782. * 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.
  26783. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  26784. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  26785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26788. */
  26789. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  26790. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  26791. if (scene !== undefined) {
  26792. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  26793. updatable = scene;
  26794. }
  26795. scene = subdivisions;
  26796. subdivisions = 1;
  26797. }
  26798. var options = {
  26799. height: height,
  26800. diameterTop: diameterTop,
  26801. diameterBottom: diameterBottom,
  26802. tessellation: tessellation,
  26803. subdivisions: subdivisions,
  26804. sideOrientation: sideOrientation,
  26805. updatable: updatable
  26806. };
  26807. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  26808. };
  26809. // Torus (Code from SharpDX.org)
  26810. /**
  26811. * Creates a torus mesh.
  26812. * Please consider using the same method from the MeshBuilder class instead.
  26813. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  26814. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  26815. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  26816. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26817. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26819. */
  26820. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  26821. var options = {
  26822. diameter: diameter,
  26823. thickness: thickness,
  26824. tessellation: tessellation,
  26825. sideOrientation: sideOrientation,
  26826. updatable: updatable
  26827. };
  26828. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  26829. };
  26830. /**
  26831. * Creates a torus knot mesh.
  26832. * Please consider using the same method from the MeshBuilder class instead.
  26833. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26834. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26835. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26836. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26840. */
  26841. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  26842. var options = {
  26843. radius: radius,
  26844. tube: tube,
  26845. radialSegments: radialSegments,
  26846. tubularSegments: tubularSegments,
  26847. p: p,
  26848. q: q,
  26849. sideOrientation: sideOrientation,
  26850. updatable: updatable
  26851. };
  26852. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  26853. };
  26854. /**
  26855. * Creates a line mesh.
  26856. * Please consider using the same method from the MeshBuilder class instead.
  26857. * 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.
  26858. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26859. * The parameter `points` is an array successive Vector3.
  26860. * 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
  26861. * When updating an instance, remember that only point positions can change, not the number of points.
  26862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26863. */
  26864. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  26865. if (scene === void 0) { scene = null; }
  26866. if (updatable === void 0) { updatable = false; }
  26867. if (instance === void 0) { instance = null; }
  26868. var options = {
  26869. points: points,
  26870. updatable: updatable,
  26871. instance: instance
  26872. };
  26873. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  26874. };
  26875. /**
  26876. * Creates a dashed line mesh.
  26877. * Please consider using the same method from the MeshBuilder class instead.
  26878. * 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.
  26879. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26880. * The parameter `points` is an array successive Vector3.
  26881. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26882. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26883. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26884. * 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
  26885. * When updating an instance, remember that only point positions can change, not the number of points.
  26886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26887. */
  26888. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  26889. if (scene === void 0) { scene = null; }
  26890. var options = {
  26891. points: points,
  26892. dashSize: dashSize,
  26893. gapSize: gapSize,
  26894. dashNb: dashNb,
  26895. updatable: updatable,
  26896. instance: instance
  26897. };
  26898. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  26899. };
  26900. /**
  26901. * Creates a polygon mesh.
  26902. * Please consider using the same method from the MeshBuilder class instead.
  26903. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  26904. * 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.
  26905. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26906. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26907. * Remember you can only change the shape positions, not their number when updating a polygon.
  26908. */
  26909. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  26910. var options = {
  26911. shape: shape,
  26912. holes: holes,
  26913. updatable: updatable,
  26914. sideOrientation: sideOrientation
  26915. };
  26916. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  26917. };
  26918. /**
  26919. * Creates an extruded polygon mesh, with depth in the Y direction.
  26920. * Please consider using the same method from the MeshBuilder class instead.
  26921. */
  26922. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  26923. var options = {
  26924. shape: shape,
  26925. holes: holes,
  26926. depth: depth,
  26927. updatable: updatable,
  26928. sideOrientation: sideOrientation
  26929. };
  26930. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  26931. };
  26932. /**
  26933. * Creates an extruded shape mesh.
  26934. * 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.
  26935. * Please consider using the same method from the MeshBuilder class instead.
  26936. *
  26937. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26938. * 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
  26939. * extruded along the Z axis.
  26940. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26941. * 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.
  26942. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26943. * 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
  26944. * 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
  26945. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26949. */
  26950. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  26951. if (scene === void 0) { scene = null; }
  26952. var options = {
  26953. shape: shape,
  26954. path: path,
  26955. scale: scale,
  26956. rotation: rotation,
  26957. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26958. sideOrientation: sideOrientation,
  26959. instance: instance,
  26960. updatable: updatable
  26961. };
  26962. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  26963. };
  26964. /**
  26965. * Creates an custom extruded shape mesh.
  26966. * 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.
  26967. * Please consider using the same method from the MeshBuilder class instead.
  26968. *
  26969. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26970. * 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
  26971. * extruded along the Z axis.
  26972. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26973. * 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
  26974. * and the distance of this point from the begining of the path :
  26975. * ```javascript
  26976. * var rotationFunction = function(i, distance) {
  26977. * // do things
  26978. * return rotationValue; }
  26979. * ```
  26980. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26981. * 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
  26982. * and the distance of this point from the begining of the path :
  26983. * ```javascript
  26984. * var scaleFunction = function(i, distance) {
  26985. * // do things
  26986. * return scaleValue;}
  26987. * ```
  26988. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26989. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26990. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26991. * 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
  26992. * 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
  26993. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26997. */
  26998. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26999. var options = {
  27000. shape: shape,
  27001. path: path,
  27002. scaleFunction: scaleFunction,
  27003. rotationFunction: rotationFunction,
  27004. ribbonCloseArray: ribbonCloseArray,
  27005. ribbonClosePath: ribbonClosePath,
  27006. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27007. sideOrientation: sideOrientation,
  27008. instance: instance,
  27009. updatable: updatable
  27010. };
  27011. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27012. };
  27013. /**
  27014. * Creates lathe mesh.
  27015. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27016. * Please consider using the same method from the MeshBuilder class instead.
  27017. * 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
  27018. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27019. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27020. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27021. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27022. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27024. */
  27025. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27026. var options = {
  27027. shape: shape,
  27028. radius: radius,
  27029. tessellation: tessellation,
  27030. sideOrientation: sideOrientation,
  27031. updatable: updatable
  27032. };
  27033. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27034. };
  27035. /**
  27036. * Creates a plane mesh.
  27037. * Please consider using the same method from the MeshBuilder class instead.
  27038. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27042. */
  27043. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27044. var options = {
  27045. size: size,
  27046. width: size,
  27047. height: size,
  27048. sideOrientation: sideOrientation,
  27049. updatable: updatable
  27050. };
  27051. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27052. };
  27053. /**
  27054. * Creates a ground mesh.
  27055. * Please consider using the same method from the MeshBuilder class instead.
  27056. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27057. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27059. */
  27060. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27061. var options = {
  27062. width: width,
  27063. height: height,
  27064. subdivisions: subdivisions,
  27065. updatable: updatable
  27066. };
  27067. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27068. };
  27069. /**
  27070. * Creates a tiled ground mesh.
  27071. * Please consider using the same method from the MeshBuilder class instead.
  27072. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27073. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27074. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27075. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27076. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27077. * numbers of subdivisions on the ground width and height of each tile.
  27078. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27079. */
  27080. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27081. var options = {
  27082. xmin: xmin,
  27083. zmin: zmin,
  27084. xmax: xmax,
  27085. zmax: zmax,
  27086. subdivisions: subdivisions,
  27087. precision: precision,
  27088. updatable: updatable
  27089. };
  27090. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27091. };
  27092. /**
  27093. * Creates a ground mesh from a height map.
  27094. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27095. * Please consider using the same method from the MeshBuilder class instead.
  27096. * The parameter `url` sets the URL of the height map image resource.
  27097. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27098. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27099. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27100. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27101. * 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).
  27102. * This function is passed the newly built mesh :
  27103. * ```javascript
  27104. * function(mesh) { // do things
  27105. * return; }
  27106. * ```
  27107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27108. */
  27109. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27110. var options = {
  27111. width: width,
  27112. height: height,
  27113. subdivisions: subdivisions,
  27114. minHeight: minHeight,
  27115. maxHeight: maxHeight,
  27116. updatable: updatable,
  27117. onReady: onReady
  27118. };
  27119. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27120. };
  27121. /**
  27122. * Creates a tube mesh.
  27123. * 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.
  27124. * Please consider using the same method from the MeshBuilder class instead.
  27125. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27126. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27127. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27128. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27129. * 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.
  27130. * It must return a radius value (positive float) :
  27131. * ```javascript
  27132. * var radiusFunction = function(i, distance) {
  27133. * // do things
  27134. * return radius; }
  27135. * ```
  27136. * 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
  27137. * 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
  27138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27141. */
  27142. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27143. var options = {
  27144. path: path,
  27145. radius: radius,
  27146. tessellation: tessellation,
  27147. radiusFunction: radiusFunction,
  27148. arc: 1,
  27149. cap: cap,
  27150. updatable: updatable,
  27151. sideOrientation: sideOrientation,
  27152. instance: instance
  27153. };
  27154. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27155. };
  27156. /**
  27157. * Creates a polyhedron mesh.
  27158. * Please consider using the same method from the MeshBuilder class instead.
  27159. * 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
  27160. * to choose the wanted type.
  27161. * The parameter `size` (positive float, default 1) sets the polygon size.
  27162. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27163. * 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`.
  27164. * 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
  27165. * 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)`).
  27166. * 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
  27167. * 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.
  27168. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27169. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27170. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27171. */
  27172. Mesh.CreatePolyhedron = function (name, options, scene) {
  27173. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27174. };
  27175. /**
  27176. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27177. * Please consider using the same method from the MeshBuilder class instead.
  27178. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27179. * 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`).
  27180. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27181. * 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.
  27182. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27183. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27185. */
  27186. Mesh.CreateIcoSphere = function (name, options, scene) {
  27187. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27188. };
  27189. /**
  27190. * Creates a decal mesh.
  27191. * Please consider using the same method from the MeshBuilder class instead.
  27192. * 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.
  27193. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27194. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27195. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27196. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27197. */
  27198. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27199. var options = {
  27200. position: position,
  27201. normal: normal,
  27202. size: size,
  27203. angle: angle
  27204. };
  27205. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27206. };
  27207. // Skeletons
  27208. /**
  27209. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27210. */
  27211. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27212. if (!this._sourcePositions) {
  27213. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27214. if (!source) {
  27215. return this._sourcePositions;
  27216. }
  27217. this._sourcePositions = new Float32Array(source);
  27218. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27219. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27220. }
  27221. }
  27222. return this._sourcePositions;
  27223. };
  27224. /**
  27225. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27226. */
  27227. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27228. if (!this._sourceNormals) {
  27229. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27230. if (!source) {
  27231. return this._sourceNormals;
  27232. }
  27233. this._sourceNormals = new Float32Array(source);
  27234. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27235. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27236. }
  27237. }
  27238. return this._sourceNormals;
  27239. };
  27240. /**
  27241. * Updates the vertex buffer by applying transformation from the bones.
  27242. * Returns the Mesh.
  27243. *
  27244. * @param {skeleton} skeleton to apply
  27245. */
  27246. Mesh.prototype.applySkeleton = function (skeleton) {
  27247. if (!this.geometry) {
  27248. return this;
  27249. }
  27250. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27251. return this;
  27252. }
  27253. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27254. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27255. return this;
  27256. }
  27257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27258. return this;
  27259. }
  27260. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27261. return this;
  27262. }
  27263. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27264. return this;
  27265. }
  27266. if (!this._sourcePositions) {
  27267. var submeshes = this.subMeshes.slice();
  27268. this.setPositionsForCPUSkinning();
  27269. this.subMeshes = submeshes;
  27270. }
  27271. if (!this._sourceNormals) {
  27272. this.setNormalsForCPUSkinning();
  27273. }
  27274. // positionsData checks for not being Float32Array will only pass at most once
  27275. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27276. if (!positionsData) {
  27277. return this;
  27278. }
  27279. if (!(positionsData instanceof Float32Array)) {
  27280. positionsData = new Float32Array(positionsData);
  27281. }
  27282. // normalsData checks for not being Float32Array will only pass at most once
  27283. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27284. if (!normalsData) {
  27285. return this;
  27286. }
  27287. if (!(normalsData instanceof Float32Array)) {
  27288. normalsData = new Float32Array(normalsData);
  27289. }
  27290. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27291. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27292. if (!matricesWeightsData || !matricesIndicesData) {
  27293. return this;
  27294. }
  27295. var needExtras = this.numBoneInfluencers > 4;
  27296. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27297. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27298. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27299. var tempVector3 = BABYLON.Vector3.Zero();
  27300. var finalMatrix = new BABYLON.Matrix();
  27301. var tempMatrix = new BABYLON.Matrix();
  27302. var matWeightIdx = 0;
  27303. var inf;
  27304. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27305. var weight;
  27306. for (inf = 0; inf < 4; inf++) {
  27307. weight = matricesWeightsData[matWeightIdx + inf];
  27308. if (weight > 0) {
  27309. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27310. finalMatrix.addToSelf(tempMatrix);
  27311. }
  27312. else
  27313. break;
  27314. }
  27315. if (needExtras) {
  27316. for (inf = 0; inf < 4; inf++) {
  27317. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27318. if (weight > 0) {
  27319. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27320. finalMatrix.addToSelf(tempMatrix);
  27321. }
  27322. else
  27323. break;
  27324. }
  27325. }
  27326. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27327. tempVector3.toArray(positionsData, index);
  27328. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27329. tempVector3.toArray(normalsData, index);
  27330. finalMatrix.reset();
  27331. }
  27332. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27333. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27334. return this;
  27335. };
  27336. // Tools
  27337. /**
  27338. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27339. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27340. */
  27341. Mesh.MinMax = function (meshes) {
  27342. var minVector = null;
  27343. var maxVector = null;
  27344. meshes.forEach(function (mesh, index, array) {
  27345. var boundingInfo = mesh.getBoundingInfo();
  27346. var boundingBox = boundingInfo.boundingBox;
  27347. if (!minVector || !maxVector) {
  27348. minVector = boundingBox.minimumWorld;
  27349. maxVector = boundingBox.maximumWorld;
  27350. }
  27351. else {
  27352. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27353. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27354. }
  27355. });
  27356. if (!minVector || !maxVector) {
  27357. return {
  27358. min: BABYLON.Vector3.Zero(),
  27359. max: BABYLON.Vector3.Zero()
  27360. };
  27361. }
  27362. return {
  27363. min: minVector,
  27364. max: maxVector
  27365. };
  27366. };
  27367. /**
  27368. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27369. */
  27370. Mesh.Center = function (meshesOrMinMaxVector) {
  27371. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27372. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27373. };
  27374. /**
  27375. * Merge the array of meshes into a single mesh for performance reasons.
  27376. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27377. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27378. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27379. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27380. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27381. */
  27382. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27383. if (disposeSource === void 0) { disposeSource = true; }
  27384. var index;
  27385. if (!allow32BitsIndices) {
  27386. var totalVertices = 0;
  27387. // Counting vertices
  27388. for (index = 0; index < meshes.length; index++) {
  27389. if (meshes[index]) {
  27390. totalVertices += meshes[index].getTotalVertices();
  27391. if (totalVertices > 65536) {
  27392. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27393. return null;
  27394. }
  27395. }
  27396. }
  27397. }
  27398. // Merge
  27399. var vertexData = null;
  27400. var otherVertexData;
  27401. var indiceArray = new Array();
  27402. var source = null;
  27403. for (index = 0; index < meshes.length; index++) {
  27404. if (meshes[index]) {
  27405. meshes[index].computeWorldMatrix(true);
  27406. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27407. otherVertexData.transform(meshes[index].getWorldMatrix());
  27408. if (vertexData) {
  27409. vertexData.merge(otherVertexData);
  27410. }
  27411. else {
  27412. vertexData = otherVertexData;
  27413. source = meshes[index];
  27414. }
  27415. if (subdivideWithSubMeshes) {
  27416. indiceArray.push(meshes[index].getTotalIndices());
  27417. }
  27418. }
  27419. }
  27420. source = source;
  27421. if (!meshSubclass) {
  27422. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27423. }
  27424. vertexData.applyToMesh(meshSubclass);
  27425. // Setting properties
  27426. meshSubclass.material = source.material;
  27427. meshSubclass.checkCollisions = source.checkCollisions;
  27428. // Cleaning
  27429. if (disposeSource) {
  27430. for (index = 0; index < meshes.length; index++) {
  27431. if (meshes[index]) {
  27432. meshes[index].dispose();
  27433. }
  27434. }
  27435. }
  27436. // Subdivide
  27437. if (subdivideWithSubMeshes) {
  27438. //-- Suppresions du submesh global
  27439. meshSubclass.releaseSubMeshes();
  27440. index = 0;
  27441. var offset = 0;
  27442. //-- aplique la subdivision en fonction du tableau d'indices
  27443. while (index < indiceArray.length) {
  27444. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27445. offset += indiceArray[index];
  27446. index++;
  27447. }
  27448. }
  27449. return meshSubclass;
  27450. };
  27451. // Consts
  27452. Mesh._FRONTSIDE = 0;
  27453. Mesh._BACKSIDE = 1;
  27454. Mesh._DOUBLESIDE = 2;
  27455. Mesh._DEFAULTSIDE = 0;
  27456. Mesh._NO_CAP = 0;
  27457. Mesh._CAP_START = 1;
  27458. Mesh._CAP_END = 2;
  27459. Mesh._CAP_ALL = 3;
  27460. return Mesh;
  27461. }(BABYLON.AbstractMesh));
  27462. BABYLON.Mesh = Mesh;
  27463. })(BABYLON || (BABYLON = {}));
  27464. //# sourceMappingURL=babylon.mesh.js.map
  27465. var BABYLON;
  27466. (function (BABYLON) {
  27467. var BaseSubMesh = /** @class */ (function () {
  27468. function BaseSubMesh() {
  27469. }
  27470. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27471. get: function () {
  27472. return this._materialEffect;
  27473. },
  27474. enumerable: true,
  27475. configurable: true
  27476. });
  27477. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27478. if (defines === void 0) { defines = null; }
  27479. if (this._materialEffect === effect) {
  27480. if (!effect) {
  27481. this._materialDefines = null;
  27482. }
  27483. return;
  27484. }
  27485. this._materialDefines = defines;
  27486. this._materialEffect = effect;
  27487. };
  27488. return BaseSubMesh;
  27489. }());
  27490. BABYLON.BaseSubMesh = BaseSubMesh;
  27491. var SubMesh = /** @class */ (function (_super) {
  27492. __extends(SubMesh, _super);
  27493. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27494. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27495. var _this = _super.call(this) || this;
  27496. _this.materialIndex = materialIndex;
  27497. _this.verticesStart = verticesStart;
  27498. _this.verticesCount = verticesCount;
  27499. _this.indexStart = indexStart;
  27500. _this.indexCount = indexCount;
  27501. _this._renderId = 0;
  27502. _this._mesh = mesh;
  27503. _this._renderingMesh = renderingMesh || mesh;
  27504. mesh.subMeshes.push(_this);
  27505. _this._trianglePlanes = [];
  27506. _this._id = mesh.subMeshes.length - 1;
  27507. if (createBoundingBox) {
  27508. _this.refreshBoundingInfo();
  27509. mesh.computeWorldMatrix(true);
  27510. }
  27511. return _this;
  27512. }
  27513. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27514. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27515. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27516. };
  27517. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27518. get: function () {
  27519. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27520. },
  27521. enumerable: true,
  27522. configurable: true
  27523. });
  27524. /**
  27525. * Returns the submesh BoudingInfo object.
  27526. */
  27527. SubMesh.prototype.getBoundingInfo = function () {
  27528. if (this.IsGlobal) {
  27529. return this._mesh.getBoundingInfo();
  27530. }
  27531. return this._boundingInfo;
  27532. };
  27533. /**
  27534. * Sets the submesh BoundingInfo.
  27535. * Return the SubMesh.
  27536. */
  27537. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27538. this._boundingInfo = boundingInfo;
  27539. return this;
  27540. };
  27541. /**
  27542. * Returns the mesh of the current submesh.
  27543. */
  27544. SubMesh.prototype.getMesh = function () {
  27545. return this._mesh;
  27546. };
  27547. /**
  27548. * Returns the rendering mesh of the submesh.
  27549. */
  27550. SubMesh.prototype.getRenderingMesh = function () {
  27551. return this._renderingMesh;
  27552. };
  27553. /**
  27554. * Returns the submesh material.
  27555. */
  27556. SubMesh.prototype.getMaterial = function () {
  27557. var rootMaterial = this._renderingMesh.material;
  27558. if (rootMaterial === null || rootMaterial === undefined) {
  27559. return this._mesh.getScene().defaultMaterial;
  27560. }
  27561. else if (rootMaterial.getSubMaterial) {
  27562. var multiMaterial = rootMaterial;
  27563. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27564. if (this._currentMaterial !== effectiveMaterial) {
  27565. this._currentMaterial = effectiveMaterial;
  27566. this._materialDefines = null;
  27567. }
  27568. return effectiveMaterial;
  27569. }
  27570. return rootMaterial;
  27571. };
  27572. // Methods
  27573. /**
  27574. * Sets a new updated BoundingInfo object to the submesh.
  27575. * Returns the SubMesh.
  27576. */
  27577. SubMesh.prototype.refreshBoundingInfo = function () {
  27578. this._lastColliderWorldVertices = null;
  27579. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27580. return this;
  27581. }
  27582. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27583. if (!data) {
  27584. this._boundingInfo = this._mesh.getBoundingInfo();
  27585. return this;
  27586. }
  27587. var indices = this._renderingMesh.getIndices();
  27588. var extend;
  27589. //is this the only submesh?
  27590. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27591. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27592. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27593. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27594. }
  27595. else {
  27596. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27597. }
  27598. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27599. return this;
  27600. };
  27601. SubMesh.prototype._checkCollision = function (collider) {
  27602. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27603. return boundingInfo._checkCollision(collider);
  27604. };
  27605. /**
  27606. * Updates the submesh BoundingInfo.
  27607. * Returns the Submesh.
  27608. */
  27609. SubMesh.prototype.updateBoundingInfo = function (world) {
  27610. var boundingInfo = this.getBoundingInfo();
  27611. if (!boundingInfo) {
  27612. this.refreshBoundingInfo();
  27613. boundingInfo = this.getBoundingInfo();
  27614. }
  27615. boundingInfo.update(world);
  27616. return this;
  27617. };
  27618. /**
  27619. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27620. * Boolean returned.
  27621. */
  27622. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27623. var boundingInfo = this.getBoundingInfo();
  27624. if (!boundingInfo) {
  27625. return false;
  27626. }
  27627. return boundingInfo.isInFrustum(frustumPlanes);
  27628. };
  27629. /**
  27630. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27631. * Boolean returned.
  27632. */
  27633. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27634. var boundingInfo = this.getBoundingInfo();
  27635. if (!boundingInfo) {
  27636. return false;
  27637. }
  27638. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27639. };
  27640. /**
  27641. * Renders the submesh.
  27642. * Returns it.
  27643. */
  27644. SubMesh.prototype.render = function (enableAlphaMode) {
  27645. this._renderingMesh.render(this, enableAlphaMode);
  27646. return this;
  27647. };
  27648. /**
  27649. * Returns a new Index Buffer.
  27650. * Type returned : WebGLBuffer.
  27651. */
  27652. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27653. if (!this._linesIndexBuffer) {
  27654. var linesIndices = [];
  27655. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27656. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27657. }
  27658. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27659. this.linesIndexCount = linesIndices.length;
  27660. }
  27661. return this._linesIndexBuffer;
  27662. };
  27663. /**
  27664. * True is the passed Ray intersects the submesh bounding box.
  27665. * Boolean returned.
  27666. */
  27667. SubMesh.prototype.canIntersects = function (ray) {
  27668. var boundingInfo = this.getBoundingInfo();
  27669. if (!boundingInfo) {
  27670. return false;
  27671. }
  27672. return ray.intersectsBox(boundingInfo.boundingBox);
  27673. };
  27674. /**
  27675. * Returns an object IntersectionInfo.
  27676. */
  27677. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27678. var intersectInfo = null;
  27679. // LineMesh first as it's also a Mesh...
  27680. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27681. var lineMesh = this._mesh;
  27682. // Line test
  27683. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27684. var p0 = positions[indices[index]];
  27685. var p1 = positions[indices[index + 1]];
  27686. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27687. if (length < 0) {
  27688. continue;
  27689. }
  27690. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27691. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27692. if (fastCheck) {
  27693. break;
  27694. }
  27695. }
  27696. }
  27697. }
  27698. else {
  27699. // Triangles test
  27700. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27701. var p0 = positions[indices[index]];
  27702. var p1 = positions[indices[index + 1]];
  27703. var p2 = positions[indices[index + 2]];
  27704. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27705. if (currentIntersectInfo) {
  27706. if (currentIntersectInfo.distance < 0) {
  27707. continue;
  27708. }
  27709. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27710. intersectInfo = currentIntersectInfo;
  27711. intersectInfo.faceId = index / 3;
  27712. if (fastCheck) {
  27713. break;
  27714. }
  27715. }
  27716. }
  27717. }
  27718. }
  27719. return intersectInfo;
  27720. };
  27721. SubMesh.prototype._rebuild = function () {
  27722. if (this._linesIndexBuffer) {
  27723. this._linesIndexBuffer = null;
  27724. }
  27725. };
  27726. // Clone
  27727. /**
  27728. * Creates a new Submesh from the passed Mesh.
  27729. */
  27730. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  27731. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  27732. if (!this.IsGlobal) {
  27733. var boundingInfo = this.getBoundingInfo();
  27734. if (!boundingInfo) {
  27735. return result;
  27736. }
  27737. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  27738. }
  27739. return result;
  27740. };
  27741. // Dispose
  27742. /**
  27743. * Disposes the Submesh.
  27744. * Returns nothing.
  27745. */
  27746. SubMesh.prototype.dispose = function () {
  27747. if (this._linesIndexBuffer) {
  27748. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  27749. this._linesIndexBuffer = null;
  27750. }
  27751. // Remove from mesh
  27752. var index = this._mesh.subMeshes.indexOf(this);
  27753. this._mesh.subMeshes.splice(index, 1);
  27754. };
  27755. // Statics
  27756. /**
  27757. * Creates a new Submesh from the passed parameters :
  27758. * - materialIndex (integer) : the index of the main mesh material.
  27759. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  27760. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  27761. * - mesh (Mesh) : the main mesh to create the submesh from.
  27762. * - renderingMesh (optional Mesh) : rendering mesh.
  27763. */
  27764. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  27765. var minVertexIndex = Number.MAX_VALUE;
  27766. var maxVertexIndex = -Number.MAX_VALUE;
  27767. renderingMesh = (renderingMesh || mesh);
  27768. var indices = renderingMesh.getIndices();
  27769. for (var index = startIndex; index < startIndex + indexCount; index++) {
  27770. var vertexIndex = indices[index];
  27771. if (vertexIndex < minVertexIndex)
  27772. minVertexIndex = vertexIndex;
  27773. if (vertexIndex > maxVertexIndex)
  27774. maxVertexIndex = vertexIndex;
  27775. }
  27776. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  27777. };
  27778. return SubMesh;
  27779. }(BaseSubMesh));
  27780. BABYLON.SubMesh = SubMesh;
  27781. })(BABYLON || (BABYLON = {}));
  27782. //# sourceMappingURL=babylon.subMesh.js.map
  27783. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27784. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27785. s = arguments[i];
  27786. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27787. t[p] = s[p];
  27788. }
  27789. return t;
  27790. };
  27791. var BABYLON;
  27792. (function (BABYLON) {
  27793. var MaterialDefines = /** @class */ (function () {
  27794. function MaterialDefines() {
  27795. this._isDirty = true;
  27796. this._areLightsDirty = true;
  27797. this._areAttributesDirty = true;
  27798. this._areTexturesDirty = true;
  27799. this._areFresnelDirty = true;
  27800. this._areMiscDirty = true;
  27801. this._areImageProcessingDirty = true;
  27802. this._normals = false;
  27803. this._uvs = false;
  27804. this._needNormals = false;
  27805. this._needUVs = false;
  27806. }
  27807. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27808. get: function () {
  27809. return this._isDirty;
  27810. },
  27811. enumerable: true,
  27812. configurable: true
  27813. });
  27814. MaterialDefines.prototype.markAsProcessed = function () {
  27815. this._isDirty = false;
  27816. this._areAttributesDirty = false;
  27817. this._areTexturesDirty = false;
  27818. this._areFresnelDirty = false;
  27819. this._areLightsDirty = false;
  27820. this._areMiscDirty = false;
  27821. this._areImageProcessingDirty = false;
  27822. };
  27823. MaterialDefines.prototype.markAsUnprocessed = function () {
  27824. this._isDirty = true;
  27825. };
  27826. MaterialDefines.prototype.markAllAsDirty = function () {
  27827. this._areTexturesDirty = true;
  27828. this._areAttributesDirty = true;
  27829. this._areLightsDirty = true;
  27830. this._areFresnelDirty = true;
  27831. this._areMiscDirty = true;
  27832. this._areImageProcessingDirty = true;
  27833. this._isDirty = true;
  27834. };
  27835. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27836. this._areImageProcessingDirty = true;
  27837. this._isDirty = true;
  27838. };
  27839. MaterialDefines.prototype.markAsLightDirty = function () {
  27840. this._areLightsDirty = true;
  27841. this._isDirty = true;
  27842. };
  27843. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27844. this._areAttributesDirty = true;
  27845. this._isDirty = true;
  27846. };
  27847. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27848. this._areTexturesDirty = true;
  27849. this._isDirty = true;
  27850. };
  27851. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27852. this._areFresnelDirty = true;
  27853. this._isDirty = true;
  27854. };
  27855. MaterialDefines.prototype.markAsMiscDirty = function () {
  27856. this._areMiscDirty = true;
  27857. this._isDirty = true;
  27858. };
  27859. MaterialDefines.prototype.rebuild = function () {
  27860. if (this._keys) {
  27861. delete this._keys;
  27862. }
  27863. this._keys = [];
  27864. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27865. var key = _a[_i];
  27866. if (key[0] === "_") {
  27867. continue;
  27868. }
  27869. this._keys.push(key);
  27870. }
  27871. };
  27872. MaterialDefines.prototype.isEqual = function (other) {
  27873. if (this._keys.length !== other._keys.length) {
  27874. return false;
  27875. }
  27876. for (var index = 0; index < this._keys.length; index++) {
  27877. var prop = this._keys[index];
  27878. if (this[prop] !== other[prop]) {
  27879. return false;
  27880. }
  27881. }
  27882. return true;
  27883. };
  27884. MaterialDefines.prototype.cloneTo = function (other) {
  27885. if (this._keys.length !== other._keys.length) {
  27886. other._keys = this._keys.slice(0);
  27887. }
  27888. for (var index = 0; index < this._keys.length; index++) {
  27889. var prop = this._keys[index];
  27890. other[prop] = this[prop];
  27891. }
  27892. };
  27893. MaterialDefines.prototype.reset = function () {
  27894. for (var index = 0; index < this._keys.length; index++) {
  27895. var prop = this._keys[index];
  27896. if (typeof (this[prop]) === "number") {
  27897. this[prop] = 0;
  27898. }
  27899. else {
  27900. this[prop] = false;
  27901. }
  27902. }
  27903. };
  27904. MaterialDefines.prototype.toString = function () {
  27905. var result = "";
  27906. for (var index = 0; index < this._keys.length; index++) {
  27907. var prop = this._keys[index];
  27908. var value = this[prop];
  27909. if (typeof (value) === "number") {
  27910. result += "#define " + prop + " " + this[prop] + "\n";
  27911. }
  27912. else if (value) {
  27913. result += "#define " + prop + "\n";
  27914. }
  27915. }
  27916. return result;
  27917. };
  27918. return MaterialDefines;
  27919. }());
  27920. BABYLON.MaterialDefines = MaterialDefines;
  27921. var Material = /** @class */ (function () {
  27922. function Material(name, scene, doNotAdd) {
  27923. this.checkReadyOnEveryCall = false;
  27924. this.checkReadyOnlyOnce = false;
  27925. this.state = "";
  27926. this.alpha = 1.0;
  27927. this._backFaceCulling = true;
  27928. this.doNotSerialize = false;
  27929. this.storeEffectOnSubMeshes = false;
  27930. /**
  27931. * An event triggered when the material is disposed.
  27932. * @type {BABYLON.Observable}
  27933. */
  27934. this.onDisposeObservable = new BABYLON.Observable();
  27935. /**
  27936. * An event triggered when the material is bound.
  27937. * @type {BABYLON.Observable}
  27938. */
  27939. this.onBindObservable = new BABYLON.Observable();
  27940. /**
  27941. * An event triggered when the material is unbound.
  27942. * @type {BABYLON.Observable}
  27943. */
  27944. this.onUnBindObservable = new BABYLON.Observable();
  27945. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27946. this._needDepthPrePass = false;
  27947. this.disableDepthWrite = false;
  27948. this.forceDepthWrite = false;
  27949. this.separateCullingPass = false;
  27950. this._fogEnabled = true;
  27951. this.pointSize = 1.0;
  27952. this.zOffset = 0;
  27953. this._wasPreviouslyReady = false;
  27954. this._fillMode = Material.TriangleFillMode;
  27955. this.name = name;
  27956. this.id = name || BABYLON.Tools.RandomId();
  27957. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27958. if (this._scene.useRightHandedSystem) {
  27959. this.sideOrientation = Material.ClockWiseSideOrientation;
  27960. }
  27961. else {
  27962. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27963. }
  27964. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27965. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27966. if (!doNotAdd) {
  27967. this._scene.materials.push(this);
  27968. }
  27969. }
  27970. Object.defineProperty(Material, "TriangleFillMode", {
  27971. get: function () {
  27972. return Material._TriangleFillMode;
  27973. },
  27974. enumerable: true,
  27975. configurable: true
  27976. });
  27977. Object.defineProperty(Material, "WireFrameFillMode", {
  27978. get: function () {
  27979. return Material._WireFrameFillMode;
  27980. },
  27981. enumerable: true,
  27982. configurable: true
  27983. });
  27984. Object.defineProperty(Material, "PointFillMode", {
  27985. get: function () {
  27986. return Material._PointFillMode;
  27987. },
  27988. enumerable: true,
  27989. configurable: true
  27990. });
  27991. Object.defineProperty(Material, "PointListDrawMode", {
  27992. get: function () {
  27993. return Material._PointListDrawMode;
  27994. },
  27995. enumerable: true,
  27996. configurable: true
  27997. });
  27998. Object.defineProperty(Material, "LineListDrawMode", {
  27999. get: function () {
  28000. return Material._LineListDrawMode;
  28001. },
  28002. enumerable: true,
  28003. configurable: true
  28004. });
  28005. Object.defineProperty(Material, "LineLoopDrawMode", {
  28006. get: function () {
  28007. return Material._LineLoopDrawMode;
  28008. },
  28009. enumerable: true,
  28010. configurable: true
  28011. });
  28012. Object.defineProperty(Material, "LineStripDrawMode", {
  28013. get: function () {
  28014. return Material._LineStripDrawMode;
  28015. },
  28016. enumerable: true,
  28017. configurable: true
  28018. });
  28019. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28020. get: function () {
  28021. return Material._TriangleStripDrawMode;
  28022. },
  28023. enumerable: true,
  28024. configurable: true
  28025. });
  28026. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28027. get: function () {
  28028. return Material._TriangleFanDrawMode;
  28029. },
  28030. enumerable: true,
  28031. configurable: true
  28032. });
  28033. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28034. get: function () {
  28035. return Material._ClockWiseSideOrientation;
  28036. },
  28037. enumerable: true,
  28038. configurable: true
  28039. });
  28040. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28041. get: function () {
  28042. return Material._CounterClockWiseSideOrientation;
  28043. },
  28044. enumerable: true,
  28045. configurable: true
  28046. });
  28047. Object.defineProperty(Material, "TextureDirtyFlag", {
  28048. get: function () {
  28049. return Material._TextureDirtyFlag;
  28050. },
  28051. enumerable: true,
  28052. configurable: true
  28053. });
  28054. Object.defineProperty(Material, "LightDirtyFlag", {
  28055. get: function () {
  28056. return Material._LightDirtyFlag;
  28057. },
  28058. enumerable: true,
  28059. configurable: true
  28060. });
  28061. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28062. get: function () {
  28063. return Material._FresnelDirtyFlag;
  28064. },
  28065. enumerable: true,
  28066. configurable: true
  28067. });
  28068. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28069. get: function () {
  28070. return Material._AttributesDirtyFlag;
  28071. },
  28072. enumerable: true,
  28073. configurable: true
  28074. });
  28075. Object.defineProperty(Material, "MiscDirtyFlag", {
  28076. get: function () {
  28077. return Material._MiscDirtyFlag;
  28078. },
  28079. enumerable: true,
  28080. configurable: true
  28081. });
  28082. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28083. get: function () {
  28084. return this._backFaceCulling;
  28085. },
  28086. set: function (value) {
  28087. if (this._backFaceCulling === value) {
  28088. return;
  28089. }
  28090. this._backFaceCulling = value;
  28091. this.markAsDirty(Material.TextureDirtyFlag);
  28092. },
  28093. enumerable: true,
  28094. configurable: true
  28095. });
  28096. Object.defineProperty(Material.prototype, "onDispose", {
  28097. set: function (callback) {
  28098. if (this._onDisposeObserver) {
  28099. this.onDisposeObservable.remove(this._onDisposeObserver);
  28100. }
  28101. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28102. },
  28103. enumerable: true,
  28104. configurable: true
  28105. });
  28106. Object.defineProperty(Material.prototype, "onBind", {
  28107. set: function (callback) {
  28108. if (this._onBindObserver) {
  28109. this.onBindObservable.remove(this._onBindObserver);
  28110. }
  28111. this._onBindObserver = this.onBindObservable.add(callback);
  28112. },
  28113. enumerable: true,
  28114. configurable: true
  28115. });
  28116. Object.defineProperty(Material.prototype, "alphaMode", {
  28117. get: function () {
  28118. return this._alphaMode;
  28119. },
  28120. set: function (value) {
  28121. if (this._alphaMode === value) {
  28122. return;
  28123. }
  28124. this._alphaMode = value;
  28125. this.markAsDirty(Material.TextureDirtyFlag);
  28126. },
  28127. enumerable: true,
  28128. configurable: true
  28129. });
  28130. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28131. get: function () {
  28132. return this._needDepthPrePass;
  28133. },
  28134. set: function (value) {
  28135. if (this._needDepthPrePass === value) {
  28136. return;
  28137. }
  28138. this._needDepthPrePass = value;
  28139. if (this._needDepthPrePass) {
  28140. this.checkReadyOnEveryCall = true;
  28141. }
  28142. },
  28143. enumerable: true,
  28144. configurable: true
  28145. });
  28146. Object.defineProperty(Material.prototype, "fogEnabled", {
  28147. get: function () {
  28148. return this._fogEnabled;
  28149. },
  28150. set: function (value) {
  28151. if (this._fogEnabled === value) {
  28152. return;
  28153. }
  28154. this._fogEnabled = value;
  28155. this.markAsDirty(Material.MiscDirtyFlag);
  28156. },
  28157. enumerable: true,
  28158. configurable: true
  28159. });
  28160. Object.defineProperty(Material.prototype, "wireframe", {
  28161. get: function () {
  28162. return this._fillMode === Material.WireFrameFillMode;
  28163. },
  28164. set: function (value) {
  28165. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28166. },
  28167. enumerable: true,
  28168. configurable: true
  28169. });
  28170. Object.defineProperty(Material.prototype, "pointsCloud", {
  28171. get: function () {
  28172. return this._fillMode === Material.PointFillMode;
  28173. },
  28174. set: function (value) {
  28175. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28176. },
  28177. enumerable: true,
  28178. configurable: true
  28179. });
  28180. Object.defineProperty(Material.prototype, "fillMode", {
  28181. get: function () {
  28182. return this._fillMode;
  28183. },
  28184. set: function (value) {
  28185. if (this._fillMode === value) {
  28186. return;
  28187. }
  28188. this._fillMode = value;
  28189. this.markAsDirty(Material.MiscDirtyFlag);
  28190. },
  28191. enumerable: true,
  28192. configurable: true
  28193. });
  28194. /**
  28195. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28196. * subclasses should override adding information pertainent to themselves
  28197. */
  28198. Material.prototype.toString = function (fullDetails) {
  28199. var ret = "Name: " + this.name;
  28200. if (fullDetails) {
  28201. }
  28202. return ret;
  28203. };
  28204. /**
  28205. * Child classes can use it to update shaders
  28206. */
  28207. Material.prototype.getClassName = function () {
  28208. return "Material";
  28209. };
  28210. Object.defineProperty(Material.prototype, "isFrozen", {
  28211. get: function () {
  28212. return this.checkReadyOnlyOnce;
  28213. },
  28214. enumerable: true,
  28215. configurable: true
  28216. });
  28217. Material.prototype.freeze = function () {
  28218. this.checkReadyOnlyOnce = true;
  28219. };
  28220. Material.prototype.unfreeze = function () {
  28221. this.checkReadyOnlyOnce = false;
  28222. };
  28223. Material.prototype.isReady = function (mesh, useInstances) {
  28224. return true;
  28225. };
  28226. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28227. return false;
  28228. };
  28229. Material.prototype.getEffect = function () {
  28230. return this._effect;
  28231. };
  28232. Material.prototype.getScene = function () {
  28233. return this._scene;
  28234. };
  28235. Material.prototype.needAlphaBlending = function () {
  28236. return (this.alpha < 1.0);
  28237. };
  28238. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28239. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28240. };
  28241. Material.prototype.needAlphaTesting = function () {
  28242. return false;
  28243. };
  28244. Material.prototype.getAlphaTestTexture = function () {
  28245. return null;
  28246. };
  28247. Material.prototype.markDirty = function () {
  28248. this._wasPreviouslyReady = false;
  28249. };
  28250. Material.prototype._preBind = function (effect, overrideOrientation) {
  28251. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28252. var engine = this._scene.getEngine();
  28253. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28254. var reverse = orientation === Material.ClockWiseSideOrientation;
  28255. engine.enableEffect(effect ? effect : this._effect);
  28256. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28257. return reverse;
  28258. };
  28259. Material.prototype.bind = function (world, mesh) {
  28260. };
  28261. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28262. };
  28263. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28264. };
  28265. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28266. sceneUbo.bindToEffect(effect, "Scene");
  28267. };
  28268. Material.prototype.bindView = function (effect) {
  28269. if (!this._useUBO) {
  28270. effect.setMatrix("view", this.getScene().getViewMatrix());
  28271. }
  28272. else {
  28273. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28274. }
  28275. };
  28276. Material.prototype.bindViewProjection = function (effect) {
  28277. if (!this._useUBO) {
  28278. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28279. }
  28280. else {
  28281. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28282. }
  28283. };
  28284. Material.prototype._afterBind = function (mesh) {
  28285. this._scene._cachedMaterial = this;
  28286. if (mesh) {
  28287. this._scene._cachedVisibility = mesh.visibility;
  28288. }
  28289. else {
  28290. this._scene._cachedVisibility = 1;
  28291. }
  28292. if (mesh) {
  28293. this.onBindObservable.notifyObservers(mesh);
  28294. }
  28295. if (this.disableDepthWrite) {
  28296. var engine = this._scene.getEngine();
  28297. this._cachedDepthWriteState = engine.getDepthWrite();
  28298. engine.setDepthWrite(false);
  28299. }
  28300. };
  28301. Material.prototype.unbind = function () {
  28302. this.onUnBindObservable.notifyObservers(this);
  28303. if (this.disableDepthWrite) {
  28304. var engine = this._scene.getEngine();
  28305. engine.setDepthWrite(this._cachedDepthWriteState);
  28306. }
  28307. };
  28308. Material.prototype.getActiveTextures = function () {
  28309. return [];
  28310. };
  28311. Material.prototype.hasTexture = function (texture) {
  28312. return false;
  28313. };
  28314. Material.prototype.clone = function (name) {
  28315. return null;
  28316. };
  28317. Material.prototype.getBindedMeshes = function () {
  28318. var result = new Array();
  28319. for (var index = 0; index < this._scene.meshes.length; index++) {
  28320. var mesh = this._scene.meshes[index];
  28321. if (mesh.material === this) {
  28322. result.push(mesh);
  28323. }
  28324. }
  28325. return result;
  28326. };
  28327. /**
  28328. * Force shader compilation including textures ready check
  28329. */
  28330. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28331. var _this = this;
  28332. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28333. var subMesh = new BABYLON.BaseSubMesh();
  28334. var scene = this.getScene();
  28335. var engine = scene.getEngine();
  28336. var checkReady = function () {
  28337. if (!_this._scene || !_this._scene.getEngine()) {
  28338. return;
  28339. }
  28340. if (subMesh._materialDefines) {
  28341. subMesh._materialDefines._renderId = -1;
  28342. }
  28343. var alphaTestState = engine.getAlphaTesting();
  28344. var clipPlaneState = scene.clipPlane;
  28345. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28346. if (localOptions.clipPlane) {
  28347. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28348. }
  28349. if (_this.storeEffectOnSubMeshes) {
  28350. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28351. if (onCompiled) {
  28352. onCompiled(_this);
  28353. }
  28354. }
  28355. else {
  28356. setTimeout(checkReady, 16);
  28357. }
  28358. }
  28359. else {
  28360. if (_this.isReady(mesh)) {
  28361. if (onCompiled) {
  28362. onCompiled(_this);
  28363. }
  28364. }
  28365. else {
  28366. setTimeout(checkReady, 16);
  28367. }
  28368. }
  28369. engine.setAlphaTesting(alphaTestState);
  28370. if (options && options.clipPlane) {
  28371. scene.clipPlane = clipPlaneState;
  28372. }
  28373. };
  28374. checkReady();
  28375. };
  28376. Material.prototype.markAsDirty = function (flag) {
  28377. if (flag & Material.TextureDirtyFlag) {
  28378. this._markAllSubMeshesAsTexturesDirty();
  28379. }
  28380. if (flag & Material.LightDirtyFlag) {
  28381. this._markAllSubMeshesAsLightsDirty();
  28382. }
  28383. if (flag & Material.FresnelDirtyFlag) {
  28384. this._markAllSubMeshesAsFresnelDirty();
  28385. }
  28386. if (flag & Material.AttributesDirtyFlag) {
  28387. this._markAllSubMeshesAsAttributesDirty();
  28388. }
  28389. if (flag & Material.MiscDirtyFlag) {
  28390. this._markAllSubMeshesAsMiscDirty();
  28391. }
  28392. this.getScene().resetCachedMaterial();
  28393. };
  28394. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28395. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28396. var mesh = _a[_i];
  28397. if (!mesh.subMeshes) {
  28398. continue;
  28399. }
  28400. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28401. var subMesh = _c[_b];
  28402. if (subMesh.getMaterial() !== this) {
  28403. continue;
  28404. }
  28405. if (!subMesh._materialDefines) {
  28406. continue;
  28407. }
  28408. func(subMesh._materialDefines);
  28409. }
  28410. }
  28411. };
  28412. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28413. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28414. };
  28415. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28416. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28417. };
  28418. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28419. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28420. };
  28421. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28422. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28423. };
  28424. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28425. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28426. };
  28427. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28428. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28429. };
  28430. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28431. // Animations
  28432. this.getScene().stopAnimation(this);
  28433. // Remove from scene
  28434. var index = this._scene.materials.indexOf(this);
  28435. if (index >= 0) {
  28436. this._scene.materials.splice(index, 1);
  28437. }
  28438. // Remove from meshes
  28439. for (index = 0; index < this._scene.meshes.length; index++) {
  28440. var mesh = this._scene.meshes[index];
  28441. if (mesh.material === this) {
  28442. mesh.material = null;
  28443. if (mesh.geometry) {
  28444. var geometry = (mesh.geometry);
  28445. if (this.storeEffectOnSubMeshes) {
  28446. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28447. var subMesh = _a[_i];
  28448. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28449. if (forceDisposeEffect && subMesh._materialEffect) {
  28450. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28451. }
  28452. }
  28453. }
  28454. else {
  28455. geometry._releaseVertexArrayObject(this._effect);
  28456. }
  28457. }
  28458. }
  28459. }
  28460. this._uniformBuffer.dispose();
  28461. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28462. if (forceDisposeEffect && this._effect) {
  28463. if (!this.storeEffectOnSubMeshes) {
  28464. this._scene.getEngine()._releaseEffect(this._effect);
  28465. }
  28466. this._effect = null;
  28467. }
  28468. // Callback
  28469. this.onDisposeObservable.notifyObservers(this);
  28470. this.onDisposeObservable.clear();
  28471. this.onBindObservable.clear();
  28472. this.onUnBindObservable.clear();
  28473. };
  28474. Material.prototype.serialize = function () {
  28475. return BABYLON.SerializationHelper.Serialize(this);
  28476. };
  28477. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28478. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28479. multiMaterial.id = parsedMultiMaterial.id;
  28480. if (BABYLON.Tags) {
  28481. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28482. }
  28483. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28484. var subMatId = parsedMultiMaterial.materials[matIndex];
  28485. if (subMatId) {
  28486. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28487. }
  28488. else {
  28489. multiMaterial.subMaterials.push(null);
  28490. }
  28491. }
  28492. return multiMaterial;
  28493. };
  28494. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28495. if (!parsedMaterial.customType) {
  28496. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28497. }
  28498. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28499. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28500. if (!BABYLON.LegacyPBRMaterial) {
  28501. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28502. return;
  28503. }
  28504. }
  28505. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28506. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28507. ;
  28508. };
  28509. // Triangle views
  28510. Material._TriangleFillMode = 0;
  28511. Material._WireFrameFillMode = 1;
  28512. Material._PointFillMode = 2;
  28513. // Draw modes
  28514. Material._PointListDrawMode = 3;
  28515. Material._LineListDrawMode = 4;
  28516. Material._LineLoopDrawMode = 5;
  28517. Material._LineStripDrawMode = 6;
  28518. Material._TriangleStripDrawMode = 7;
  28519. Material._TriangleFanDrawMode = 8;
  28520. Material._ClockWiseSideOrientation = 0;
  28521. Material._CounterClockWiseSideOrientation = 1;
  28522. Material._TextureDirtyFlag = 1;
  28523. Material._LightDirtyFlag = 2;
  28524. Material._FresnelDirtyFlag = 4;
  28525. Material._AttributesDirtyFlag = 8;
  28526. Material._MiscDirtyFlag = 16;
  28527. __decorate([
  28528. BABYLON.serialize()
  28529. ], Material.prototype, "id", void 0);
  28530. __decorate([
  28531. BABYLON.serialize()
  28532. ], Material.prototype, "name", void 0);
  28533. __decorate([
  28534. BABYLON.serialize()
  28535. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28536. __decorate([
  28537. BABYLON.serialize()
  28538. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28539. __decorate([
  28540. BABYLON.serialize()
  28541. ], Material.prototype, "state", void 0);
  28542. __decorate([
  28543. BABYLON.serialize()
  28544. ], Material.prototype, "alpha", void 0);
  28545. __decorate([
  28546. BABYLON.serialize("backFaceCulling")
  28547. ], Material.prototype, "_backFaceCulling", void 0);
  28548. __decorate([
  28549. BABYLON.serialize()
  28550. ], Material.prototype, "sideOrientation", void 0);
  28551. __decorate([
  28552. BABYLON.serialize("alphaMode")
  28553. ], Material.prototype, "_alphaMode", void 0);
  28554. __decorate([
  28555. BABYLON.serialize()
  28556. ], Material.prototype, "_needDepthPrePass", void 0);
  28557. __decorate([
  28558. BABYLON.serialize()
  28559. ], Material.prototype, "disableDepthWrite", void 0);
  28560. __decorate([
  28561. BABYLON.serialize()
  28562. ], Material.prototype, "forceDepthWrite", void 0);
  28563. __decorate([
  28564. BABYLON.serialize()
  28565. ], Material.prototype, "separateCullingPass", void 0);
  28566. __decorate([
  28567. BABYLON.serialize("fogEnabled")
  28568. ], Material.prototype, "_fogEnabled", void 0);
  28569. __decorate([
  28570. BABYLON.serialize()
  28571. ], Material.prototype, "pointSize", void 0);
  28572. __decorate([
  28573. BABYLON.serialize()
  28574. ], Material.prototype, "zOffset", void 0);
  28575. __decorate([
  28576. BABYLON.serialize()
  28577. ], Material.prototype, "wireframe", null);
  28578. __decorate([
  28579. BABYLON.serialize()
  28580. ], Material.prototype, "pointsCloud", null);
  28581. __decorate([
  28582. BABYLON.serialize()
  28583. ], Material.prototype, "fillMode", null);
  28584. return Material;
  28585. }());
  28586. BABYLON.Material = Material;
  28587. })(BABYLON || (BABYLON = {}));
  28588. //# sourceMappingURL=babylon.material.js.map
  28589. var BABYLON;
  28590. (function (BABYLON) {
  28591. var UniformBuffer = /** @class */ (function () {
  28592. /**
  28593. * Uniform buffer objects.
  28594. *
  28595. * Handles blocks of uniform on the GPU.
  28596. *
  28597. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28598. *
  28599. * For more information, please refer to :
  28600. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28601. */
  28602. function UniformBuffer(engine, data, dynamic) {
  28603. this._engine = engine;
  28604. this._noUBO = !engine.supportsUniformBuffers;
  28605. this._dynamic = dynamic;
  28606. this._data = data || [];
  28607. this._uniformLocations = {};
  28608. this._uniformSizes = {};
  28609. this._uniformLocationPointer = 0;
  28610. this._needSync = false;
  28611. if (this._noUBO) {
  28612. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28613. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28614. this.updateFloat = this._updateFloatForEffect;
  28615. this.updateFloat2 = this._updateFloat2ForEffect;
  28616. this.updateFloat3 = this._updateFloat3ForEffect;
  28617. this.updateFloat4 = this._updateFloat4ForEffect;
  28618. this.updateMatrix = this._updateMatrixForEffect;
  28619. this.updateVector3 = this._updateVector3ForEffect;
  28620. this.updateVector4 = this._updateVector4ForEffect;
  28621. this.updateColor3 = this._updateColor3ForEffect;
  28622. this.updateColor4 = this._updateColor4ForEffect;
  28623. }
  28624. else {
  28625. this._engine._uniformBuffers.push(this);
  28626. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28627. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28628. this.updateFloat = this._updateFloatForUniform;
  28629. this.updateFloat2 = this._updateFloat2ForUniform;
  28630. this.updateFloat3 = this._updateFloat3ForUniform;
  28631. this.updateFloat4 = this._updateFloat4ForUniform;
  28632. this.updateMatrix = this._updateMatrixForUniform;
  28633. this.updateVector3 = this._updateVector3ForUniform;
  28634. this.updateVector4 = this._updateVector4ForUniform;
  28635. this.updateColor3 = this._updateColor3ForUniform;
  28636. this.updateColor4 = this._updateColor4ForUniform;
  28637. }
  28638. }
  28639. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28640. // Properties
  28641. /**
  28642. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28643. * or just falling back on setUniformXXX calls.
  28644. */
  28645. get: function () {
  28646. return !this._noUBO;
  28647. },
  28648. enumerable: true,
  28649. configurable: true
  28650. });
  28651. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28652. /**
  28653. * Indicates if the WebGL underlying uniform buffer is in sync
  28654. * with the javascript cache data.
  28655. */
  28656. get: function () {
  28657. return !this._needSync;
  28658. },
  28659. enumerable: true,
  28660. configurable: true
  28661. });
  28662. /**
  28663. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28664. * Also, a dynamic UniformBuffer will disable cache verification and always
  28665. * update the underlying WebGL uniform buffer to the GPU.
  28666. */
  28667. UniformBuffer.prototype.isDynamic = function () {
  28668. return this._dynamic !== undefined;
  28669. };
  28670. /**
  28671. * The data cache on JS side.
  28672. */
  28673. UniformBuffer.prototype.getData = function () {
  28674. return this._bufferData;
  28675. };
  28676. /**
  28677. * The underlying WebGL Uniform buffer.
  28678. */
  28679. UniformBuffer.prototype.getBuffer = function () {
  28680. return this._buffer;
  28681. };
  28682. /**
  28683. * std140 layout specifies how to align data within an UBO structure.
  28684. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28685. * for specs.
  28686. */
  28687. UniformBuffer.prototype._fillAlignment = function (size) {
  28688. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28689. // and 4x4 matrices
  28690. // TODO : change if other types are used
  28691. var alignment;
  28692. if (size <= 2) {
  28693. alignment = size;
  28694. }
  28695. else {
  28696. alignment = 4;
  28697. }
  28698. if ((this._uniformLocationPointer % alignment) !== 0) {
  28699. var oldPointer = this._uniformLocationPointer;
  28700. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28701. var diff = this._uniformLocationPointer - oldPointer;
  28702. for (var i = 0; i < diff; i++) {
  28703. this._data.push(0);
  28704. }
  28705. }
  28706. };
  28707. /**
  28708. * Adds an uniform in the buffer.
  28709. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28710. * for the layout to be correct !
  28711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28712. * @param {number|number[]} size Data size, or data directly.
  28713. */
  28714. UniformBuffer.prototype.addUniform = function (name, size) {
  28715. if (this._noUBO) {
  28716. return;
  28717. }
  28718. if (this._uniformLocations[name] !== undefined) {
  28719. // Already existing uniform
  28720. return;
  28721. }
  28722. // This function must be called in the order of the shader layout !
  28723. // size can be the size of the uniform, or data directly
  28724. var data;
  28725. if (size instanceof Array) {
  28726. data = size;
  28727. size = data.length;
  28728. }
  28729. else {
  28730. size = size;
  28731. data = [];
  28732. // Fill with zeros
  28733. for (var i = 0; i < size; i++) {
  28734. data.push(0);
  28735. }
  28736. }
  28737. this._fillAlignment(size);
  28738. this._uniformSizes[name] = size;
  28739. this._uniformLocations[name] = this._uniformLocationPointer;
  28740. this._uniformLocationPointer += size;
  28741. for (var i = 0; i < size; i++) {
  28742. this._data.push(data[i]);
  28743. }
  28744. this._needSync = true;
  28745. };
  28746. /**
  28747. * Wrapper for addUniform.
  28748. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28749. * @param {Matrix} mat A 4x4 matrix.
  28750. */
  28751. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28752. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28753. };
  28754. /**
  28755. * Wrapper for addUniform.
  28756. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28757. * @param {number} x
  28758. * @param {number} y
  28759. */
  28760. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28761. var temp = [x, y];
  28762. this.addUniform(name, temp);
  28763. };
  28764. /**
  28765. * Wrapper for addUniform.
  28766. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28767. * @param {number} x
  28768. * @param {number} y
  28769. * @param {number} z
  28770. */
  28771. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28772. var temp = [x, y, z];
  28773. this.addUniform(name, temp);
  28774. };
  28775. /**
  28776. * Wrapper for addUniform.
  28777. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28778. * @param {Color3} color
  28779. */
  28780. UniformBuffer.prototype.addColor3 = function (name, color) {
  28781. var temp = new Array();
  28782. color.toArray(temp);
  28783. this.addUniform(name, temp);
  28784. };
  28785. /**
  28786. * Wrapper for addUniform.
  28787. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28788. * @param {Color3} color
  28789. * @param {number} alpha
  28790. */
  28791. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28792. var temp = new Array();
  28793. color.toArray(temp);
  28794. temp.push(alpha);
  28795. this.addUniform(name, temp);
  28796. };
  28797. /**
  28798. * Wrapper for addUniform.
  28799. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28800. * @param {Vector3} vector
  28801. */
  28802. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28803. var temp = new Array();
  28804. vector.toArray(temp);
  28805. this.addUniform(name, temp);
  28806. };
  28807. /**
  28808. * Wrapper for addUniform.
  28809. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28810. */
  28811. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28812. this.addUniform(name, 12);
  28813. };
  28814. /**
  28815. * Wrapper for addUniform.
  28816. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28817. */
  28818. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28819. this.addUniform(name, 8);
  28820. };
  28821. /**
  28822. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28823. */
  28824. UniformBuffer.prototype.create = function () {
  28825. if (this._noUBO) {
  28826. return;
  28827. }
  28828. if (this._buffer) {
  28829. return; // nothing to do
  28830. }
  28831. // See spec, alignment must be filled as a vec4
  28832. this._fillAlignment(4);
  28833. this._bufferData = new Float32Array(this._data);
  28834. this._rebuild();
  28835. this._needSync = true;
  28836. };
  28837. UniformBuffer.prototype._rebuild = function () {
  28838. if (this._noUBO) {
  28839. return;
  28840. }
  28841. if (this._dynamic) {
  28842. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28843. }
  28844. else {
  28845. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28846. }
  28847. };
  28848. /**
  28849. * Updates the WebGL Uniform Buffer on the GPU.
  28850. * If the `dynamic` flag is set to true, no cache comparison is done.
  28851. * Otherwise, the buffer will be updated only if the cache differs.
  28852. */
  28853. UniformBuffer.prototype.update = function () {
  28854. if (!this._buffer) {
  28855. this.create();
  28856. return;
  28857. }
  28858. if (!this._dynamic && !this._needSync) {
  28859. return;
  28860. }
  28861. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28862. this._needSync = false;
  28863. };
  28864. /**
  28865. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28866. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28867. * @param {number[]|Float32Array} data Flattened data
  28868. * @param {number} size Size of the data.
  28869. */
  28870. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28871. var location = this._uniformLocations[uniformName];
  28872. if (location === undefined) {
  28873. if (this._buffer) {
  28874. // Cannot add an uniform if the buffer is already created
  28875. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28876. return;
  28877. }
  28878. this.addUniform(uniformName, size);
  28879. location = this._uniformLocations[uniformName];
  28880. }
  28881. if (!this._buffer) {
  28882. this.create();
  28883. }
  28884. if (!this._dynamic) {
  28885. // Cache for static uniform buffers
  28886. var changed = false;
  28887. for (var i = 0; i < size; i++) {
  28888. if (this._bufferData[location + i] !== data[i]) {
  28889. changed = true;
  28890. this._bufferData[location + i] = data[i];
  28891. }
  28892. }
  28893. this._needSync = this._needSync || changed;
  28894. }
  28895. else {
  28896. // No cache for dynamic
  28897. for (var i = 0; i < size; i++) {
  28898. this._bufferData[location + i] = data[i];
  28899. }
  28900. }
  28901. };
  28902. // Update methods
  28903. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28904. // To match std140, matrix must be realigned
  28905. for (var i = 0; i < 3; i++) {
  28906. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28907. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28908. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28909. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28910. }
  28911. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28912. };
  28913. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28914. this._currentEffect.setMatrix3x3(name, matrix);
  28915. };
  28916. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28917. this._currentEffect.setMatrix2x2(name, matrix);
  28918. };
  28919. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28920. // To match std140, matrix must be realigned
  28921. for (var i = 0; i < 2; i++) {
  28922. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28923. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28924. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28925. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28926. }
  28927. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28928. };
  28929. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28930. this._currentEffect.setFloat(name, x);
  28931. };
  28932. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28933. UniformBuffer._tempBuffer[0] = x;
  28934. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28935. };
  28936. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28937. if (suffix === void 0) { suffix = ""; }
  28938. this._currentEffect.setFloat2(name + suffix, x, y);
  28939. };
  28940. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28941. if (suffix === void 0) { suffix = ""; }
  28942. UniformBuffer._tempBuffer[0] = x;
  28943. UniformBuffer._tempBuffer[1] = y;
  28944. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28945. };
  28946. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28947. if (suffix === void 0) { suffix = ""; }
  28948. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28949. };
  28950. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28951. if (suffix === void 0) { suffix = ""; }
  28952. UniformBuffer._tempBuffer[0] = x;
  28953. UniformBuffer._tempBuffer[1] = y;
  28954. UniformBuffer._tempBuffer[2] = z;
  28955. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28956. };
  28957. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28958. if (suffix === void 0) { suffix = ""; }
  28959. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28960. };
  28961. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28962. if (suffix === void 0) { suffix = ""; }
  28963. UniformBuffer._tempBuffer[0] = x;
  28964. UniformBuffer._tempBuffer[1] = y;
  28965. UniformBuffer._tempBuffer[2] = z;
  28966. UniformBuffer._tempBuffer[3] = w;
  28967. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28968. };
  28969. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28970. this._currentEffect.setMatrix(name, mat);
  28971. };
  28972. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28973. this.updateUniform(name, mat.toArray(), 16);
  28974. };
  28975. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28976. this._currentEffect.setVector3(name, vector);
  28977. };
  28978. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28979. vector.toArray(UniformBuffer._tempBuffer);
  28980. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28981. };
  28982. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28983. this._currentEffect.setVector4(name, vector);
  28984. };
  28985. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28986. vector.toArray(UniformBuffer._tempBuffer);
  28987. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28988. };
  28989. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28990. if (suffix === void 0) { suffix = ""; }
  28991. this._currentEffect.setColor3(name + suffix, color);
  28992. };
  28993. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28994. if (suffix === void 0) { suffix = ""; }
  28995. color.toArray(UniformBuffer._tempBuffer);
  28996. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28997. };
  28998. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28999. if (suffix === void 0) { suffix = ""; }
  29000. this._currentEffect.setColor4(name + suffix, color, alpha);
  29001. };
  29002. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29003. if (suffix === void 0) { suffix = ""; }
  29004. color.toArray(UniformBuffer._tempBuffer);
  29005. UniformBuffer._tempBuffer[3] = alpha;
  29006. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29007. };
  29008. /**
  29009. * Sets a sampler uniform on the effect.
  29010. * @param {string} name Name of the sampler.
  29011. * @param {Texture} texture
  29012. */
  29013. UniformBuffer.prototype.setTexture = function (name, texture) {
  29014. this._currentEffect.setTexture(name, texture);
  29015. };
  29016. /**
  29017. * Directly updates the value of the uniform in the cache AND on the GPU.
  29018. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29019. * @param {number[]|Float32Array} data Flattened data
  29020. */
  29021. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29022. this.updateUniform(uniformName, data, data.length);
  29023. this.update();
  29024. };
  29025. /**
  29026. * Binds this uniform buffer to an effect.
  29027. * @param {Effect} effect
  29028. * @param {string} name Name of the uniform block in the shader.
  29029. */
  29030. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29031. this._currentEffect = effect;
  29032. if (this._noUBO || !this._buffer) {
  29033. return;
  29034. }
  29035. effect.bindUniformBuffer(this._buffer, name);
  29036. };
  29037. /**
  29038. * Disposes the uniform buffer.
  29039. */
  29040. UniformBuffer.prototype.dispose = function () {
  29041. if (this._noUBO) {
  29042. return;
  29043. }
  29044. var index = this._engine._uniformBuffers.indexOf(this);
  29045. if (index !== -1) {
  29046. this._engine._uniformBuffers.splice(index, 1);
  29047. }
  29048. if (!this._buffer) {
  29049. return;
  29050. }
  29051. if (this._engine._releaseBuffer(this._buffer)) {
  29052. this._buffer = null;
  29053. }
  29054. };
  29055. // Pool for avoiding memory leaks
  29056. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29057. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29058. return UniformBuffer;
  29059. }());
  29060. BABYLON.UniformBuffer = UniformBuffer;
  29061. })(BABYLON || (BABYLON = {}));
  29062. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29063. var BABYLON;
  29064. (function (BABYLON) {
  29065. var VertexData = /** @class */ (function () {
  29066. function VertexData() {
  29067. }
  29068. VertexData.prototype.set = function (data, kind) {
  29069. switch (kind) {
  29070. case BABYLON.VertexBuffer.PositionKind:
  29071. this.positions = data;
  29072. break;
  29073. case BABYLON.VertexBuffer.NormalKind:
  29074. this.normals = data;
  29075. break;
  29076. case BABYLON.VertexBuffer.TangentKind:
  29077. this.tangents = data;
  29078. break;
  29079. case BABYLON.VertexBuffer.UVKind:
  29080. this.uvs = data;
  29081. break;
  29082. case BABYLON.VertexBuffer.UV2Kind:
  29083. this.uvs2 = data;
  29084. break;
  29085. case BABYLON.VertexBuffer.UV3Kind:
  29086. this.uvs3 = data;
  29087. break;
  29088. case BABYLON.VertexBuffer.UV4Kind:
  29089. this.uvs4 = data;
  29090. break;
  29091. case BABYLON.VertexBuffer.UV5Kind:
  29092. this.uvs5 = data;
  29093. break;
  29094. case BABYLON.VertexBuffer.UV6Kind:
  29095. this.uvs6 = data;
  29096. break;
  29097. case BABYLON.VertexBuffer.ColorKind:
  29098. this.colors = data;
  29099. break;
  29100. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29101. this.matricesIndices = data;
  29102. break;
  29103. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29104. this.matricesWeights = data;
  29105. break;
  29106. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29107. this.matricesIndicesExtra = data;
  29108. break;
  29109. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29110. this.matricesWeightsExtra = data;
  29111. break;
  29112. }
  29113. };
  29114. /**
  29115. * Associates the vertexData to the passed Mesh.
  29116. * Sets it as updatable or not (default `false`).
  29117. * Returns the VertexData.
  29118. */
  29119. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29120. this._applyTo(mesh, updatable);
  29121. return this;
  29122. };
  29123. /**
  29124. * Associates the vertexData to the passed Geometry.
  29125. * Sets it as updatable or not (default `false`).
  29126. * Returns the VertexData.
  29127. */
  29128. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29129. this._applyTo(geometry, updatable);
  29130. return this;
  29131. };
  29132. /**
  29133. * Updates the associated mesh.
  29134. * Returns the VertexData.
  29135. */
  29136. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29137. this._update(mesh);
  29138. return this;
  29139. };
  29140. /**
  29141. * Updates the associated geometry.
  29142. * Returns the VertexData.
  29143. */
  29144. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29145. this._update(geometry);
  29146. return this;
  29147. };
  29148. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29149. if (updatable === void 0) { updatable = false; }
  29150. if (this.positions) {
  29151. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29152. }
  29153. if (this.normals) {
  29154. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29155. }
  29156. if (this.tangents) {
  29157. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29158. }
  29159. if (this.uvs) {
  29160. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29161. }
  29162. if (this.uvs2) {
  29163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29164. }
  29165. if (this.uvs3) {
  29166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29167. }
  29168. if (this.uvs4) {
  29169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29170. }
  29171. if (this.uvs5) {
  29172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29173. }
  29174. if (this.uvs6) {
  29175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29176. }
  29177. if (this.colors) {
  29178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29179. }
  29180. if (this.matricesIndices) {
  29181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29182. }
  29183. if (this.matricesWeights) {
  29184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29185. }
  29186. if (this.matricesIndicesExtra) {
  29187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29188. }
  29189. if (this.matricesWeightsExtra) {
  29190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29191. }
  29192. if (this.indices) {
  29193. meshOrGeometry.setIndices(this.indices, null, updatable);
  29194. }
  29195. return this;
  29196. };
  29197. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29198. if (this.positions) {
  29199. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29200. }
  29201. if (this.normals) {
  29202. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29203. }
  29204. if (this.tangents) {
  29205. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29206. }
  29207. if (this.uvs) {
  29208. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29209. }
  29210. if (this.uvs2) {
  29211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29212. }
  29213. if (this.uvs3) {
  29214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29215. }
  29216. if (this.uvs4) {
  29217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29218. }
  29219. if (this.uvs5) {
  29220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29221. }
  29222. if (this.uvs6) {
  29223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29224. }
  29225. if (this.colors) {
  29226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29227. }
  29228. if (this.matricesIndices) {
  29229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29230. }
  29231. if (this.matricesWeights) {
  29232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29233. }
  29234. if (this.matricesIndicesExtra) {
  29235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29236. }
  29237. if (this.matricesWeightsExtra) {
  29238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29239. }
  29240. if (this.indices) {
  29241. meshOrGeometry.setIndices(this.indices, null);
  29242. }
  29243. return this;
  29244. };
  29245. /**
  29246. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29247. * Returns the VertexData.
  29248. */
  29249. VertexData.prototype.transform = function (matrix) {
  29250. var transformed = BABYLON.Vector3.Zero();
  29251. var index;
  29252. if (this.positions) {
  29253. var position = BABYLON.Vector3.Zero();
  29254. for (index = 0; index < this.positions.length; index += 3) {
  29255. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29256. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29257. this.positions[index] = transformed.x;
  29258. this.positions[index + 1] = transformed.y;
  29259. this.positions[index + 2] = transformed.z;
  29260. }
  29261. }
  29262. if (this.normals) {
  29263. var normal = BABYLON.Vector3.Zero();
  29264. for (index = 0; index < this.normals.length; index += 3) {
  29265. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29266. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29267. this.normals[index] = transformed.x;
  29268. this.normals[index + 1] = transformed.y;
  29269. this.normals[index + 2] = transformed.z;
  29270. }
  29271. }
  29272. if (this.tangents) {
  29273. var tangent = BABYLON.Vector4.Zero();
  29274. var tangentTransformed = BABYLON.Vector4.Zero();
  29275. for (index = 0; index < this.tangents.length; index += 4) {
  29276. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29277. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29278. this.tangents[index] = tangentTransformed.x;
  29279. this.tangents[index + 1] = tangentTransformed.y;
  29280. this.tangents[index + 2] = tangentTransformed.z;
  29281. this.tangents[index + 3] = tangentTransformed.w;
  29282. }
  29283. }
  29284. return this;
  29285. };
  29286. /**
  29287. * Merges the passed VertexData into the current one.
  29288. * Returns the modified VertexData.
  29289. */
  29290. VertexData.prototype.merge = function (other, options) {
  29291. options = options || {};
  29292. if (other.indices) {
  29293. if (!this.indices) {
  29294. this.indices = [];
  29295. }
  29296. var offset = this.positions ? this.positions.length / 3 : 0;
  29297. for (var index = 0; index < other.indices.length; index++) {
  29298. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29299. this.indices.push(other.indices[index] + offset);
  29300. }
  29301. }
  29302. this.positions = this._mergeElement(this.positions, other.positions);
  29303. if (!this.positions) {
  29304. return this;
  29305. }
  29306. var count = this.positions.length / 3;
  29307. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29308. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29309. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29310. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29311. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29312. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29313. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29314. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29315. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29316. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29317. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29318. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29319. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29320. return this;
  29321. };
  29322. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29323. if (length === void 0) { length = 0; }
  29324. if (defaultValue === void 0) { defaultValue = 0; }
  29325. if (!other && !source) {
  29326. return null;
  29327. }
  29328. if (!other) {
  29329. var padding = new Float32Array(source.length);
  29330. padding.fill(defaultValue);
  29331. return this._mergeElement(source, padding, length);
  29332. }
  29333. if (!source) {
  29334. if (length === 0 || length === other.length) {
  29335. return other;
  29336. }
  29337. var padding = new Float32Array(length - other.length);
  29338. padding.fill(defaultValue);
  29339. return this._mergeElement(padding, other, length);
  29340. }
  29341. var len = other.length + source.length;
  29342. var isSrcTypedArray = source instanceof Float32Array;
  29343. var isOthTypedArray = other instanceof Float32Array;
  29344. // use non-loop method when the source is Float32Array
  29345. if (isSrcTypedArray) {
  29346. var ret32 = new Float32Array(len);
  29347. ret32.set(source);
  29348. ret32.set(other, source.length);
  29349. return ret32;
  29350. // source is number[], when other is also use concat
  29351. }
  29352. else if (!isOthTypedArray) {
  29353. return source.concat(other);
  29354. // source is a number[], but other is a Float32Array, loop required
  29355. }
  29356. else {
  29357. var ret = source.slice(0); // copy source to a separate array
  29358. for (var i = 0, len = other.length; i < len; i++) {
  29359. ret.push(other[i]);
  29360. }
  29361. return ret;
  29362. }
  29363. };
  29364. /**
  29365. * Serializes the VertexData.
  29366. * Returns a serialized object.
  29367. */
  29368. VertexData.prototype.serialize = function () {
  29369. var serializationObject = this.serialize();
  29370. if (this.positions) {
  29371. serializationObject.positions = this.positions;
  29372. }
  29373. if (this.normals) {
  29374. serializationObject.normals = this.normals;
  29375. }
  29376. if (this.tangents) {
  29377. serializationObject.tangents = this.tangents;
  29378. }
  29379. if (this.uvs) {
  29380. serializationObject.uvs = this.uvs;
  29381. }
  29382. if (this.uvs2) {
  29383. serializationObject.uvs2 = this.uvs2;
  29384. }
  29385. if (this.uvs3) {
  29386. serializationObject.uvs3 = this.uvs3;
  29387. }
  29388. if (this.uvs4) {
  29389. serializationObject.uvs4 = this.uvs4;
  29390. }
  29391. if (this.uvs5) {
  29392. serializationObject.uvs5 = this.uvs5;
  29393. }
  29394. if (this.uvs6) {
  29395. serializationObject.uvs6 = this.uvs6;
  29396. }
  29397. if (this.colors) {
  29398. serializationObject.colors = this.colors;
  29399. }
  29400. if (this.matricesIndices) {
  29401. serializationObject.matricesIndices = this.matricesIndices;
  29402. serializationObject.matricesIndices._isExpanded = true;
  29403. }
  29404. if (this.matricesWeights) {
  29405. serializationObject.matricesWeights = this.matricesWeights;
  29406. }
  29407. if (this.matricesIndicesExtra) {
  29408. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29409. serializationObject.matricesIndicesExtra._isExpanded = true;
  29410. }
  29411. if (this.matricesWeightsExtra) {
  29412. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29413. }
  29414. serializationObject.indices = this.indices;
  29415. return serializationObject;
  29416. };
  29417. // Statics
  29418. /**
  29419. * Returns the object VertexData associated to the passed mesh.
  29420. */
  29421. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29422. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29423. };
  29424. /**
  29425. * Returns the object VertexData associated to the passed geometry.
  29426. */
  29427. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29428. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29429. };
  29430. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29431. var result = new VertexData();
  29432. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29433. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29434. }
  29435. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29436. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29437. }
  29438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29439. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29440. }
  29441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29442. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29443. }
  29444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29445. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29446. }
  29447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29448. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29449. }
  29450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29451. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29452. }
  29453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29454. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29455. }
  29456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29457. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29458. }
  29459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29460. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29461. }
  29462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29463. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29464. }
  29465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29466. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29467. }
  29468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29469. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29470. }
  29471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29472. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29473. }
  29474. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29475. return result;
  29476. };
  29477. /**
  29478. * Creates the vertexData of the Ribbon.
  29479. */
  29480. VertexData.CreateRibbon = function (options) {
  29481. var pathArray = options.pathArray;
  29482. var closeArray = options.closeArray || false;
  29483. var closePath = options.closePath || false;
  29484. var invertUV = options.invertUV || false;
  29485. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29486. var offset = options.offset || defaultOffset;
  29487. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29488. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29489. var customUV = options.uvs;
  29490. var customColors = options.colors;
  29491. var positions = [];
  29492. var indices = [];
  29493. var normals = [];
  29494. var uvs = [];
  29495. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29496. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29497. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29498. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29499. var minlg; // minimal length among all paths from pathArray
  29500. var lg = []; // array of path lengths : nb of vertex per path
  29501. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29502. var p; // path iterator
  29503. var i; // point iterator
  29504. var j; // point iterator
  29505. // if single path in pathArray
  29506. if (pathArray.length < 2) {
  29507. var ar1 = [];
  29508. var ar2 = [];
  29509. for (i = 0; i < pathArray[0].length - offset; i++) {
  29510. ar1.push(pathArray[0][i]);
  29511. ar2.push(pathArray[0][i + offset]);
  29512. }
  29513. pathArray = [ar1, ar2];
  29514. }
  29515. // positions and horizontal distances (u)
  29516. var idc = 0;
  29517. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29518. var path;
  29519. var l;
  29520. minlg = pathArray[0].length;
  29521. var vectlg;
  29522. var dist;
  29523. for (p = 0; p < pathArray.length; p++) {
  29524. uTotalDistance[p] = 0;
  29525. us[p] = [0];
  29526. path = pathArray[p];
  29527. l = path.length;
  29528. minlg = (minlg < l) ? minlg : l;
  29529. j = 0;
  29530. while (j < l) {
  29531. positions.push(path[j].x, path[j].y, path[j].z);
  29532. if (j > 0) {
  29533. vectlg = path[j].subtract(path[j - 1]).length();
  29534. dist = vectlg + uTotalDistance[p];
  29535. us[p].push(dist);
  29536. uTotalDistance[p] = dist;
  29537. }
  29538. j++;
  29539. }
  29540. if (closePath) {
  29541. j--;
  29542. positions.push(path[0].x, path[0].y, path[0].z);
  29543. vectlg = path[j].subtract(path[0]).length();
  29544. dist = vectlg + uTotalDistance[p];
  29545. us[p].push(dist);
  29546. uTotalDistance[p] = dist;
  29547. }
  29548. lg[p] = l + closePathCorr;
  29549. idx[p] = idc;
  29550. idc += (l + closePathCorr);
  29551. }
  29552. // vertical distances (v)
  29553. var path1;
  29554. var path2;
  29555. var vertex1 = null;
  29556. var vertex2 = null;
  29557. for (i = 0; i < minlg + closePathCorr; i++) {
  29558. vTotalDistance[i] = 0;
  29559. vs[i] = [0];
  29560. for (p = 0; p < pathArray.length - 1; p++) {
  29561. path1 = pathArray[p];
  29562. path2 = pathArray[p + 1];
  29563. if (i === minlg) {
  29564. vertex1 = path1[0];
  29565. vertex2 = path2[0];
  29566. }
  29567. else {
  29568. vertex1 = path1[i];
  29569. vertex2 = path2[i];
  29570. }
  29571. vectlg = vertex2.subtract(vertex1).length();
  29572. dist = vectlg + vTotalDistance[i];
  29573. vs[i].push(dist);
  29574. vTotalDistance[i] = dist;
  29575. }
  29576. if (closeArray && vertex2 && vertex1) {
  29577. path1 = pathArray[p];
  29578. path2 = pathArray[0];
  29579. if (i === minlg) {
  29580. vertex2 = path2[0];
  29581. }
  29582. vectlg = vertex2.subtract(vertex1).length();
  29583. dist = vectlg + vTotalDistance[i];
  29584. vTotalDistance[i] = dist;
  29585. }
  29586. }
  29587. // uvs
  29588. var u;
  29589. var v;
  29590. if (customUV) {
  29591. for (p = 0; p < customUV.length; p++) {
  29592. uvs.push(customUV[p].x, customUV[p].y);
  29593. }
  29594. }
  29595. else {
  29596. for (p = 0; p < pathArray.length; p++) {
  29597. for (i = 0; i < minlg + closePathCorr; i++) {
  29598. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29599. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29600. if (invertUV) {
  29601. uvs.push(v, u);
  29602. }
  29603. else {
  29604. uvs.push(u, v);
  29605. }
  29606. }
  29607. }
  29608. }
  29609. // indices
  29610. p = 0; // path index
  29611. var pi = 0; // positions array index
  29612. var l1 = lg[p] - 1; // path1 length
  29613. var l2 = lg[p + 1] - 1; // path2 length
  29614. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29615. var shft = idx[1] - idx[0]; // shift
  29616. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29617. while (pi <= min && p < path1nb) {
  29618. // 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
  29619. indices.push(pi, pi + shft, pi + 1);
  29620. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29621. pi += 1;
  29622. if (pi === min) {
  29623. p++;
  29624. if (p === lg.length - 1) {
  29625. shft = idx[0] - idx[p];
  29626. l1 = lg[p] - 1;
  29627. l2 = lg[0] - 1;
  29628. }
  29629. else {
  29630. shft = idx[p + 1] - idx[p];
  29631. l1 = lg[p] - 1;
  29632. l2 = lg[p + 1] - 1;
  29633. }
  29634. pi = idx[p];
  29635. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29636. }
  29637. }
  29638. // normals
  29639. VertexData.ComputeNormals(positions, indices, normals);
  29640. if (closePath) {
  29641. var indexFirst = 0;
  29642. var indexLast = 0;
  29643. for (p = 0; p < pathArray.length; p++) {
  29644. indexFirst = idx[p] * 3;
  29645. if (p + 1 < pathArray.length) {
  29646. indexLast = (idx[p + 1] - 1) * 3;
  29647. }
  29648. else {
  29649. indexLast = normals.length - 3;
  29650. }
  29651. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29652. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29653. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29654. normals[indexLast] = normals[indexFirst];
  29655. normals[indexLast + 1] = normals[indexFirst + 1];
  29656. normals[indexLast + 2] = normals[indexFirst + 2];
  29657. }
  29658. }
  29659. // sides
  29660. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29661. // Colors
  29662. var colors = null;
  29663. if (customColors) {
  29664. colors = new Float32Array(customColors.length * 4);
  29665. for (var c = 0; c < customColors.length; c++) {
  29666. colors[c * 4] = customColors[c].r;
  29667. colors[c * 4 + 1] = customColors[c].g;
  29668. colors[c * 4 + 2] = customColors[c].b;
  29669. colors[c * 4 + 3] = customColors[c].a;
  29670. }
  29671. }
  29672. // Result
  29673. var vertexData = new VertexData();
  29674. var positions32 = new Float32Array(positions);
  29675. var normals32 = new Float32Array(normals);
  29676. var uvs32 = new Float32Array(uvs);
  29677. vertexData.indices = indices;
  29678. vertexData.positions = positions32;
  29679. vertexData.normals = normals32;
  29680. vertexData.uvs = uvs32;
  29681. if (colors) {
  29682. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29683. }
  29684. if (closePath) {
  29685. vertexData._idx = idx;
  29686. }
  29687. return vertexData;
  29688. };
  29689. /**
  29690. * Creates the VertexData of the Box.
  29691. */
  29692. VertexData.CreateBox = function (options) {
  29693. var normalsSource = [
  29694. new BABYLON.Vector3(0, 0, 1),
  29695. new BABYLON.Vector3(0, 0, -1),
  29696. new BABYLON.Vector3(1, 0, 0),
  29697. new BABYLON.Vector3(-1, 0, 0),
  29698. new BABYLON.Vector3(0, 1, 0),
  29699. new BABYLON.Vector3(0, -1, 0)
  29700. ];
  29701. var indices = [];
  29702. var positions = [];
  29703. var normals = [];
  29704. var uvs = [];
  29705. var width = options.width || options.size || 1;
  29706. var height = options.height || options.size || 1;
  29707. var depth = options.depth || options.size || 1;
  29708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29709. var faceUV = options.faceUV || new Array(6);
  29710. var faceColors = options.faceColors;
  29711. var colors = [];
  29712. // default face colors and UV if undefined
  29713. for (var f = 0; f < 6; f++) {
  29714. if (faceUV[f] === undefined) {
  29715. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29716. }
  29717. if (faceColors && faceColors[f] === undefined) {
  29718. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29719. }
  29720. }
  29721. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29722. // Create each face in turn.
  29723. for (var index = 0; index < normalsSource.length; index++) {
  29724. var normal = normalsSource[index];
  29725. // Get two vectors perpendicular to the face normal and to each other.
  29726. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29727. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29728. // Six indices (two triangles) per face.
  29729. var verticesLength = positions.length / 3;
  29730. indices.push(verticesLength);
  29731. indices.push(verticesLength + 1);
  29732. indices.push(verticesLength + 2);
  29733. indices.push(verticesLength);
  29734. indices.push(verticesLength + 2);
  29735. indices.push(verticesLength + 3);
  29736. // Four vertices per face.
  29737. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29738. positions.push(vertex.x, vertex.y, vertex.z);
  29739. normals.push(normal.x, normal.y, normal.z);
  29740. uvs.push(faceUV[index].z, faceUV[index].w);
  29741. if (faceColors) {
  29742. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29743. }
  29744. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29745. positions.push(vertex.x, vertex.y, vertex.z);
  29746. normals.push(normal.x, normal.y, normal.z);
  29747. uvs.push(faceUV[index].x, faceUV[index].w);
  29748. if (faceColors) {
  29749. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29750. }
  29751. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29752. positions.push(vertex.x, vertex.y, vertex.z);
  29753. normals.push(normal.x, normal.y, normal.z);
  29754. uvs.push(faceUV[index].x, faceUV[index].y);
  29755. if (faceColors) {
  29756. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29757. }
  29758. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29759. positions.push(vertex.x, vertex.y, vertex.z);
  29760. normals.push(normal.x, normal.y, normal.z);
  29761. uvs.push(faceUV[index].z, faceUV[index].y);
  29762. if (faceColors) {
  29763. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29764. }
  29765. }
  29766. // sides
  29767. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29768. // Result
  29769. var vertexData = new VertexData();
  29770. vertexData.indices = indices;
  29771. vertexData.positions = positions;
  29772. vertexData.normals = normals;
  29773. vertexData.uvs = uvs;
  29774. if (faceColors) {
  29775. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29776. vertexData.colors = totalColors;
  29777. }
  29778. return vertexData;
  29779. };
  29780. /**
  29781. * Creates the VertexData of the Sphere.
  29782. */
  29783. VertexData.CreateSphere = function (options) {
  29784. var segments = options.segments || 32;
  29785. var diameterX = options.diameterX || options.diameter || 1;
  29786. var diameterY = options.diameterY || options.diameter || 1;
  29787. var diameterZ = options.diameterZ || options.diameter || 1;
  29788. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29789. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29790. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29791. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29792. var totalZRotationSteps = 2 + segments;
  29793. var totalYRotationSteps = 2 * totalZRotationSteps;
  29794. var indices = [];
  29795. var positions = [];
  29796. var normals = [];
  29797. var uvs = [];
  29798. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29799. var normalizedZ = zRotationStep / totalZRotationSteps;
  29800. var angleZ = normalizedZ * Math.PI * slice;
  29801. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29802. var normalizedY = yRotationStep / totalYRotationSteps;
  29803. var angleY = normalizedY * Math.PI * 2 * arc;
  29804. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29805. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29806. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29807. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29808. var vertex = complete.multiply(radius);
  29809. var normal = complete.divide(radius).normalize();
  29810. positions.push(vertex.x, vertex.y, vertex.z);
  29811. normals.push(normal.x, normal.y, normal.z);
  29812. uvs.push(normalizedY, normalizedZ);
  29813. }
  29814. if (zRotationStep > 0) {
  29815. var verticesCount = positions.length / 3;
  29816. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29817. indices.push((firstIndex));
  29818. indices.push((firstIndex + 1));
  29819. indices.push(firstIndex + totalYRotationSteps + 1);
  29820. indices.push((firstIndex + totalYRotationSteps + 1));
  29821. indices.push((firstIndex + 1));
  29822. indices.push((firstIndex + totalYRotationSteps + 2));
  29823. }
  29824. }
  29825. }
  29826. // Sides
  29827. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29828. // Result
  29829. var vertexData = new VertexData();
  29830. vertexData.indices = indices;
  29831. vertexData.positions = positions;
  29832. vertexData.normals = normals;
  29833. vertexData.uvs = uvs;
  29834. return vertexData;
  29835. };
  29836. /**
  29837. * Creates the VertexData of the Cylinder or Cone.
  29838. */
  29839. VertexData.CreateCylinder = function (options) {
  29840. var height = options.height || 2;
  29841. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29842. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29843. var tessellation = options.tessellation || 24;
  29844. var subdivisions = options.subdivisions || 1;
  29845. var hasRings = options.hasRings ? true : false;
  29846. var enclose = options.enclose ? true : false;
  29847. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29848. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29849. var faceUV = options.faceUV || new Array(3);
  29850. var faceColors = options.faceColors;
  29851. // default face colors and UV if undefined
  29852. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29853. var ringNb = (hasRings) ? subdivisions : 1;
  29854. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29855. var f;
  29856. for (f = 0; f < surfaceNb; f++) {
  29857. if (faceColors && faceColors[f] === undefined) {
  29858. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29859. }
  29860. }
  29861. for (f = 0; f < surfaceNb; f++) {
  29862. if (faceUV && faceUV[f] === undefined) {
  29863. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29864. }
  29865. }
  29866. var indices = new Array();
  29867. var positions = new Array();
  29868. var normals = new Array();
  29869. var uvs = new Array();
  29870. var colors = new Array();
  29871. var angle_step = Math.PI * 2 * arc / tessellation;
  29872. var angle;
  29873. var h;
  29874. var radius;
  29875. var tan = (diameterBottom - diameterTop) / 2 / height;
  29876. var ringVertex = BABYLON.Vector3.Zero();
  29877. var ringNormal = BABYLON.Vector3.Zero();
  29878. var ringFirstVertex = BABYLON.Vector3.Zero();
  29879. var ringFirstNormal = BABYLON.Vector3.Zero();
  29880. var quadNormal = BABYLON.Vector3.Zero();
  29881. var Y = BABYLON.Axis.Y;
  29882. // positions, normals, uvs
  29883. var i;
  29884. var j;
  29885. var r;
  29886. var ringIdx = 1;
  29887. var s = 1; // surface index
  29888. var cs = 0;
  29889. var v = 0;
  29890. for (i = 0; i <= subdivisions; i++) {
  29891. h = i / subdivisions;
  29892. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29893. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29894. for (r = 0; r < ringIdx; r++) {
  29895. if (hasRings) {
  29896. s += r;
  29897. }
  29898. if (enclose) {
  29899. s += 2 * r;
  29900. }
  29901. for (j = 0; j <= tessellation; j++) {
  29902. angle = j * angle_step;
  29903. // position
  29904. ringVertex.x = Math.cos(-angle) * radius;
  29905. ringVertex.y = -height / 2 + h * height;
  29906. ringVertex.z = Math.sin(-angle) * radius;
  29907. // normal
  29908. if (diameterTop === 0 && i === subdivisions) {
  29909. // if no top cap, reuse former normals
  29910. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29911. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29912. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29913. }
  29914. else {
  29915. ringNormal.x = ringVertex.x;
  29916. ringNormal.z = ringVertex.z;
  29917. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29918. ringNormal.normalize();
  29919. }
  29920. // keep first ring vertex values for enclose
  29921. if (j === 0) {
  29922. ringFirstVertex.copyFrom(ringVertex);
  29923. ringFirstNormal.copyFrom(ringNormal);
  29924. }
  29925. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29926. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29927. if (hasRings) {
  29928. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29929. }
  29930. else {
  29931. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29932. }
  29933. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29934. if (faceColors) {
  29935. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29936. }
  29937. }
  29938. // if enclose, add four vertices and their dedicated normals
  29939. if (arc !== 1 && enclose) {
  29940. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29941. positions.push(0, ringVertex.y, 0);
  29942. positions.push(0, ringVertex.y, 0);
  29943. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29944. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29945. quadNormal.normalize();
  29946. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29947. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29948. quadNormal.normalize();
  29949. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29950. if (hasRings) {
  29951. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29952. }
  29953. else {
  29954. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29955. }
  29956. uvs.push(faceUV[s + 1].x, v);
  29957. uvs.push(faceUV[s + 1].z, v);
  29958. if (hasRings) {
  29959. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29960. }
  29961. else {
  29962. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29963. }
  29964. uvs.push(faceUV[s + 2].x, v);
  29965. uvs.push(faceUV[s + 2].z, v);
  29966. if (faceColors) {
  29967. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29968. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29969. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29970. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29971. }
  29972. }
  29973. if (cs !== s) {
  29974. cs = s;
  29975. }
  29976. }
  29977. }
  29978. // indices
  29979. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29980. var s;
  29981. i = 0;
  29982. for (s = 0; s < subdivisions; s++) {
  29983. var i0 = 0;
  29984. var i1 = 0;
  29985. var i2 = 0;
  29986. var i3 = 0;
  29987. for (j = 0; j < tessellation; j++) {
  29988. i0 = i * (e + 1) + j;
  29989. i1 = (i + 1) * (e + 1) + j;
  29990. i2 = i * (e + 1) + (j + 1);
  29991. i3 = (i + 1) * (e + 1) + (j + 1);
  29992. indices.push(i0, i1, i2);
  29993. indices.push(i3, i2, i1);
  29994. }
  29995. if (arc !== 1 && enclose) {
  29996. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29997. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29998. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29999. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30000. }
  30001. i = (hasRings) ? (i + 2) : (i + 1);
  30002. }
  30003. // Caps
  30004. var createCylinderCap = function (isTop) {
  30005. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30006. if (radius === 0) {
  30007. return;
  30008. }
  30009. // Cap positions, normals & uvs
  30010. var angle;
  30011. var circleVector;
  30012. var i;
  30013. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30014. var c = null;
  30015. if (faceColors) {
  30016. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30017. }
  30018. // cap center
  30019. var vbase = positions.length / 3;
  30020. var offset = isTop ? height / 2 : -height / 2;
  30021. var center = new BABYLON.Vector3(0, offset, 0);
  30022. positions.push(center.x, center.y, center.z);
  30023. normals.push(0, isTop ? 1 : -1, 0);
  30024. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30025. if (c) {
  30026. colors.push(c.r, c.g, c.b, c.a);
  30027. }
  30028. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30029. for (i = 0; i <= tessellation; i++) {
  30030. angle = Math.PI * 2 * i * arc / tessellation;
  30031. var cos = Math.cos(-angle);
  30032. var sin = Math.sin(-angle);
  30033. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30034. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30035. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30036. normals.push(0, isTop ? 1 : -1, 0);
  30037. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30038. if (c) {
  30039. colors.push(c.r, c.g, c.b, c.a);
  30040. }
  30041. }
  30042. // Cap indices
  30043. for (i = 0; i < tessellation; i++) {
  30044. if (!isTop) {
  30045. indices.push(vbase);
  30046. indices.push(vbase + (i + 1));
  30047. indices.push(vbase + (i + 2));
  30048. }
  30049. else {
  30050. indices.push(vbase);
  30051. indices.push(vbase + (i + 2));
  30052. indices.push(vbase + (i + 1));
  30053. }
  30054. }
  30055. };
  30056. // add caps to geometry
  30057. createCylinderCap(false);
  30058. createCylinderCap(true);
  30059. // Sides
  30060. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30061. var vertexData = new VertexData();
  30062. vertexData.indices = indices;
  30063. vertexData.positions = positions;
  30064. vertexData.normals = normals;
  30065. vertexData.uvs = uvs;
  30066. if (faceColors) {
  30067. vertexData.colors = colors;
  30068. }
  30069. return vertexData;
  30070. };
  30071. /**
  30072. * Creates the VertexData of the Torus.
  30073. */
  30074. VertexData.CreateTorus = function (options) {
  30075. var indices = [];
  30076. var positions = [];
  30077. var normals = [];
  30078. var uvs = [];
  30079. var diameter = options.diameter || 1;
  30080. var thickness = options.thickness || 0.5;
  30081. var tessellation = options.tessellation || 16;
  30082. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30083. var stride = tessellation + 1;
  30084. for (var i = 0; i <= tessellation; i++) {
  30085. var u = i / tessellation;
  30086. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30087. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30088. for (var j = 0; j <= tessellation; j++) {
  30089. var v = 1 - j / tessellation;
  30090. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30091. var dx = Math.cos(innerAngle);
  30092. var dy = Math.sin(innerAngle);
  30093. // Create a vertex.
  30094. var normal = new BABYLON.Vector3(dx, dy, 0);
  30095. var position = normal.scale(thickness / 2);
  30096. var textureCoordinate = new BABYLON.Vector2(u, v);
  30097. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30098. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30099. positions.push(position.x, position.y, position.z);
  30100. normals.push(normal.x, normal.y, normal.z);
  30101. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30102. // And create indices for two triangles.
  30103. var nextI = (i + 1) % stride;
  30104. var nextJ = (j + 1) % stride;
  30105. indices.push(i * stride + j);
  30106. indices.push(i * stride + nextJ);
  30107. indices.push(nextI * stride + j);
  30108. indices.push(i * stride + nextJ);
  30109. indices.push(nextI * stride + nextJ);
  30110. indices.push(nextI * stride + j);
  30111. }
  30112. }
  30113. // Sides
  30114. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30115. // Result
  30116. var vertexData = new VertexData();
  30117. vertexData.indices = indices;
  30118. vertexData.positions = positions;
  30119. vertexData.normals = normals;
  30120. vertexData.uvs = uvs;
  30121. return vertexData;
  30122. };
  30123. /**
  30124. * Creates the VertexData of the LineSystem.
  30125. */
  30126. VertexData.CreateLineSystem = function (options) {
  30127. var indices = [];
  30128. var positions = [];
  30129. var lines = options.lines;
  30130. var colors = options.colors;
  30131. var vertexColors = [];
  30132. var idx = 0;
  30133. for (var l = 0; l < lines.length; l++) {
  30134. var points = lines[l];
  30135. for (var index = 0; index < points.length; index++) {
  30136. positions.push(points[index].x, points[index].y, points[index].z);
  30137. if (colors) {
  30138. var color = colors[l];
  30139. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30140. }
  30141. if (index > 0) {
  30142. indices.push(idx - 1);
  30143. indices.push(idx);
  30144. }
  30145. idx++;
  30146. }
  30147. }
  30148. var vertexData = new VertexData();
  30149. vertexData.indices = indices;
  30150. vertexData.positions = positions;
  30151. if (colors) {
  30152. vertexData.colors = vertexColors;
  30153. }
  30154. return vertexData;
  30155. };
  30156. /**
  30157. * Create the VertexData of the DashedLines.
  30158. */
  30159. VertexData.CreateDashedLines = function (options) {
  30160. var dashSize = options.dashSize || 3;
  30161. var gapSize = options.gapSize || 1;
  30162. var dashNb = options.dashNb || 200;
  30163. var points = options.points;
  30164. var positions = new Array();
  30165. var indices = new Array();
  30166. var curvect = BABYLON.Vector3.Zero();
  30167. var lg = 0;
  30168. var nb = 0;
  30169. var shft = 0;
  30170. var dashshft = 0;
  30171. var curshft = 0;
  30172. var idx = 0;
  30173. var i = 0;
  30174. for (i = 0; i < points.length - 1; i++) {
  30175. points[i + 1].subtractToRef(points[i], curvect);
  30176. lg += curvect.length();
  30177. }
  30178. shft = lg / dashNb;
  30179. dashshft = dashSize * shft / (dashSize + gapSize);
  30180. for (i = 0; i < points.length - 1; i++) {
  30181. points[i + 1].subtractToRef(points[i], curvect);
  30182. nb = Math.floor(curvect.length() / shft);
  30183. curvect.normalize();
  30184. for (var j = 0; j < nb; j++) {
  30185. curshft = shft * j;
  30186. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30187. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30188. indices.push(idx, idx + 1);
  30189. idx += 2;
  30190. }
  30191. }
  30192. // Result
  30193. var vertexData = new VertexData();
  30194. vertexData.positions = positions;
  30195. vertexData.indices = indices;
  30196. return vertexData;
  30197. };
  30198. /**
  30199. * Creates the VertexData of the Ground.
  30200. */
  30201. VertexData.CreateGround = function (options) {
  30202. var indices = [];
  30203. var positions = [];
  30204. var normals = [];
  30205. var uvs = [];
  30206. var row, col;
  30207. var width = options.width || 1;
  30208. var height = options.height || 1;
  30209. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30210. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30211. for (row = 0; row <= subdivisionsY; row++) {
  30212. for (col = 0; col <= subdivisionsX; col++) {
  30213. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30214. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30215. positions.push(position.x, position.y, position.z);
  30216. normals.push(normal.x, normal.y, normal.z);
  30217. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30218. }
  30219. }
  30220. for (row = 0; row < subdivisionsY; row++) {
  30221. for (col = 0; col < subdivisionsX; col++) {
  30222. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30223. indices.push(col + 1 + row * (subdivisionsX + 1));
  30224. indices.push(col + row * (subdivisionsX + 1));
  30225. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30226. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30227. indices.push(col + row * (subdivisionsX + 1));
  30228. }
  30229. }
  30230. // Result
  30231. var vertexData = new VertexData();
  30232. vertexData.indices = indices;
  30233. vertexData.positions = positions;
  30234. vertexData.normals = normals;
  30235. vertexData.uvs = uvs;
  30236. return vertexData;
  30237. };
  30238. /**
  30239. * Creates the VertexData of the TiledGround.
  30240. */
  30241. VertexData.CreateTiledGround = function (options) {
  30242. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30243. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30244. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30245. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30246. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30247. var precision = options.precision || { w: 1, h: 1 };
  30248. var indices = new Array();
  30249. var positions = new Array();
  30250. var normals = new Array();
  30251. var uvs = new Array();
  30252. var row, col, tileRow, tileCol;
  30253. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30254. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30255. precision.w = (precision.w < 1) ? 1 : precision.w;
  30256. precision.h = (precision.h < 1) ? 1 : precision.h;
  30257. var tileSize = {
  30258. 'w': (xmax - xmin) / subdivisions.w,
  30259. 'h': (zmax - zmin) / subdivisions.h
  30260. };
  30261. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30262. // Indices
  30263. var base = positions.length / 3;
  30264. var rowLength = precision.w + 1;
  30265. for (row = 0; row < precision.h; row++) {
  30266. for (col = 0; col < precision.w; col++) {
  30267. var square = [
  30268. base + col + row * rowLength,
  30269. base + (col + 1) + row * rowLength,
  30270. base + (col + 1) + (row + 1) * rowLength,
  30271. base + col + (row + 1) * rowLength
  30272. ];
  30273. indices.push(square[1]);
  30274. indices.push(square[2]);
  30275. indices.push(square[3]);
  30276. indices.push(square[0]);
  30277. indices.push(square[1]);
  30278. indices.push(square[3]);
  30279. }
  30280. }
  30281. // Position, normals and uvs
  30282. var position = BABYLON.Vector3.Zero();
  30283. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30284. for (row = 0; row <= precision.h; row++) {
  30285. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30286. for (col = 0; col <= precision.w; col++) {
  30287. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30288. position.y = 0;
  30289. positions.push(position.x, position.y, position.z);
  30290. normals.push(normal.x, normal.y, normal.z);
  30291. uvs.push(col / precision.w, row / precision.h);
  30292. }
  30293. }
  30294. }
  30295. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30296. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30297. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30298. }
  30299. }
  30300. // Result
  30301. var vertexData = new VertexData();
  30302. vertexData.indices = indices;
  30303. vertexData.positions = positions;
  30304. vertexData.normals = normals;
  30305. vertexData.uvs = uvs;
  30306. return vertexData;
  30307. };
  30308. /**
  30309. * Creates the VertexData of the Ground designed from a heightmap.
  30310. */
  30311. VertexData.CreateGroundFromHeightMap = function (options) {
  30312. var indices = [];
  30313. var positions = [];
  30314. var normals = [];
  30315. var uvs = [];
  30316. var row, col;
  30317. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30318. // Vertices
  30319. for (row = 0; row <= options.subdivisions; row++) {
  30320. for (col = 0; col <= options.subdivisions; col++) {
  30321. 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));
  30322. // Compute height
  30323. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30324. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30325. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30326. var r = options.buffer[pos] / 255.0;
  30327. var g = options.buffer[pos + 1] / 255.0;
  30328. var b = options.buffer[pos + 2] / 255.0;
  30329. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30330. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30331. // Add vertex
  30332. positions.push(position.x, position.y, position.z);
  30333. normals.push(0, 0, 0);
  30334. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30335. }
  30336. }
  30337. // Indices
  30338. for (row = 0; row < options.subdivisions; row++) {
  30339. for (col = 0; col < options.subdivisions; col++) {
  30340. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30341. indices.push(col + 1 + row * (options.subdivisions + 1));
  30342. indices.push(col + row * (options.subdivisions + 1));
  30343. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30344. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30345. indices.push(col + row * (options.subdivisions + 1));
  30346. }
  30347. }
  30348. // Normals
  30349. VertexData.ComputeNormals(positions, indices, normals);
  30350. // Result
  30351. var vertexData = new VertexData();
  30352. vertexData.indices = indices;
  30353. vertexData.positions = positions;
  30354. vertexData.normals = normals;
  30355. vertexData.uvs = uvs;
  30356. return vertexData;
  30357. };
  30358. /**
  30359. * Creates the VertexData of the Plane.
  30360. */
  30361. VertexData.CreatePlane = function (options) {
  30362. var indices = [];
  30363. var positions = [];
  30364. var normals = [];
  30365. var uvs = [];
  30366. var width = options.width || options.size || 1;
  30367. var height = options.height || options.size || 1;
  30368. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30369. // Vertices
  30370. var halfWidth = width / 2.0;
  30371. var halfHeight = height / 2.0;
  30372. positions.push(-halfWidth, -halfHeight, 0);
  30373. normals.push(0, 0, -1.0);
  30374. uvs.push(0.0, 0.0);
  30375. positions.push(halfWidth, -halfHeight, 0);
  30376. normals.push(0, 0, -1.0);
  30377. uvs.push(1.0, 0.0);
  30378. positions.push(halfWidth, halfHeight, 0);
  30379. normals.push(0, 0, -1.0);
  30380. uvs.push(1.0, 1.0);
  30381. positions.push(-halfWidth, halfHeight, 0);
  30382. normals.push(0, 0, -1.0);
  30383. uvs.push(0.0, 1.0);
  30384. // Indices
  30385. indices.push(0);
  30386. indices.push(1);
  30387. indices.push(2);
  30388. indices.push(0);
  30389. indices.push(2);
  30390. indices.push(3);
  30391. // Sides
  30392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30393. // Result
  30394. var vertexData = new VertexData();
  30395. vertexData.indices = indices;
  30396. vertexData.positions = positions;
  30397. vertexData.normals = normals;
  30398. vertexData.uvs = uvs;
  30399. return vertexData;
  30400. };
  30401. /**
  30402. * Creates the VertexData of the Disc or regular Polygon.
  30403. */
  30404. VertexData.CreateDisc = function (options) {
  30405. var positions = new Array();
  30406. var indices = new Array();
  30407. var normals = new Array();
  30408. var uvs = new Array();
  30409. var radius = options.radius || 0.5;
  30410. var tessellation = options.tessellation || 64;
  30411. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30413. // positions and uvs
  30414. positions.push(0, 0, 0); // disc center first
  30415. uvs.push(0.5, 0.5);
  30416. var theta = Math.PI * 2 * arc;
  30417. var step = theta / tessellation;
  30418. for (var a = 0; a < theta; a += step) {
  30419. var x = Math.cos(a);
  30420. var y = Math.sin(a);
  30421. var u = (x + 1) / 2;
  30422. var v = (1 - y) / 2;
  30423. positions.push(radius * x, radius * y, 0);
  30424. uvs.push(u, v);
  30425. }
  30426. if (arc === 1) {
  30427. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30428. uvs.push(uvs[2], uvs[3]);
  30429. }
  30430. //indices
  30431. var vertexNb = positions.length / 3;
  30432. for (var i = 1; i < vertexNb - 1; i++) {
  30433. indices.push(i + 1, 0, i);
  30434. }
  30435. // result
  30436. VertexData.ComputeNormals(positions, indices, normals);
  30437. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30438. var vertexData = new VertexData();
  30439. vertexData.indices = indices;
  30440. vertexData.positions = positions;
  30441. vertexData.normals = normals;
  30442. vertexData.uvs = uvs;
  30443. return vertexData;
  30444. };
  30445. /**
  30446. * Re-creates the VertexData of the Polygon for sideOrientation.
  30447. */
  30448. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30449. var faceUV = fUV || new Array(3);
  30450. var faceColors = fColors;
  30451. var colors = [];
  30452. // default face colors and UV if undefined
  30453. for (var f = 0; f < 3; f++) {
  30454. if (faceUV[f] === undefined) {
  30455. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30456. }
  30457. if (faceColors && faceColors[f] === undefined) {
  30458. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30459. }
  30460. }
  30461. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30462. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30463. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30464. var indices = polygon.getIndices();
  30465. // set face colours and textures
  30466. var idx = 0;
  30467. var face = 0;
  30468. for (var index = 0; index < normals.length; index += 3) {
  30469. //Edge Face no. 1
  30470. if (Math.abs(normals[index + 1]) < 0.001) {
  30471. face = 1;
  30472. }
  30473. //Top Face no. 0
  30474. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30475. face = 0;
  30476. }
  30477. //Bottom Face no. 2
  30478. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30479. face = 2;
  30480. }
  30481. idx = index / 3;
  30482. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30483. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30484. if (faceColors) {
  30485. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30486. }
  30487. }
  30488. // sides
  30489. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30490. // Result
  30491. var vertexData = new VertexData();
  30492. vertexData.indices = indices;
  30493. vertexData.positions = positions;
  30494. vertexData.normals = normals;
  30495. vertexData.uvs = uvs;
  30496. if (faceColors) {
  30497. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30498. vertexData.colors = totalColors;
  30499. }
  30500. return vertexData;
  30501. };
  30502. /**
  30503. * Creates the VertexData of the IcoSphere.
  30504. */
  30505. VertexData.CreateIcoSphere = function (options) {
  30506. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30507. var radius = options.radius || 1;
  30508. var flat = (options.flat === undefined) ? true : options.flat;
  30509. var subdivisions = options.subdivisions || 4;
  30510. var radiusX = options.radiusX || radius;
  30511. var radiusY = options.radiusY || radius;
  30512. var radiusZ = options.radiusZ || radius;
  30513. var t = (1 + Math.sqrt(5)) / 2;
  30514. // 12 vertex x,y,z
  30515. var ico_vertices = [
  30516. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30517. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30518. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30519. ];
  30520. // index of 3 vertex makes a face of icopshere
  30521. var ico_indices = [
  30522. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30523. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30524. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30525. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30526. ];
  30527. // vertex for uv have aliased position, not for UV
  30528. var vertices_unalias_id = [
  30529. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30530. // vertex alias
  30531. 0,
  30532. 2,
  30533. 3,
  30534. 3,
  30535. 3,
  30536. 4,
  30537. 7,
  30538. 8,
  30539. 9,
  30540. 9,
  30541. 10,
  30542. 11 // 23: B + 12
  30543. ];
  30544. // uv as integer step (not pixels !)
  30545. var ico_vertexuv = [
  30546. 5, 1, 3, 1, 6, 4, 0, 0,
  30547. 5, 3, 4, 2, 2, 2, 4, 0,
  30548. 2, 0, 1, 1, 6, 0, 6, 2,
  30549. // vertex alias (for same vertex on different faces)
  30550. 0, 4,
  30551. 3, 3,
  30552. 4, 4,
  30553. 3, 1,
  30554. 4, 2,
  30555. 4, 4,
  30556. 0, 2,
  30557. 1, 1,
  30558. 2, 2,
  30559. 3, 3,
  30560. 1, 3,
  30561. 2, 4 // 23: B + 12
  30562. ];
  30563. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30564. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30565. // First island of uv mapping
  30566. // v = 4h 3+ 2
  30567. // v = 3h 9+ 4
  30568. // v = 2h 9+ 5 B
  30569. // v = 1h 9 1 0
  30570. // v = 0h 3 8 7 A
  30571. // u = 0 1 2 3 4 5 6 *a
  30572. // Second island of uv mapping
  30573. // v = 4h 0+ B+ 4+
  30574. // v = 3h A+ 2+
  30575. // v = 2h 7+ 6 3+
  30576. // v = 1h 8+ 3+
  30577. // v = 0h
  30578. // u = 0 1 2 3 4 5 6 *a
  30579. // Face layout on texture UV mapping
  30580. // ============
  30581. // \ 4 /\ 16 / ======
  30582. // \ / \ / /\ 11 /
  30583. // \/ 7 \/ / \ /
  30584. // ======= / 10 \/
  30585. // /\ 17 /\ =======
  30586. // / \ / \ \ 15 /\
  30587. // / 8 \/ 12 \ \ / \
  30588. // ============ \/ 6 \
  30589. // \ 18 /\ ============
  30590. // \ / \ \ 5 /\ 0 /
  30591. // \/ 13 \ \ / \ /
  30592. // ======= \/ 1 \/
  30593. // =============
  30594. // /\ 19 /\ 2 /\
  30595. // / \ / \ / \
  30596. // / 14 \/ 9 \/ 3 \
  30597. // ===================
  30598. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30599. var ustep = 138 / 1024;
  30600. var vstep = 239 / 1024;
  30601. var uoffset = 60 / 1024;
  30602. var voffset = 26 / 1024;
  30603. // Second island should have margin, not to touch the first island
  30604. // avoid any borderline artefact in pixel rounding
  30605. var island_u_offset = -40 / 1024;
  30606. var island_v_offset = +20 / 1024;
  30607. // face is either island 0 or 1 :
  30608. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30609. var island = [
  30610. 0, 0, 0, 0, 1,
  30611. 0, 0, 1, 1, 0,
  30612. 0, 0, 1, 1, 0,
  30613. 0, 1, 1, 1, 0 // 15 - 19
  30614. ];
  30615. var indices = new Array();
  30616. var positions = new Array();
  30617. var normals = new Array();
  30618. var uvs = new Array();
  30619. var current_indice = 0;
  30620. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30621. var face_vertex_pos = new Array(3);
  30622. var face_vertex_uv = new Array(3);
  30623. var v012;
  30624. for (v012 = 0; v012 < 3; v012++) {
  30625. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30626. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30627. }
  30628. // create all with normals
  30629. for (var face = 0; face < 20; face++) {
  30630. // 3 vertex per face
  30631. for (v012 = 0; v012 < 3; v012++) {
  30632. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30633. var v_id = ico_indices[3 * face + v012];
  30634. // vertex have 3D position (x,y,z)
  30635. 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]);
  30636. // Normalize to get normal, then scale to radius
  30637. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30638. // uv Coordinates from vertex ID
  30639. 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);
  30640. }
  30641. // Subdivide the face (interpolate pos, norm, uv)
  30642. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30643. // - norm is linear interpolation of vertex corner normal
  30644. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30645. // - uv is linear interpolation
  30646. //
  30647. // Topology is as below for sub-divide by 2
  30648. // vertex shown as v0,v1,v2
  30649. // interp index is i1 to progress in range [v0,v1[
  30650. // interp index is i2 to progress in range [v0,v2[
  30651. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30652. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30653. //
  30654. //
  30655. // i2 v2
  30656. // ^ ^
  30657. // / / \
  30658. // / / \
  30659. // / / \
  30660. // / / (0,1) \
  30661. // / #---------\
  30662. // / / \ (0,0)'/ \
  30663. // / / \ / \
  30664. // / / \ / \
  30665. // / / (0,0) \ / (1,0) \
  30666. // / #---------#---------\
  30667. // v0 v1
  30668. //
  30669. // --------------------> i1
  30670. //
  30671. // interp of (i1,i2):
  30672. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30673. // along i1 : lerp(x0,x1, i1/(S-i2))
  30674. //
  30675. // centroid of triangle is needed to get help normal computation
  30676. // (c1,c2) are used for centroid location
  30677. var interp_vertex = function (i1, i2, c1, c2) {
  30678. // vertex is interpolated from
  30679. // - face_vertex_pos[0..2]
  30680. // - face_vertex_uv[0..2]
  30681. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30682. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30683. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30684. pos_interp.normalize();
  30685. var vertex_normal;
  30686. if (flat) {
  30687. // in flat mode, recalculate normal as face centroid normal
  30688. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30689. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30690. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30691. }
  30692. else {
  30693. // in smooth mode, recalculate normal from each single vertex position
  30694. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30695. }
  30696. // Vertex normal need correction due to X,Y,Z radius scaling
  30697. vertex_normal.x /= radiusX;
  30698. vertex_normal.y /= radiusY;
  30699. vertex_normal.z /= radiusZ;
  30700. vertex_normal.normalize();
  30701. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30702. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30703. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30704. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30705. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30706. uvs.push(uv_interp.x, uv_interp.y);
  30707. // push each vertex has member of a face
  30708. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30709. indices.push(current_indice);
  30710. current_indice++;
  30711. };
  30712. for (var i2 = 0; i2 < subdivisions; i2++) {
  30713. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30714. // face : (i1,i2) for /\ :
  30715. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30716. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30717. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30718. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30719. if (i1 + i2 + 1 < subdivisions) {
  30720. // face : (i1,i2)' for \/ :
  30721. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30722. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30723. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30724. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30725. }
  30726. }
  30727. }
  30728. }
  30729. // Sides
  30730. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30731. // Result
  30732. var vertexData = new VertexData();
  30733. vertexData.indices = indices;
  30734. vertexData.positions = positions;
  30735. vertexData.normals = normals;
  30736. vertexData.uvs = uvs;
  30737. return vertexData;
  30738. };
  30739. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30740. /**
  30741. * Creates the VertexData of the Polyhedron.
  30742. */
  30743. VertexData.CreatePolyhedron = function (options) {
  30744. // provided polyhedron types :
  30745. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30746. // 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)
  30747. var polyhedra = [];
  30748. 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]] };
  30749. 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]] };
  30750. polyhedra[2] = {
  30751. 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]],
  30752. 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]]
  30753. };
  30754. polyhedra[3] = {
  30755. 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]],
  30756. 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]]
  30757. };
  30758. polyhedra[4] = {
  30759. 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]],
  30760. 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]]
  30761. };
  30762. 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]] };
  30763. 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]] };
  30764. 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]] };
  30765. 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]] };
  30766. 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]] };
  30767. 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]] };
  30768. 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]] };
  30769. 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]] };
  30770. 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]] };
  30771. polyhedra[14] = {
  30772. 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]],
  30773. 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]]
  30774. };
  30775. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30776. var size = options.size;
  30777. var sizeX = options.sizeX || size || 1;
  30778. var sizeY = options.sizeY || size || 1;
  30779. var sizeZ = options.sizeZ || size || 1;
  30780. var data = options.custom || polyhedra[type];
  30781. var nbfaces = data.face.length;
  30782. var faceUV = options.faceUV || new Array(nbfaces);
  30783. var faceColors = options.faceColors;
  30784. var flat = (options.flat === undefined) ? true : options.flat;
  30785. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30786. var positions = new Array();
  30787. var indices = new Array();
  30788. var normals = new Array();
  30789. var uvs = new Array();
  30790. var colors = new Array();
  30791. var index = 0;
  30792. var faceIdx = 0; // face cursor in the array "indexes"
  30793. var indexes = new Array();
  30794. var i = 0;
  30795. var f = 0;
  30796. var u, v, ang, x, y, tmp;
  30797. // default face colors and UV if undefined
  30798. if (flat) {
  30799. for (f = 0; f < nbfaces; f++) {
  30800. if (faceColors && faceColors[f] === undefined) {
  30801. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30802. }
  30803. if (faceUV && faceUV[f] === undefined) {
  30804. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30805. }
  30806. }
  30807. }
  30808. if (!flat) {
  30809. for (i = 0; i < data.vertex.length; i++) {
  30810. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30811. uvs.push(0, 0);
  30812. }
  30813. for (f = 0; f < nbfaces; f++) {
  30814. for (i = 0; i < data.face[f].length - 2; i++) {
  30815. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30816. }
  30817. }
  30818. }
  30819. else {
  30820. for (f = 0; f < nbfaces; f++) {
  30821. var fl = data.face[f].length; // number of vertices of the current face
  30822. ang = 2 * Math.PI / fl;
  30823. x = 0.5 * Math.tan(ang / 2);
  30824. y = 0.5;
  30825. // positions, uvs, colors
  30826. for (i = 0; i < fl; i++) {
  30827. // positions
  30828. 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);
  30829. indexes.push(index);
  30830. index++;
  30831. // uvs
  30832. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30833. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30834. uvs.push(u, v);
  30835. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30836. y = x * Math.sin(ang) + y * Math.cos(ang);
  30837. x = tmp;
  30838. // colors
  30839. if (faceColors) {
  30840. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30841. }
  30842. }
  30843. // indices from indexes
  30844. for (i = 0; i < fl - 2; i++) {
  30845. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30846. }
  30847. faceIdx += fl;
  30848. }
  30849. }
  30850. VertexData.ComputeNormals(positions, indices, normals);
  30851. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30852. var vertexData = new VertexData();
  30853. vertexData.positions = positions;
  30854. vertexData.indices = indices;
  30855. vertexData.normals = normals;
  30856. vertexData.uvs = uvs;
  30857. if (faceColors && flat) {
  30858. vertexData.colors = colors;
  30859. }
  30860. return vertexData;
  30861. };
  30862. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30863. /**
  30864. * Creates the VertexData of the Torus Knot.
  30865. */
  30866. VertexData.CreateTorusKnot = function (options) {
  30867. var indices = new Array();
  30868. var positions = new Array();
  30869. var normals = new Array();
  30870. var uvs = new Array();
  30871. var radius = options.radius || 2;
  30872. var tube = options.tube || 0.5;
  30873. var radialSegments = options.radialSegments || 32;
  30874. var tubularSegments = options.tubularSegments || 32;
  30875. var p = options.p || 2;
  30876. var q = options.q || 3;
  30877. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30878. // Helper
  30879. var getPos = function (angle) {
  30880. var cu = Math.cos(angle);
  30881. var su = Math.sin(angle);
  30882. var quOverP = q / p * angle;
  30883. var cs = Math.cos(quOverP);
  30884. var tx = radius * (2 + cs) * 0.5 * cu;
  30885. var ty = radius * (2 + cs) * su * 0.5;
  30886. var tz = radius * Math.sin(quOverP) * 0.5;
  30887. return new BABYLON.Vector3(tx, ty, tz);
  30888. };
  30889. // Vertices
  30890. var i;
  30891. var j;
  30892. for (i = 0; i <= radialSegments; i++) {
  30893. var modI = i % radialSegments;
  30894. var u = modI / radialSegments * 2 * p * Math.PI;
  30895. var p1 = getPos(u);
  30896. var p2 = getPos(u + 0.01);
  30897. var tang = p2.subtract(p1);
  30898. var n = p2.add(p1);
  30899. var bitan = BABYLON.Vector3.Cross(tang, n);
  30900. n = BABYLON.Vector3.Cross(bitan, tang);
  30901. bitan.normalize();
  30902. n.normalize();
  30903. for (j = 0; j < tubularSegments; j++) {
  30904. var modJ = j % tubularSegments;
  30905. var v = modJ / tubularSegments * 2 * Math.PI;
  30906. var cx = -tube * Math.cos(v);
  30907. var cy = tube * Math.sin(v);
  30908. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30909. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30910. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30911. uvs.push(i / radialSegments);
  30912. uvs.push(j / tubularSegments);
  30913. }
  30914. }
  30915. for (i = 0; i < radialSegments; i++) {
  30916. for (j = 0; j < tubularSegments; j++) {
  30917. var jNext = (j + 1) % tubularSegments;
  30918. var a = i * tubularSegments + j;
  30919. var b = (i + 1) * tubularSegments + j;
  30920. var c = (i + 1) * tubularSegments + jNext;
  30921. var d = i * tubularSegments + jNext;
  30922. indices.push(d);
  30923. indices.push(b);
  30924. indices.push(a);
  30925. indices.push(d);
  30926. indices.push(c);
  30927. indices.push(b);
  30928. }
  30929. }
  30930. // Normals
  30931. VertexData.ComputeNormals(positions, indices, normals);
  30932. // Sides
  30933. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30934. // Result
  30935. var vertexData = new VertexData();
  30936. vertexData.indices = indices;
  30937. vertexData.positions = positions;
  30938. vertexData.normals = normals;
  30939. vertexData.uvs = uvs;
  30940. return vertexData;
  30941. };
  30942. // Tools
  30943. /**
  30944. * @param {any} - positions (number[] or Float32Array)
  30945. * @param {any} - indices (number[] or Uint16Array)
  30946. * @param {any} - normals (number[] or Float32Array)
  30947. * options (optional) :
  30948. * facetPositions : optional array of facet positions (vector3)
  30949. * facetNormals : optional array of facet normals (vector3)
  30950. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30951. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30952. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30953. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30954. * bInfo : optional bounding info, required for facetPartitioning computation
  30955. * useRightHandedSystem: optional boolean to for right handed system computation
  30956. * depthSort : optional boolean to enable the facet depth sort computation
  30957. * distanceTo : optional Vector3 to compute the facet depth from this location
  30958. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30959. */
  30960. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30961. // temporary scalar variables
  30962. var index = 0; // facet index
  30963. var p1p2x = 0.0; // p1p2 vector x coordinate
  30964. var p1p2y = 0.0; // p1p2 vector y coordinate
  30965. var p1p2z = 0.0; // p1p2 vector z coordinate
  30966. var p3p2x = 0.0; // p3p2 vector x coordinate
  30967. var p3p2y = 0.0; // p3p2 vector y coordinate
  30968. var p3p2z = 0.0; // p3p2 vector z coordinate
  30969. var faceNormalx = 0.0; // facet normal x coordinate
  30970. var faceNormaly = 0.0; // facet normal y coordinate
  30971. var faceNormalz = 0.0; // facet normal z coordinate
  30972. var length = 0.0; // facet normal length before normalization
  30973. var v1x = 0; // vector1 x index in the positions array
  30974. var v1y = 0; // vector1 y index in the positions array
  30975. var v1z = 0; // vector1 z index in the positions array
  30976. var v2x = 0; // vector2 x index in the positions array
  30977. var v2y = 0; // vector2 y index in the positions array
  30978. var v2z = 0; // vector2 z index in the positions array
  30979. var v3x = 0; // vector3 x index in the positions array
  30980. var v3y = 0; // vector3 y index in the positions array
  30981. var v3z = 0; // vector3 z index in the positions array
  30982. var computeFacetNormals = false;
  30983. var computeFacetPositions = false;
  30984. var computeFacetPartitioning = false;
  30985. var computeDepthSort = false;
  30986. var faceNormalSign = 1;
  30987. var ratio = 0;
  30988. var distanceTo = null;
  30989. if (options) {
  30990. computeFacetNormals = (options.facetNormals) ? true : false;
  30991. computeFacetPositions = (options.facetPositions) ? true : false;
  30992. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30993. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30994. ratio = options.ratio || 0;
  30995. computeDepthSort = (options.depthSort) ? true : false;
  30996. distanceTo = (options.distanceTo);
  30997. if (computeDepthSort) {
  30998. if (distanceTo === undefined) {
  30999. distanceTo = BABYLON.Vector3.Zero();
  31000. }
  31001. var depthSortedFacets = options.depthSortedFacets;
  31002. }
  31003. }
  31004. // facetPartitioning reinit if needed
  31005. var xSubRatio = 0;
  31006. var ySubRatio = 0;
  31007. var zSubRatio = 0;
  31008. var subSq = 0;
  31009. if (computeFacetPartitioning && options && options.bbSize) {
  31010. var ox = 0; // X partitioning index for facet position
  31011. var oy = 0; // Y partinioning index for facet position
  31012. var oz = 0; // Z partinioning index for facet position
  31013. var b1x = 0; // X partitioning index for facet v1 vertex
  31014. var b1y = 0; // Y partitioning index for facet v1 vertex
  31015. var b1z = 0; // z partitioning index for facet v1 vertex
  31016. var b2x = 0; // X partitioning index for facet v2 vertex
  31017. var b2y = 0; // Y partitioning index for facet v2 vertex
  31018. var b2z = 0; // Z partitioning index for facet v2 vertex
  31019. var b3x = 0; // X partitioning index for facet v3 vertex
  31020. var b3y = 0; // Y partitioning index for facet v3 vertex
  31021. var b3z = 0; // Z partitioning index for facet v3 vertex
  31022. var block_idx_o = 0; // facet barycenter block index
  31023. var block_idx_v1 = 0; // v1 vertex block index
  31024. var block_idx_v2 = 0; // v2 vertex block index
  31025. var block_idx_v3 = 0; // v3 vertex block index
  31026. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31027. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31028. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31029. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31030. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31031. subSq = options.subDiv.max * options.subDiv.max;
  31032. options.facetPartitioning.length = 0;
  31033. }
  31034. // reset the normals
  31035. for (index = 0; index < positions.length; index++) {
  31036. normals[index] = 0.0;
  31037. }
  31038. // Loop : 1 indice triplet = 1 facet
  31039. var nbFaces = (indices.length / 3) | 0;
  31040. for (index = 0; index < nbFaces; index++) {
  31041. // get the indexes of the coordinates of each vertex of the facet
  31042. v1x = indices[index * 3] * 3;
  31043. v1y = v1x + 1;
  31044. v1z = v1x + 2;
  31045. v2x = indices[index * 3 + 1] * 3;
  31046. v2y = v2x + 1;
  31047. v2z = v2x + 2;
  31048. v3x = indices[index * 3 + 2] * 3;
  31049. v3y = v3x + 1;
  31050. v3z = v3x + 2;
  31051. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31052. p1p2y = positions[v1y] - positions[v2y];
  31053. p1p2z = positions[v1z] - positions[v2z];
  31054. p3p2x = positions[v3x] - positions[v2x];
  31055. p3p2y = positions[v3y] - positions[v2y];
  31056. p3p2z = positions[v3z] - positions[v2z];
  31057. // compute the face normal with the cross product
  31058. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31059. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31060. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31061. // normalize this normal and store it in the array facetData
  31062. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31063. length = (length === 0) ? 1.0 : length;
  31064. faceNormalx /= length;
  31065. faceNormaly /= length;
  31066. faceNormalz /= length;
  31067. if (computeFacetNormals && options) {
  31068. options.facetNormals[index].x = faceNormalx;
  31069. options.facetNormals[index].y = faceNormaly;
  31070. options.facetNormals[index].z = faceNormalz;
  31071. }
  31072. if (computeFacetPositions && options) {
  31073. // compute and the facet barycenter coordinates in the array facetPositions
  31074. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31075. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31076. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31077. }
  31078. if (computeFacetPartitioning && options) {
  31079. // store the facet indexes in arrays in the main facetPartitioning array :
  31080. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31081. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31082. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31083. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31084. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31085. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31086. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31087. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31088. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31089. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31090. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31091. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31092. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31093. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31094. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31095. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31096. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31097. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31098. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31099. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31100. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31101. // push each facet index in each block containing the vertex
  31102. options.facetPartitioning[block_idx_v1].push(index);
  31103. if (block_idx_v2 != block_idx_v1) {
  31104. options.facetPartitioning[block_idx_v2].push(index);
  31105. }
  31106. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31107. options.facetPartitioning[block_idx_v3].push(index);
  31108. }
  31109. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31110. options.facetPartitioning[block_idx_o].push(index);
  31111. }
  31112. }
  31113. if (computeDepthSort && options && options.facetPositions) {
  31114. var dsf = depthSortedFacets[index];
  31115. dsf.ind = index * 3;
  31116. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31117. }
  31118. // compute the normals anyway
  31119. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31120. normals[v1y] += faceNormaly;
  31121. normals[v1z] += faceNormalz;
  31122. normals[v2x] += faceNormalx;
  31123. normals[v2y] += faceNormaly;
  31124. normals[v2z] += faceNormalz;
  31125. normals[v3x] += faceNormalx;
  31126. normals[v3y] += faceNormaly;
  31127. normals[v3z] += faceNormalz;
  31128. }
  31129. // last normalization of each normal
  31130. for (index = 0; index < normals.length / 3; index++) {
  31131. faceNormalx = normals[index * 3];
  31132. faceNormaly = normals[index * 3 + 1];
  31133. faceNormalz = normals[index * 3 + 2];
  31134. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31135. length = (length === 0) ? 1.0 : length;
  31136. faceNormalx /= length;
  31137. faceNormaly /= length;
  31138. faceNormalz /= length;
  31139. normals[index * 3] = faceNormalx;
  31140. normals[index * 3 + 1] = faceNormaly;
  31141. normals[index * 3 + 2] = faceNormalz;
  31142. }
  31143. };
  31144. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31145. var li = indices.length;
  31146. var ln = normals.length;
  31147. var i;
  31148. var n;
  31149. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31150. switch (sideOrientation) {
  31151. case BABYLON.Mesh.FRONTSIDE:
  31152. // nothing changed
  31153. break;
  31154. case BABYLON.Mesh.BACKSIDE:
  31155. var tmp;
  31156. // indices
  31157. for (i = 0; i < li; i += 3) {
  31158. tmp = indices[i];
  31159. indices[i] = indices[i + 2];
  31160. indices[i + 2] = tmp;
  31161. }
  31162. // normals
  31163. for (n = 0; n < ln; n++) {
  31164. normals[n] = -normals[n];
  31165. }
  31166. break;
  31167. case BABYLON.Mesh.DOUBLESIDE:
  31168. // positions
  31169. var lp = positions.length;
  31170. var l = lp / 3;
  31171. for (var p = 0; p < lp; p++) {
  31172. positions[lp + p] = positions[p];
  31173. }
  31174. // indices
  31175. for (i = 0; i < li; i += 3) {
  31176. indices[i + li] = indices[i + 2] + l;
  31177. indices[i + 1 + li] = indices[i + 1] + l;
  31178. indices[i + 2 + li] = indices[i] + l;
  31179. }
  31180. // normals
  31181. for (n = 0; n < ln; n++) {
  31182. normals[ln + n] = -normals[n];
  31183. }
  31184. // uvs
  31185. var lu = uvs.length;
  31186. var u = 0;
  31187. for (u = 0; u < lu; u++) {
  31188. uvs[u + lu] = uvs[u];
  31189. }
  31190. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31191. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31192. u = 0;
  31193. for (i = 0; i < lu / 2; i++) {
  31194. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31195. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31196. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31197. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31198. u += 2;
  31199. }
  31200. break;
  31201. }
  31202. };
  31203. /**
  31204. * Creates a new VertexData from the imported parameters.
  31205. */
  31206. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31207. var vertexData = new VertexData();
  31208. // positions
  31209. var positions = parsedVertexData.positions;
  31210. if (positions) {
  31211. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31212. }
  31213. // normals
  31214. var normals = parsedVertexData.normals;
  31215. if (normals) {
  31216. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31217. }
  31218. // tangents
  31219. var tangents = parsedVertexData.tangents;
  31220. if (tangents) {
  31221. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31222. }
  31223. // uvs
  31224. var uvs = parsedVertexData.uvs;
  31225. if (uvs) {
  31226. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31227. }
  31228. // uv2s
  31229. var uv2s = parsedVertexData.uv2s;
  31230. if (uv2s) {
  31231. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31232. }
  31233. // uv3s
  31234. var uv3s = parsedVertexData.uv3s;
  31235. if (uv3s) {
  31236. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31237. }
  31238. // uv4s
  31239. var uv4s = parsedVertexData.uv4s;
  31240. if (uv4s) {
  31241. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31242. }
  31243. // uv5s
  31244. var uv5s = parsedVertexData.uv5s;
  31245. if (uv5s) {
  31246. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31247. }
  31248. // uv6s
  31249. var uv6s = parsedVertexData.uv6s;
  31250. if (uv6s) {
  31251. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31252. }
  31253. // colors
  31254. var colors = parsedVertexData.colors;
  31255. if (colors) {
  31256. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31257. }
  31258. // matricesIndices
  31259. var matricesIndices = parsedVertexData.matricesIndices;
  31260. if (matricesIndices) {
  31261. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31262. }
  31263. // matricesWeights
  31264. var matricesWeights = parsedVertexData.matricesWeights;
  31265. if (matricesWeights) {
  31266. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31267. }
  31268. // indices
  31269. var indices = parsedVertexData.indices;
  31270. if (indices) {
  31271. vertexData.indices = indices;
  31272. }
  31273. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31274. };
  31275. return VertexData;
  31276. }());
  31277. BABYLON.VertexData = VertexData;
  31278. })(BABYLON || (BABYLON = {}));
  31279. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31280. var BABYLON;
  31281. (function (BABYLON) {
  31282. var Geometry = /** @class */ (function () {
  31283. function Geometry(id, scene, vertexData, updatable, mesh) {
  31284. if (updatable === void 0) { updatable = false; }
  31285. if (mesh === void 0) { mesh = null; }
  31286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31287. this._totalVertices = 0;
  31288. this._isDisposed = false;
  31289. this._indexBufferIsUpdatable = false;
  31290. this.id = id;
  31291. this._engine = scene.getEngine();
  31292. this._meshes = [];
  31293. this._scene = scene;
  31294. //Init vertex buffer cache
  31295. this._vertexBuffers = {};
  31296. this._indices = [];
  31297. this._updatable = updatable;
  31298. // vertexData
  31299. if (vertexData) {
  31300. this.setAllVerticesData(vertexData, updatable);
  31301. }
  31302. else {
  31303. this._totalVertices = 0;
  31304. this._indices = [];
  31305. }
  31306. if (this._engine.getCaps().vertexArrayObject) {
  31307. this._vertexArrayObjects = {};
  31308. }
  31309. // applyToMesh
  31310. if (mesh) {
  31311. if (mesh.getClassName() === "LinesMesh") {
  31312. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31313. this.updateExtend();
  31314. }
  31315. this.applyToMesh(mesh);
  31316. mesh.computeWorldMatrix(true);
  31317. }
  31318. }
  31319. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31320. /**
  31321. * 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
  31322. * @returns The Bias Vector
  31323. */
  31324. get: function () {
  31325. return this._boundingBias;
  31326. },
  31327. set: function (value) {
  31328. if (this._boundingBias && this._boundingBias.equals(value)) {
  31329. return;
  31330. }
  31331. this._boundingBias = value.clone();
  31332. this.updateBoundingInfo(true, null);
  31333. },
  31334. enumerable: true,
  31335. configurable: true
  31336. });
  31337. Geometry.CreateGeometryForMesh = function (mesh) {
  31338. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31339. geometry.applyToMesh(mesh);
  31340. return geometry;
  31341. };
  31342. Object.defineProperty(Geometry.prototype, "extend", {
  31343. get: function () {
  31344. return this._extend;
  31345. },
  31346. enumerable: true,
  31347. configurable: true
  31348. });
  31349. Geometry.prototype.getScene = function () {
  31350. return this._scene;
  31351. };
  31352. Geometry.prototype.getEngine = function () {
  31353. return this._engine;
  31354. };
  31355. Geometry.prototype.isReady = function () {
  31356. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31357. };
  31358. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31359. get: function () {
  31360. for (var index = 0; index < this._meshes.length; index++) {
  31361. if (!this._meshes[index].doNotSerialize) {
  31362. return false;
  31363. }
  31364. }
  31365. return true;
  31366. },
  31367. enumerable: true,
  31368. configurable: true
  31369. });
  31370. Geometry.prototype._rebuild = function () {
  31371. if (this._vertexArrayObjects) {
  31372. this._vertexArrayObjects = {};
  31373. }
  31374. // Index buffer
  31375. if (this._meshes.length !== 0 && this._indices) {
  31376. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31377. }
  31378. // Vertex buffers
  31379. for (var key in this._vertexBuffers) {
  31380. var vertexBuffer = this._vertexBuffers[key];
  31381. vertexBuffer._rebuild();
  31382. }
  31383. };
  31384. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31385. vertexData.applyToGeometry(this, updatable);
  31386. this.notifyUpdate();
  31387. };
  31388. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31389. if (updatable === void 0) { updatable = false; }
  31390. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31391. this.setVerticesBuffer(buffer);
  31392. };
  31393. Geometry.prototype.removeVerticesData = function (kind) {
  31394. if (this._vertexBuffers[kind]) {
  31395. this._vertexBuffers[kind].dispose();
  31396. delete this._vertexBuffers[kind];
  31397. }
  31398. };
  31399. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31400. var kind = buffer.getKind();
  31401. if (this._vertexBuffers[kind]) {
  31402. this._vertexBuffers[kind].dispose();
  31403. }
  31404. this._vertexBuffers[kind] = buffer;
  31405. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31406. var data = buffer.getData();
  31407. var stride = buffer.getStrideSize();
  31408. this._totalVertices = data.length / stride;
  31409. this.updateExtend(data, stride);
  31410. this._resetPointsArrayCache();
  31411. var meshes = this._meshes;
  31412. var numOfMeshes = meshes.length;
  31413. for (var index = 0; index < numOfMeshes; index++) {
  31414. var mesh = meshes[index];
  31415. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31416. mesh._createGlobalSubMesh(false);
  31417. mesh.computeWorldMatrix(true);
  31418. }
  31419. }
  31420. this.notifyUpdate(kind);
  31421. if (this._vertexArrayObjects) {
  31422. this._disposeVertexArrayObjects();
  31423. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31424. }
  31425. };
  31426. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31427. var vertexBuffer = this.getVertexBuffer(kind);
  31428. if (!vertexBuffer) {
  31429. return;
  31430. }
  31431. vertexBuffer.updateDirectly(data, offset);
  31432. this.notifyUpdate(kind);
  31433. };
  31434. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31435. if (updateExtends === void 0) { updateExtends = false; }
  31436. var vertexBuffer = this.getVertexBuffer(kind);
  31437. if (!vertexBuffer) {
  31438. return;
  31439. }
  31440. vertexBuffer.update(data);
  31441. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31442. var stride = vertexBuffer.getStrideSize();
  31443. this._totalVertices = data.length / stride;
  31444. this.updateBoundingInfo(updateExtends, data);
  31445. }
  31446. this.notifyUpdate(kind);
  31447. };
  31448. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31449. if (updateExtends) {
  31450. this.updateExtend(data);
  31451. }
  31452. var meshes = this._meshes;
  31453. var numOfMeshes = meshes.length;
  31454. this._resetPointsArrayCache();
  31455. for (var index = 0; index < numOfMeshes; index++) {
  31456. var mesh = meshes[index];
  31457. if (updateExtends) {
  31458. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31459. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31460. var subMesh = mesh.subMeshes[subIndex];
  31461. subMesh.refreshBoundingInfo();
  31462. }
  31463. }
  31464. }
  31465. };
  31466. Geometry.prototype._bind = function (effect, indexToBind) {
  31467. if (!effect) {
  31468. return;
  31469. }
  31470. if (indexToBind === undefined) {
  31471. indexToBind = this._indexBuffer;
  31472. }
  31473. var vbs = this.getVertexBuffers();
  31474. if (!vbs) {
  31475. return;
  31476. }
  31477. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31478. this._engine.bindBuffers(vbs, indexToBind, effect);
  31479. return;
  31480. }
  31481. // Using VAO
  31482. if (!this._vertexArrayObjects[effect.key]) {
  31483. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31484. }
  31485. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31486. };
  31487. Geometry.prototype.getTotalVertices = function () {
  31488. if (!this.isReady()) {
  31489. return 0;
  31490. }
  31491. return this._totalVertices;
  31492. };
  31493. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31494. var vertexBuffer = this.getVertexBuffer(kind);
  31495. if (!vertexBuffer) {
  31496. return null;
  31497. }
  31498. var orig = vertexBuffer.getData();
  31499. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31500. return orig;
  31501. }
  31502. else {
  31503. var len = orig.length;
  31504. var copy = [];
  31505. for (var i = 0; i < len; i++) {
  31506. copy.push(orig[i]);
  31507. }
  31508. return copy;
  31509. }
  31510. };
  31511. /**
  31512. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31513. * Possible `kind` values :
  31514. * - BABYLON.VertexBuffer.PositionKind
  31515. * - BABYLON.VertexBuffer.UVKind
  31516. * - BABYLON.VertexBuffer.UV2Kind
  31517. * - BABYLON.VertexBuffer.UV3Kind
  31518. * - BABYLON.VertexBuffer.UV4Kind
  31519. * - BABYLON.VertexBuffer.UV5Kind
  31520. * - BABYLON.VertexBuffer.UV6Kind
  31521. * - BABYLON.VertexBuffer.ColorKind
  31522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31526. */
  31527. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31528. var vb = this._vertexBuffers[kind];
  31529. if (!vb) {
  31530. return false;
  31531. }
  31532. return vb.isUpdatable();
  31533. };
  31534. Geometry.prototype.getVertexBuffer = function (kind) {
  31535. if (!this.isReady()) {
  31536. return null;
  31537. }
  31538. return this._vertexBuffers[kind];
  31539. };
  31540. Geometry.prototype.getVertexBuffers = function () {
  31541. if (!this.isReady()) {
  31542. return null;
  31543. }
  31544. return this._vertexBuffers;
  31545. };
  31546. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31547. if (!this._vertexBuffers) {
  31548. if (this._delayInfo) {
  31549. return this._delayInfo.indexOf(kind) !== -1;
  31550. }
  31551. return false;
  31552. }
  31553. return this._vertexBuffers[kind] !== undefined;
  31554. };
  31555. Geometry.prototype.getVerticesDataKinds = function () {
  31556. var result = [];
  31557. var kind;
  31558. if (!this._vertexBuffers && this._delayInfo) {
  31559. for (kind in this._delayInfo) {
  31560. result.push(kind);
  31561. }
  31562. }
  31563. else {
  31564. for (kind in this._vertexBuffers) {
  31565. result.push(kind);
  31566. }
  31567. }
  31568. return result;
  31569. };
  31570. Geometry.prototype.updateIndices = function (indices, offset) {
  31571. if (!this._indexBuffer) {
  31572. return;
  31573. }
  31574. if (!this._indexBufferIsUpdatable) {
  31575. this.setIndices(indices, null, true);
  31576. }
  31577. else {
  31578. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31579. }
  31580. };
  31581. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31582. if (totalVertices === void 0) { totalVertices = null; }
  31583. if (updatable === void 0) { updatable = false; }
  31584. if (this._indexBuffer) {
  31585. this._engine._releaseBuffer(this._indexBuffer);
  31586. }
  31587. this._disposeVertexArrayObjects();
  31588. this._indices = indices;
  31589. this._indexBufferIsUpdatable = updatable;
  31590. if (this._meshes.length !== 0 && this._indices) {
  31591. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31592. }
  31593. if (totalVertices != undefined) {
  31594. this._totalVertices = totalVertices;
  31595. }
  31596. var meshes = this._meshes;
  31597. var numOfMeshes = meshes.length;
  31598. for (var index = 0; index < numOfMeshes; index++) {
  31599. meshes[index]._createGlobalSubMesh(true);
  31600. }
  31601. this.notifyUpdate();
  31602. };
  31603. Geometry.prototype.getTotalIndices = function () {
  31604. if (!this.isReady()) {
  31605. return 0;
  31606. }
  31607. return this._indices.length;
  31608. };
  31609. Geometry.prototype.getIndices = function (copyWhenShared) {
  31610. if (!this.isReady()) {
  31611. return null;
  31612. }
  31613. var orig = this._indices;
  31614. if (!copyWhenShared || this._meshes.length === 1) {
  31615. return orig;
  31616. }
  31617. else {
  31618. var len = orig.length;
  31619. var copy = [];
  31620. for (var i = 0; i < len; i++) {
  31621. copy.push(orig[i]);
  31622. }
  31623. return copy;
  31624. }
  31625. };
  31626. Geometry.prototype.getIndexBuffer = function () {
  31627. if (!this.isReady()) {
  31628. return null;
  31629. }
  31630. return this._indexBuffer;
  31631. };
  31632. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31633. if (effect === void 0) { effect = null; }
  31634. if (!effect || !this._vertexArrayObjects) {
  31635. return;
  31636. }
  31637. if (this._vertexArrayObjects[effect.key]) {
  31638. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31639. delete this._vertexArrayObjects[effect.key];
  31640. }
  31641. };
  31642. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31643. var meshes = this._meshes;
  31644. var index = meshes.indexOf(mesh);
  31645. if (index === -1) {
  31646. return;
  31647. }
  31648. meshes.splice(index, 1);
  31649. mesh._geometry = null;
  31650. if (meshes.length === 0 && shouldDispose) {
  31651. this.dispose();
  31652. }
  31653. };
  31654. Geometry.prototype.applyToMesh = function (mesh) {
  31655. if (mesh._geometry === this) {
  31656. return;
  31657. }
  31658. var previousGeometry = mesh._geometry;
  31659. if (previousGeometry) {
  31660. previousGeometry.releaseForMesh(mesh);
  31661. }
  31662. var meshes = this._meshes;
  31663. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31664. mesh._geometry = this;
  31665. this._scene.pushGeometry(this);
  31666. meshes.push(mesh);
  31667. if (this.isReady()) {
  31668. this._applyToMesh(mesh);
  31669. }
  31670. else {
  31671. mesh._boundingInfo = this._boundingInfo;
  31672. }
  31673. };
  31674. Geometry.prototype.updateExtend = function (data, stride) {
  31675. if (data === void 0) { data = null; }
  31676. if (!data) {
  31677. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31678. }
  31679. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31680. };
  31681. Geometry.prototype._applyToMesh = function (mesh) {
  31682. var numOfMeshes = this._meshes.length;
  31683. // vertexBuffers
  31684. for (var kind in this._vertexBuffers) {
  31685. if (numOfMeshes === 1) {
  31686. this._vertexBuffers[kind].create();
  31687. }
  31688. var buffer = this._vertexBuffers[kind].getBuffer();
  31689. if (buffer)
  31690. buffer.references = numOfMeshes;
  31691. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31692. if (!this._extend) {
  31693. this.updateExtend(this._vertexBuffers[kind].getData());
  31694. }
  31695. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31696. mesh._createGlobalSubMesh(false);
  31697. //bounding info was just created again, world matrix should be applied again.
  31698. mesh._updateBoundingInfo();
  31699. }
  31700. }
  31701. // indexBuffer
  31702. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31703. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31704. }
  31705. if (this._indexBuffer) {
  31706. this._indexBuffer.references = numOfMeshes;
  31707. }
  31708. };
  31709. Geometry.prototype.notifyUpdate = function (kind) {
  31710. if (this.onGeometryUpdated) {
  31711. this.onGeometryUpdated(this, kind);
  31712. }
  31713. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31714. var mesh = _a[_i];
  31715. mesh._markSubMeshesAsAttributesDirty();
  31716. }
  31717. };
  31718. Geometry.prototype.load = function (scene, onLoaded) {
  31719. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31720. return;
  31721. }
  31722. if (this.isReady()) {
  31723. if (onLoaded) {
  31724. onLoaded();
  31725. }
  31726. return;
  31727. }
  31728. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31729. this._queueLoad(scene, onLoaded);
  31730. };
  31731. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31732. var _this = this;
  31733. if (!this.delayLoadingFile) {
  31734. return;
  31735. }
  31736. scene._addPendingData(this);
  31737. scene._loadFile(this.delayLoadingFile, function (data) {
  31738. if (!_this._delayLoadingFunction) {
  31739. return;
  31740. }
  31741. _this._delayLoadingFunction(JSON.parse(data), _this);
  31742. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31743. _this._delayInfo = [];
  31744. scene._removePendingData(_this);
  31745. var meshes = _this._meshes;
  31746. var numOfMeshes = meshes.length;
  31747. for (var index = 0; index < numOfMeshes; index++) {
  31748. _this._applyToMesh(meshes[index]);
  31749. }
  31750. if (onLoaded) {
  31751. onLoaded();
  31752. }
  31753. }, undefined, true);
  31754. };
  31755. /**
  31756. * Invert the geometry to move from a right handed system to a left handed one.
  31757. */
  31758. Geometry.prototype.toLeftHanded = function () {
  31759. // Flip faces
  31760. var tIndices = this.getIndices(false);
  31761. if (tIndices != null && tIndices.length > 0) {
  31762. for (var i = 0; i < tIndices.length; i += 3) {
  31763. var tTemp = tIndices[i + 0];
  31764. tIndices[i + 0] = tIndices[i + 2];
  31765. tIndices[i + 2] = tTemp;
  31766. }
  31767. this.setIndices(tIndices);
  31768. }
  31769. // Negate position.z
  31770. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31771. if (tPositions != null && tPositions.length > 0) {
  31772. for (var i = 0; i < tPositions.length; i += 3) {
  31773. tPositions[i + 2] = -tPositions[i + 2];
  31774. }
  31775. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31776. }
  31777. // Negate normal.z
  31778. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31779. if (tNormals != null && tNormals.length > 0) {
  31780. for (var i = 0; i < tNormals.length; i += 3) {
  31781. tNormals[i + 2] = -tNormals[i + 2];
  31782. }
  31783. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31784. }
  31785. };
  31786. // Cache
  31787. Geometry.prototype._resetPointsArrayCache = function () {
  31788. this._positions = null;
  31789. };
  31790. Geometry.prototype._generatePointsArray = function () {
  31791. if (this._positions)
  31792. return true;
  31793. this._positions = [];
  31794. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31795. if (!data) {
  31796. return false;
  31797. }
  31798. for (var index = 0; index < data.length; index += 3) {
  31799. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31800. }
  31801. return true;
  31802. };
  31803. Geometry.prototype.isDisposed = function () {
  31804. return this._isDisposed;
  31805. };
  31806. Geometry.prototype._disposeVertexArrayObjects = function () {
  31807. if (this._vertexArrayObjects) {
  31808. for (var kind in this._vertexArrayObjects) {
  31809. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31810. }
  31811. this._vertexArrayObjects = {};
  31812. }
  31813. };
  31814. Geometry.prototype.dispose = function () {
  31815. var meshes = this._meshes;
  31816. var numOfMeshes = meshes.length;
  31817. var index;
  31818. for (index = 0; index < numOfMeshes; index++) {
  31819. this.releaseForMesh(meshes[index]);
  31820. }
  31821. this._meshes = [];
  31822. this._disposeVertexArrayObjects();
  31823. for (var kind in this._vertexBuffers) {
  31824. this._vertexBuffers[kind].dispose();
  31825. }
  31826. this._vertexBuffers = {};
  31827. this._totalVertices = 0;
  31828. if (this._indexBuffer) {
  31829. this._engine._releaseBuffer(this._indexBuffer);
  31830. }
  31831. this._indexBuffer = null;
  31832. this._indices = [];
  31833. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31834. this.delayLoadingFile = null;
  31835. this._delayLoadingFunction = null;
  31836. this._delayInfo = [];
  31837. this._boundingInfo = null;
  31838. this._scene.removeGeometry(this);
  31839. this._isDisposed = true;
  31840. };
  31841. Geometry.prototype.copy = function (id) {
  31842. var vertexData = new BABYLON.VertexData();
  31843. vertexData.indices = [];
  31844. var indices = this.getIndices();
  31845. if (indices) {
  31846. for (var index = 0; index < indices.length; index++) {
  31847. vertexData.indices.push(indices[index]);
  31848. }
  31849. }
  31850. var updatable = false;
  31851. var stopChecking = false;
  31852. var kind;
  31853. for (kind in this._vertexBuffers) {
  31854. // using slice() to make a copy of the array and not just reference it
  31855. var data = this.getVerticesData(kind);
  31856. if (data instanceof Float32Array) {
  31857. vertexData.set(new Float32Array(data), kind);
  31858. }
  31859. else {
  31860. vertexData.set(data.slice(0), kind);
  31861. }
  31862. if (!stopChecking) {
  31863. var vb = this.getVertexBuffer(kind);
  31864. if (vb) {
  31865. updatable = vb.isUpdatable();
  31866. stopChecking = !updatable;
  31867. }
  31868. }
  31869. }
  31870. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31871. geometry.delayLoadState = this.delayLoadState;
  31872. geometry.delayLoadingFile = this.delayLoadingFile;
  31873. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31874. for (kind in this._delayInfo) {
  31875. geometry._delayInfo = geometry._delayInfo || [];
  31876. geometry._delayInfo.push(kind);
  31877. }
  31878. // Bounding info
  31879. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31880. return geometry;
  31881. };
  31882. Geometry.prototype.serialize = function () {
  31883. var serializationObject = {};
  31884. serializationObject.id = this.id;
  31885. serializationObject.updatable = this._updatable;
  31886. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31887. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31888. }
  31889. return serializationObject;
  31890. };
  31891. Geometry.prototype.toNumberArray = function (origin) {
  31892. if (Array.isArray(origin)) {
  31893. return origin;
  31894. }
  31895. else {
  31896. return Array.prototype.slice.call(origin);
  31897. }
  31898. };
  31899. Geometry.prototype.serializeVerticeData = function () {
  31900. var serializationObject = this.serialize();
  31901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31902. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31903. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31904. serializationObject.positions._updatable = true;
  31905. }
  31906. }
  31907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31908. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31910. serializationObject.normals._updatable = true;
  31911. }
  31912. }
  31913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31914. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31916. serializationObject.uvs._updatable = true;
  31917. }
  31918. }
  31919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31920. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31922. serializationObject.uv2s._updatable = true;
  31923. }
  31924. }
  31925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31926. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31928. serializationObject.uv3s._updatable = true;
  31929. }
  31930. }
  31931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31932. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31934. serializationObject.uv4s._updatable = true;
  31935. }
  31936. }
  31937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31938. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31940. serializationObject.uv5s._updatable = true;
  31941. }
  31942. }
  31943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31944. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31946. serializationObject.uv6s._updatable = true;
  31947. }
  31948. }
  31949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31950. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31952. serializationObject.colors._updatable = true;
  31953. }
  31954. }
  31955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31956. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31957. serializationObject.matricesIndices._isExpanded = true;
  31958. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31959. serializationObject.matricesIndices._updatable = true;
  31960. }
  31961. }
  31962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31963. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31965. serializationObject.matricesWeights._updatable = true;
  31966. }
  31967. }
  31968. serializationObject.indices = this.toNumberArray(this.getIndices());
  31969. return serializationObject;
  31970. };
  31971. // Statics
  31972. Geometry.ExtractFromMesh = function (mesh, id) {
  31973. var geometry = mesh._geometry;
  31974. if (!geometry) {
  31975. return null;
  31976. }
  31977. return geometry.copy(id);
  31978. };
  31979. /**
  31980. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31981. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31982. * Be aware Math.random() could cause collisions, but:
  31983. * "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"
  31984. */
  31985. Geometry.RandomId = function () {
  31986. return BABYLON.Tools.RandomId();
  31987. };
  31988. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31989. var scene = mesh.getScene();
  31990. // Geometry
  31991. var geometryId = parsedGeometry.geometryId;
  31992. if (geometryId) {
  31993. var geometry = scene.getGeometryByID(geometryId);
  31994. if (geometry) {
  31995. geometry.applyToMesh(mesh);
  31996. }
  31997. }
  31998. else if (parsedGeometry instanceof ArrayBuffer) {
  31999. var binaryInfo = mesh._binaryInfo;
  32000. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32001. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32002. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32003. }
  32004. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32005. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32006. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32007. }
  32008. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32009. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32010. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32011. }
  32012. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32013. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32014. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32015. }
  32016. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32017. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32018. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32019. }
  32020. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32021. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32022. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32023. }
  32024. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32025. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32026. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32027. }
  32028. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32029. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32030. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32031. }
  32032. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32033. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32034. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32035. }
  32036. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32037. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32038. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32039. }
  32040. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32041. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32042. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32043. }
  32044. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32045. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32046. mesh.setIndices(indicesData, null);
  32047. }
  32048. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32049. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32050. mesh.subMeshes = [];
  32051. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32052. var materialIndex = subMeshesData[(i * 5) + 0];
  32053. var verticesStart = subMeshesData[(i * 5) + 1];
  32054. var verticesCount = subMeshesData[(i * 5) + 2];
  32055. var indexStart = subMeshesData[(i * 5) + 3];
  32056. var indexCount = subMeshesData[(i * 5) + 4];
  32057. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32058. }
  32059. }
  32060. }
  32061. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32062. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32063. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32064. if (parsedGeometry.uvs) {
  32065. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32066. }
  32067. if (parsedGeometry.uvs2) {
  32068. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32069. }
  32070. if (parsedGeometry.uvs3) {
  32071. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32072. }
  32073. if (parsedGeometry.uvs4) {
  32074. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32075. }
  32076. if (parsedGeometry.uvs5) {
  32077. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32078. }
  32079. if (parsedGeometry.uvs6) {
  32080. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32081. }
  32082. if (parsedGeometry.colors) {
  32083. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32084. }
  32085. if (parsedGeometry.matricesIndices) {
  32086. if (!parsedGeometry.matricesIndices._isExpanded) {
  32087. var floatIndices = [];
  32088. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32089. var matricesIndex = parsedGeometry.matricesIndices[i];
  32090. floatIndices.push(matricesIndex & 0x000000FF);
  32091. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32092. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32093. floatIndices.push(matricesIndex >> 24);
  32094. }
  32095. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32096. }
  32097. else {
  32098. delete parsedGeometry.matricesIndices._isExpanded;
  32099. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32100. }
  32101. }
  32102. if (parsedGeometry.matricesIndicesExtra) {
  32103. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32104. var floatIndices = [];
  32105. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32106. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32107. floatIndices.push(matricesIndex & 0x000000FF);
  32108. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32109. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32110. floatIndices.push(matricesIndex >> 24);
  32111. }
  32112. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32113. }
  32114. else {
  32115. delete parsedGeometry.matricesIndices._isExpanded;
  32116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32117. }
  32118. }
  32119. if (parsedGeometry.matricesWeights) {
  32120. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32121. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32122. }
  32123. if (parsedGeometry.matricesWeightsExtra) {
  32124. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32125. }
  32126. mesh.setIndices(parsedGeometry.indices, null);
  32127. }
  32128. // SubMeshes
  32129. if (parsedGeometry.subMeshes) {
  32130. mesh.subMeshes = [];
  32131. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32132. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32133. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32134. }
  32135. }
  32136. // Flat shading
  32137. if (mesh._shouldGenerateFlatShading) {
  32138. mesh.convertToFlatShadedMesh();
  32139. delete mesh._shouldGenerateFlatShading;
  32140. }
  32141. // Update
  32142. mesh.computeWorldMatrix(true);
  32143. // Octree
  32144. var sceneOctree = scene.selectionOctree;
  32145. if (sceneOctree !== undefined && sceneOctree !== null) {
  32146. sceneOctree.addMesh(mesh);
  32147. }
  32148. };
  32149. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32150. var epsilon = 1e-3;
  32151. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32152. return;
  32153. }
  32154. var noInfluenceBoneIndex = 0.0;
  32155. if (parsedGeometry.skeletonId > -1) {
  32156. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32157. if (!skeleton) {
  32158. return;
  32159. }
  32160. noInfluenceBoneIndex = skeleton.bones.length;
  32161. }
  32162. else {
  32163. return;
  32164. }
  32165. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32166. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32167. var matricesWeights = parsedGeometry.matricesWeights;
  32168. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32169. var influencers = parsedGeometry.numBoneInfluencer;
  32170. var size = matricesWeights.length;
  32171. for (var i = 0; i < size; i += 4) {
  32172. var weight = 0.0;
  32173. var firstZeroWeight = -1;
  32174. for (var j = 0; j < 4; j++) {
  32175. var w = matricesWeights[i + j];
  32176. weight += w;
  32177. if (w < epsilon && firstZeroWeight < 0) {
  32178. firstZeroWeight = j;
  32179. }
  32180. }
  32181. if (matricesWeightsExtra) {
  32182. for (var j = 0; j < 4; j++) {
  32183. var w = matricesWeightsExtra[i + j];
  32184. weight += w;
  32185. if (w < epsilon && firstZeroWeight < 0) {
  32186. firstZeroWeight = j + 4;
  32187. }
  32188. }
  32189. }
  32190. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32191. firstZeroWeight = influencers - 1;
  32192. }
  32193. if (weight > epsilon) {
  32194. var mweight = 1.0 / weight;
  32195. for (var j = 0; j < 4; j++) {
  32196. matricesWeights[i + j] *= mweight;
  32197. }
  32198. if (matricesWeightsExtra) {
  32199. for (var j = 0; j < 4; j++) {
  32200. matricesWeightsExtra[i + j] *= mweight;
  32201. }
  32202. }
  32203. }
  32204. else {
  32205. if (firstZeroWeight >= 4) {
  32206. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32207. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32208. }
  32209. else {
  32210. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32211. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32212. }
  32213. }
  32214. }
  32215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32216. if (parsedGeometry.matricesWeightsExtra) {
  32217. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32218. }
  32219. };
  32220. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32221. if (scene.getGeometryByID(parsedVertexData.id)) {
  32222. return null; // null since geometry could be something else than a box...
  32223. }
  32224. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32225. if (BABYLON.Tags) {
  32226. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32227. }
  32228. if (parsedVertexData.delayLoadingFile) {
  32229. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32230. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32231. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32232. geometry._delayInfo = [];
  32233. if (parsedVertexData.hasUVs) {
  32234. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32235. }
  32236. if (parsedVertexData.hasUVs2) {
  32237. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32238. }
  32239. if (parsedVertexData.hasUVs3) {
  32240. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32241. }
  32242. if (parsedVertexData.hasUVs4) {
  32243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32244. }
  32245. if (parsedVertexData.hasUVs5) {
  32246. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32247. }
  32248. if (parsedVertexData.hasUVs6) {
  32249. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32250. }
  32251. if (parsedVertexData.hasColors) {
  32252. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32253. }
  32254. if (parsedVertexData.hasMatricesIndices) {
  32255. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32256. }
  32257. if (parsedVertexData.hasMatricesWeights) {
  32258. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32259. }
  32260. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32261. }
  32262. else {
  32263. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32264. }
  32265. scene.pushGeometry(geometry, true);
  32266. return geometry;
  32267. };
  32268. return Geometry;
  32269. }());
  32270. BABYLON.Geometry = Geometry;
  32271. /////// Primitives //////////////////////////////////////////////
  32272. //export module Geometry.Primitives {
  32273. /// Abstract class
  32274. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32275. __extends(_PrimitiveGeometry, _super);
  32276. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32277. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32278. if (mesh === void 0) { mesh = null; }
  32279. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32280. _this._canBeRegenerated = _canBeRegenerated;
  32281. _this._beingRegenerated = true;
  32282. _this.regenerate();
  32283. _this._beingRegenerated = false;
  32284. return _this;
  32285. }
  32286. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32287. return this._canBeRegenerated;
  32288. };
  32289. _PrimitiveGeometry.prototype.regenerate = function () {
  32290. if (!this._canBeRegenerated) {
  32291. return;
  32292. }
  32293. this._beingRegenerated = true;
  32294. this.setAllVerticesData(this._regenerateVertexData(), false);
  32295. this._beingRegenerated = false;
  32296. };
  32297. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32298. return _super.prototype.copy.call(this, id);
  32299. };
  32300. // overrides
  32301. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32302. if (!this._beingRegenerated) {
  32303. return;
  32304. }
  32305. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32306. };
  32307. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32308. if (!this._beingRegenerated) {
  32309. return;
  32310. }
  32311. _super.prototype.setVerticesData.call(this, kind, data, false);
  32312. };
  32313. // to override
  32314. // protected
  32315. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32316. throw new Error("Abstract method");
  32317. };
  32318. _PrimitiveGeometry.prototype.copy = function (id) {
  32319. throw new Error("Must be overriden in sub-classes.");
  32320. };
  32321. _PrimitiveGeometry.prototype.serialize = function () {
  32322. var serializationObject = _super.prototype.serialize.call(this);
  32323. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32324. return serializationObject;
  32325. };
  32326. return _PrimitiveGeometry;
  32327. }(Geometry));
  32328. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32329. var RibbonGeometry = /** @class */ (function (_super) {
  32330. __extends(RibbonGeometry, _super);
  32331. // Members
  32332. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32333. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32334. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32335. _this.pathArray = pathArray;
  32336. _this.closeArray = closeArray;
  32337. _this.closePath = closePath;
  32338. _this.offset = offset;
  32339. _this.side = side;
  32340. return _this;
  32341. }
  32342. RibbonGeometry.prototype._regenerateVertexData = function () {
  32343. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32344. };
  32345. RibbonGeometry.prototype.copy = function (id) {
  32346. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32347. };
  32348. return RibbonGeometry;
  32349. }(_PrimitiveGeometry));
  32350. BABYLON.RibbonGeometry = RibbonGeometry;
  32351. var BoxGeometry = /** @class */ (function (_super) {
  32352. __extends(BoxGeometry, _super);
  32353. // Members
  32354. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32355. if (mesh === void 0) { mesh = null; }
  32356. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32357. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32358. _this.size = size;
  32359. _this.side = side;
  32360. return _this;
  32361. }
  32362. BoxGeometry.prototype._regenerateVertexData = function () {
  32363. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32364. };
  32365. BoxGeometry.prototype.copy = function (id) {
  32366. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32367. };
  32368. BoxGeometry.prototype.serialize = function () {
  32369. var serializationObject = _super.prototype.serialize.call(this);
  32370. serializationObject.size = this.size;
  32371. return serializationObject;
  32372. };
  32373. BoxGeometry.Parse = function (parsedBox, scene) {
  32374. if (scene.getGeometryByID(parsedBox.id)) {
  32375. return null; // null since geometry could be something else than a box...
  32376. }
  32377. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32378. if (BABYLON.Tags) {
  32379. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32380. }
  32381. scene.pushGeometry(box, true);
  32382. return box;
  32383. };
  32384. return BoxGeometry;
  32385. }(_PrimitiveGeometry));
  32386. BABYLON.BoxGeometry = BoxGeometry;
  32387. var SphereGeometry = /** @class */ (function (_super) {
  32388. __extends(SphereGeometry, _super);
  32389. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32390. if (mesh === void 0) { mesh = null; }
  32391. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32392. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32393. _this.segments = segments;
  32394. _this.diameter = diameter;
  32395. _this.side = side;
  32396. return _this;
  32397. }
  32398. SphereGeometry.prototype._regenerateVertexData = function () {
  32399. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32400. };
  32401. SphereGeometry.prototype.copy = function (id) {
  32402. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32403. };
  32404. SphereGeometry.prototype.serialize = function () {
  32405. var serializationObject = _super.prototype.serialize.call(this);
  32406. serializationObject.segments = this.segments;
  32407. serializationObject.diameter = this.diameter;
  32408. return serializationObject;
  32409. };
  32410. SphereGeometry.Parse = function (parsedSphere, scene) {
  32411. if (scene.getGeometryByID(parsedSphere.id)) {
  32412. return null; // null since geometry could be something else than a sphere...
  32413. }
  32414. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32415. if (BABYLON.Tags) {
  32416. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32417. }
  32418. scene.pushGeometry(sphere, true);
  32419. return sphere;
  32420. };
  32421. return SphereGeometry;
  32422. }(_PrimitiveGeometry));
  32423. BABYLON.SphereGeometry = SphereGeometry;
  32424. var DiscGeometry = /** @class */ (function (_super) {
  32425. __extends(DiscGeometry, _super);
  32426. // Members
  32427. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32428. if (mesh === void 0) { mesh = null; }
  32429. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32430. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32431. _this.radius = radius;
  32432. _this.tessellation = tessellation;
  32433. _this.side = side;
  32434. return _this;
  32435. }
  32436. DiscGeometry.prototype._regenerateVertexData = function () {
  32437. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32438. };
  32439. DiscGeometry.prototype.copy = function (id) {
  32440. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32441. };
  32442. return DiscGeometry;
  32443. }(_PrimitiveGeometry));
  32444. BABYLON.DiscGeometry = DiscGeometry;
  32445. var CylinderGeometry = /** @class */ (function (_super) {
  32446. __extends(CylinderGeometry, _super);
  32447. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32448. if (subdivisions === void 0) { subdivisions = 1; }
  32449. if (mesh === void 0) { mesh = null; }
  32450. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32451. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32452. _this.height = height;
  32453. _this.diameterTop = diameterTop;
  32454. _this.diameterBottom = diameterBottom;
  32455. _this.tessellation = tessellation;
  32456. _this.subdivisions = subdivisions;
  32457. _this.side = side;
  32458. return _this;
  32459. }
  32460. CylinderGeometry.prototype._regenerateVertexData = function () {
  32461. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32462. };
  32463. CylinderGeometry.prototype.copy = function (id) {
  32464. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32465. };
  32466. CylinderGeometry.prototype.serialize = function () {
  32467. var serializationObject = _super.prototype.serialize.call(this);
  32468. serializationObject.height = this.height;
  32469. serializationObject.diameterTop = this.diameterTop;
  32470. serializationObject.diameterBottom = this.diameterBottom;
  32471. serializationObject.tessellation = this.tessellation;
  32472. return serializationObject;
  32473. };
  32474. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32475. if (scene.getGeometryByID(parsedCylinder.id)) {
  32476. return null; // null since geometry could be something else than a cylinder...
  32477. }
  32478. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32479. if (BABYLON.Tags) {
  32480. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32481. }
  32482. scene.pushGeometry(cylinder, true);
  32483. return cylinder;
  32484. };
  32485. return CylinderGeometry;
  32486. }(_PrimitiveGeometry));
  32487. BABYLON.CylinderGeometry = CylinderGeometry;
  32488. var TorusGeometry = /** @class */ (function (_super) {
  32489. __extends(TorusGeometry, _super);
  32490. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32491. if (mesh === void 0) { mesh = null; }
  32492. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32493. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32494. _this.diameter = diameter;
  32495. _this.thickness = thickness;
  32496. _this.tessellation = tessellation;
  32497. _this.side = side;
  32498. return _this;
  32499. }
  32500. TorusGeometry.prototype._regenerateVertexData = function () {
  32501. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32502. };
  32503. TorusGeometry.prototype.copy = function (id) {
  32504. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32505. };
  32506. TorusGeometry.prototype.serialize = function () {
  32507. var serializationObject = _super.prototype.serialize.call(this);
  32508. serializationObject.diameter = this.diameter;
  32509. serializationObject.thickness = this.thickness;
  32510. serializationObject.tessellation = this.tessellation;
  32511. return serializationObject;
  32512. };
  32513. TorusGeometry.Parse = function (parsedTorus, scene) {
  32514. if (scene.getGeometryByID(parsedTorus.id)) {
  32515. return null; // null since geometry could be something else than a torus...
  32516. }
  32517. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32518. if (BABYLON.Tags) {
  32519. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32520. }
  32521. scene.pushGeometry(torus, true);
  32522. return torus;
  32523. };
  32524. return TorusGeometry;
  32525. }(_PrimitiveGeometry));
  32526. BABYLON.TorusGeometry = TorusGeometry;
  32527. var GroundGeometry = /** @class */ (function (_super) {
  32528. __extends(GroundGeometry, _super);
  32529. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32530. if (mesh === void 0) { mesh = null; }
  32531. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32532. _this.width = width;
  32533. _this.height = height;
  32534. _this.subdivisions = subdivisions;
  32535. return _this;
  32536. }
  32537. GroundGeometry.prototype._regenerateVertexData = function () {
  32538. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32539. };
  32540. GroundGeometry.prototype.copy = function (id) {
  32541. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32542. };
  32543. GroundGeometry.prototype.serialize = function () {
  32544. var serializationObject = _super.prototype.serialize.call(this);
  32545. serializationObject.width = this.width;
  32546. serializationObject.height = this.height;
  32547. serializationObject.subdivisions = this.subdivisions;
  32548. return serializationObject;
  32549. };
  32550. GroundGeometry.Parse = function (parsedGround, scene) {
  32551. if (scene.getGeometryByID(parsedGround.id)) {
  32552. return null; // null since geometry could be something else than a ground...
  32553. }
  32554. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32555. if (BABYLON.Tags) {
  32556. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32557. }
  32558. scene.pushGeometry(ground, true);
  32559. return ground;
  32560. };
  32561. return GroundGeometry;
  32562. }(_PrimitiveGeometry));
  32563. BABYLON.GroundGeometry = GroundGeometry;
  32564. var TiledGroundGeometry = /** @class */ (function (_super) {
  32565. __extends(TiledGroundGeometry, _super);
  32566. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32567. if (mesh === void 0) { mesh = null; }
  32568. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32569. _this.xmin = xmin;
  32570. _this.zmin = zmin;
  32571. _this.xmax = xmax;
  32572. _this.zmax = zmax;
  32573. _this.subdivisions = subdivisions;
  32574. _this.precision = precision;
  32575. return _this;
  32576. }
  32577. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32578. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32579. };
  32580. TiledGroundGeometry.prototype.copy = function (id) {
  32581. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32582. };
  32583. return TiledGroundGeometry;
  32584. }(_PrimitiveGeometry));
  32585. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32586. var PlaneGeometry = /** @class */ (function (_super) {
  32587. __extends(PlaneGeometry, _super);
  32588. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32589. if (mesh === void 0) { mesh = null; }
  32590. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32591. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32592. _this.size = size;
  32593. _this.side = side;
  32594. return _this;
  32595. }
  32596. PlaneGeometry.prototype._regenerateVertexData = function () {
  32597. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32598. };
  32599. PlaneGeometry.prototype.copy = function (id) {
  32600. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32601. };
  32602. PlaneGeometry.prototype.serialize = function () {
  32603. var serializationObject = _super.prototype.serialize.call(this);
  32604. serializationObject.size = this.size;
  32605. return serializationObject;
  32606. };
  32607. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32608. if (scene.getGeometryByID(parsedPlane.id)) {
  32609. return null; // null since geometry could be something else than a ground...
  32610. }
  32611. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32612. if (BABYLON.Tags) {
  32613. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32614. }
  32615. scene.pushGeometry(plane, true);
  32616. return plane;
  32617. };
  32618. return PlaneGeometry;
  32619. }(_PrimitiveGeometry));
  32620. BABYLON.PlaneGeometry = PlaneGeometry;
  32621. var TorusKnotGeometry = /** @class */ (function (_super) {
  32622. __extends(TorusKnotGeometry, _super);
  32623. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32624. if (mesh === void 0) { mesh = null; }
  32625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32626. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32627. _this.radius = radius;
  32628. _this.tube = tube;
  32629. _this.radialSegments = radialSegments;
  32630. _this.tubularSegments = tubularSegments;
  32631. _this.p = p;
  32632. _this.q = q;
  32633. _this.side = side;
  32634. return _this;
  32635. }
  32636. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32637. 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 });
  32638. };
  32639. TorusKnotGeometry.prototype.copy = function (id) {
  32640. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32641. };
  32642. TorusKnotGeometry.prototype.serialize = function () {
  32643. var serializationObject = _super.prototype.serialize.call(this);
  32644. serializationObject.radius = this.radius;
  32645. serializationObject.tube = this.tube;
  32646. serializationObject.radialSegments = this.radialSegments;
  32647. serializationObject.tubularSegments = this.tubularSegments;
  32648. serializationObject.p = this.p;
  32649. serializationObject.q = this.q;
  32650. return serializationObject;
  32651. };
  32652. ;
  32653. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32654. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32655. return null; // null since geometry could be something else than a ground...
  32656. }
  32657. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32658. if (BABYLON.Tags) {
  32659. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32660. }
  32661. scene.pushGeometry(torusKnot, true);
  32662. return torusKnot;
  32663. };
  32664. return TorusKnotGeometry;
  32665. }(_PrimitiveGeometry));
  32666. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32667. //}
  32668. })(BABYLON || (BABYLON = {}));
  32669. //# sourceMappingURL=babylon.geometry.js.map
  32670. var BABYLON;
  32671. (function (BABYLON) {
  32672. var PostProcessManager = /** @class */ (function () {
  32673. function PostProcessManager(scene) {
  32674. this._vertexBuffers = {};
  32675. this._scene = scene;
  32676. }
  32677. PostProcessManager.prototype._prepareBuffers = function () {
  32678. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32679. return;
  32680. }
  32681. // VBO
  32682. var vertices = [];
  32683. vertices.push(1, 1);
  32684. vertices.push(-1, 1);
  32685. vertices.push(-1, -1);
  32686. vertices.push(1, -1);
  32687. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32688. this._buildIndexBuffer();
  32689. };
  32690. PostProcessManager.prototype._buildIndexBuffer = function () {
  32691. // Indices
  32692. var indices = [];
  32693. indices.push(0);
  32694. indices.push(1);
  32695. indices.push(2);
  32696. indices.push(0);
  32697. indices.push(2);
  32698. indices.push(3);
  32699. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32700. };
  32701. PostProcessManager.prototype._rebuild = function () {
  32702. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32703. if (!vb) {
  32704. return;
  32705. }
  32706. vb._rebuild();
  32707. this._buildIndexBuffer();
  32708. };
  32709. // Methods
  32710. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32711. if (sourceTexture === void 0) { sourceTexture = null; }
  32712. if (postProcesses === void 0) { postProcesses = null; }
  32713. var camera = this._scene.activeCamera;
  32714. if (!camera) {
  32715. return false;
  32716. }
  32717. var postProcesses = postProcesses || camera._postProcesses;
  32718. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32719. return false;
  32720. }
  32721. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32722. return true;
  32723. };
  32724. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32725. if (targetTexture === void 0) { targetTexture = null; }
  32726. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32727. var engine = this._scene.getEngine();
  32728. for (var index = 0; index < postProcesses.length; index++) {
  32729. if (index < postProcesses.length - 1) {
  32730. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32731. }
  32732. else {
  32733. if (targetTexture) {
  32734. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32735. }
  32736. else {
  32737. engine.restoreDefaultFramebuffer();
  32738. }
  32739. }
  32740. var pp = postProcesses[index];
  32741. var effect = pp.apply();
  32742. if (effect) {
  32743. pp.onBeforeRenderObservable.notifyObservers(effect);
  32744. // VBOs
  32745. this._prepareBuffers();
  32746. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32747. // Draw order
  32748. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32749. pp.onAfterRenderObservable.notifyObservers(effect);
  32750. }
  32751. }
  32752. // Restore depth buffer
  32753. engine.setDepthBuffer(true);
  32754. engine.setDepthWrite(true);
  32755. };
  32756. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32757. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32758. var camera = this._scene.activeCamera;
  32759. if (!camera) {
  32760. return;
  32761. }
  32762. postProcesses = postProcesses || camera._postProcesses;
  32763. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32764. return;
  32765. }
  32766. var engine = this._scene.getEngine();
  32767. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32768. if (index < len - 1) {
  32769. postProcesses[index + 1].activate(camera, targetTexture);
  32770. }
  32771. else {
  32772. if (targetTexture) {
  32773. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32774. }
  32775. else {
  32776. engine.restoreDefaultFramebuffer();
  32777. }
  32778. }
  32779. if (doNotPresent) {
  32780. break;
  32781. }
  32782. var pp = postProcesses[index];
  32783. var effect = pp.apply();
  32784. if (effect) {
  32785. pp.onBeforeRenderObservable.notifyObservers(effect);
  32786. // VBOs
  32787. this._prepareBuffers();
  32788. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32789. // Draw order
  32790. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32791. pp.onAfterRenderObservable.notifyObservers(effect);
  32792. }
  32793. }
  32794. // Restore states
  32795. engine.setDepthBuffer(true);
  32796. engine.setDepthWrite(true);
  32797. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32798. };
  32799. PostProcessManager.prototype.dispose = function () {
  32800. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32801. if (buffer) {
  32802. buffer.dispose();
  32803. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32804. }
  32805. if (this._indexBuffer) {
  32806. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32807. this._indexBuffer = null;
  32808. }
  32809. };
  32810. return PostProcessManager;
  32811. }());
  32812. BABYLON.PostProcessManager = PostProcessManager;
  32813. })(BABYLON || (BABYLON = {}));
  32814. //# sourceMappingURL=babylon.postProcessManager.js.map
  32815. BABYLON.Effect.IncludesShadersStore['depthPrePass'] = "#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif";
  32816. BABYLON.Effect.IncludesShadersStore['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";
  32817. BABYLON.Effect.IncludesShadersStore['instancesDeclaration'] = "#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif";
  32818. BABYLON.Effect.IncludesShadersStore['pointCloudVertexDeclaration'] = "#ifdef POINTSIZE\nuniform float pointSize;\n#endif";
  32819. BABYLON.Effect.IncludesShadersStore['bumpVertexDeclaration'] = "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n";
  32820. BABYLON.Effect.IncludesShadersStore['clipPlaneVertexDeclaration'] = "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif";
  32821. BABYLON.Effect.IncludesShadersStore['fogVertexDeclaration'] = "#ifdef FOG\nvarying vec3 vFogDistance;\n#endif";
  32822. BABYLON.Effect.IncludesShadersStore['morphTargetsVertexGlobalDeclaration'] = "#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif";
  32823. BABYLON.Effect.IncludesShadersStore['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";
  32824. BABYLON.Effect.IncludesShadersStore['logDepthDeclaration'] = "#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif";
  32825. BABYLON.Effect.IncludesShadersStore['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";
  32826. BABYLON.Effect.IncludesShadersStore['instancesVertex'] = "#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif";
  32827. BABYLON.Effect.IncludesShadersStore['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";
  32828. BABYLON.Effect.IncludesShadersStore['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";
  32829. BABYLON.Effect.IncludesShadersStore['clipPlaneVertex'] = "#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif";
  32830. BABYLON.Effect.IncludesShadersStore['fogVertex'] = "#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif";
  32831. BABYLON.Effect.IncludesShadersStore['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";
  32832. BABYLON.Effect.IncludesShadersStore['pointCloudVertex'] = "#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif";
  32833. BABYLON.Effect.IncludesShadersStore['logDepthVertex'] = "#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif";
  32834. BABYLON.Effect.IncludesShadersStore['helperFunctions'] = "const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}";
  32835. BABYLON.Effect.IncludesShadersStore['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";
  32836. BABYLON.Effect.IncludesShadersStore['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";
  32837. BABYLON.Effect.IncludesShadersStore['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";
  32838. BABYLON.Effect.IncludesShadersStore['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";
  32839. BABYLON.Effect.IncludesShadersStore['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";
  32840. BABYLON.Effect.IncludesShadersStore['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};";
  32841. BABYLON.Effect.IncludesShadersStore['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";
  32842. BABYLON.Effect.IncludesShadersStore['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";
  32843. BABYLON.Effect.IncludesShadersStore['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}";
  32844. BABYLON.Effect.IncludesShadersStore['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";
  32845. BABYLON.Effect.IncludesShadersStore['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}";
  32846. BABYLON.Effect.IncludesShadersStore['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";
  32847. BABYLON.Effect.IncludesShadersStore['clipPlaneFragmentDeclaration'] = "#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif";
  32848. BABYLON.Effect.IncludesShadersStore['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";
  32849. BABYLON.Effect.IncludesShadersStore['clipPlaneFragment'] = "#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif";
  32850. BABYLON.Effect.IncludesShadersStore['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";
  32851. BABYLON.Effect.IncludesShadersStore['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";
  32852. BABYLON.Effect.IncludesShadersStore['logDepthFragment'] = "#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif";
  32853. BABYLON.Effect.IncludesShadersStore['fogFragment'] = "#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif";
  32854. var BABYLON;
  32855. (function (BABYLON) {
  32856. /**
  32857. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32858. */
  32859. var PerformanceMonitor = /** @class */ (function () {
  32860. /**
  32861. * constructor
  32862. * @param frameSampleSize The number of samples required to saturate the sliding window
  32863. */
  32864. function PerformanceMonitor(frameSampleSize) {
  32865. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32866. this._enabled = true;
  32867. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32868. }
  32869. /**
  32870. * Samples current frame
  32871. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32872. */
  32873. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32874. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32875. if (!this._enabled)
  32876. return;
  32877. if (this._lastFrameTimeMs != null) {
  32878. var dt = timeMs - this._lastFrameTimeMs;
  32879. this._rollingFrameTime.add(dt);
  32880. }
  32881. this._lastFrameTimeMs = timeMs;
  32882. };
  32883. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32884. /**
  32885. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32886. * @return Average frame time in milliseconds
  32887. */
  32888. get: function () {
  32889. return this._rollingFrameTime.average;
  32890. },
  32891. enumerable: true,
  32892. configurable: true
  32893. });
  32894. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32895. /**
  32896. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32897. * @return Frame time variance in milliseconds squared
  32898. */
  32899. get: function () {
  32900. return this._rollingFrameTime.variance;
  32901. },
  32902. enumerable: true,
  32903. configurable: true
  32904. });
  32905. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32906. /**
  32907. * Returns the frame time of the most recent frame
  32908. * @return Frame time in milliseconds
  32909. */
  32910. get: function () {
  32911. return this._rollingFrameTime.history(0);
  32912. },
  32913. enumerable: true,
  32914. configurable: true
  32915. });
  32916. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32917. /**
  32918. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32919. * @return Framerate in frames per second
  32920. */
  32921. get: function () {
  32922. return 1000.0 / this._rollingFrameTime.average;
  32923. },
  32924. enumerable: true,
  32925. configurable: true
  32926. });
  32927. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32928. /**
  32929. * Returns the average framerate in frames per second using the most recent frame time
  32930. * @return Framerate in frames per second
  32931. */
  32932. get: function () {
  32933. var history = this._rollingFrameTime.history(0);
  32934. if (history === 0) {
  32935. return 0;
  32936. }
  32937. return 1000.0 / history;
  32938. },
  32939. enumerable: true,
  32940. configurable: true
  32941. });
  32942. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32943. /**
  32944. * Returns true if enough samples have been taken to completely fill the sliding window
  32945. * @return true if saturated
  32946. */
  32947. get: function () {
  32948. return this._rollingFrameTime.isSaturated();
  32949. },
  32950. enumerable: true,
  32951. configurable: true
  32952. });
  32953. /**
  32954. * Enables contributions to the sliding window sample set
  32955. */
  32956. PerformanceMonitor.prototype.enable = function () {
  32957. this._enabled = true;
  32958. };
  32959. /**
  32960. * Disables contributions to the sliding window sample set
  32961. * Samples will not be interpolated over the disabled period
  32962. */
  32963. PerformanceMonitor.prototype.disable = function () {
  32964. this._enabled = false;
  32965. //clear last sample to avoid interpolating over the disabled period when next enabled
  32966. this._lastFrameTimeMs = null;
  32967. };
  32968. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32969. /**
  32970. * Returns true if sampling is enabled
  32971. * @return true if enabled
  32972. */
  32973. get: function () {
  32974. return this._enabled;
  32975. },
  32976. enumerable: true,
  32977. configurable: true
  32978. });
  32979. /**
  32980. * Resets performance monitor
  32981. */
  32982. PerformanceMonitor.prototype.reset = function () {
  32983. //clear last sample to avoid interpolating over the disabled period when next enabled
  32984. this._lastFrameTimeMs = null;
  32985. //wipe record
  32986. this._rollingFrameTime.reset();
  32987. };
  32988. return PerformanceMonitor;
  32989. }());
  32990. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32991. /**
  32992. * RollingAverage
  32993. *
  32994. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32995. */
  32996. var RollingAverage = /** @class */ (function () {
  32997. /**
  32998. * constructor
  32999. * @param length The number of samples required to saturate the sliding window
  33000. */
  33001. function RollingAverage(length) {
  33002. this._samples = new Array(length);
  33003. this.reset();
  33004. }
  33005. /**
  33006. * Adds a sample to the sample set
  33007. * @param v The sample value
  33008. */
  33009. RollingAverage.prototype.add = function (v) {
  33010. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33011. var delta;
  33012. //we need to check if we've already wrapped round
  33013. if (this.isSaturated()) {
  33014. //remove bottom of stack from mean
  33015. var bottomValue = this._samples[this._pos];
  33016. delta = bottomValue - this.average;
  33017. this.average -= delta / (this._sampleCount - 1);
  33018. this._m2 -= delta * (bottomValue - this.average);
  33019. }
  33020. else {
  33021. this._sampleCount++;
  33022. }
  33023. //add new value to mean
  33024. delta = v - this.average;
  33025. this.average += delta / (this._sampleCount);
  33026. this._m2 += delta * (v - this.average);
  33027. //set the new variance
  33028. this.variance = this._m2 / (this._sampleCount - 1);
  33029. this._samples[this._pos] = v;
  33030. this._pos++;
  33031. this._pos %= this._samples.length; //positive wrap around
  33032. };
  33033. /**
  33034. * Returns previously added values or null if outside of history or outside the sliding window domain
  33035. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33036. * @return Value previously recorded with add() or null if outside of range
  33037. */
  33038. RollingAverage.prototype.history = function (i) {
  33039. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33040. return 0;
  33041. }
  33042. var i0 = this._wrapPosition(this._pos - 1.0);
  33043. return this._samples[this._wrapPosition(i0 - i)];
  33044. };
  33045. /**
  33046. * Returns true if enough samples have been taken to completely fill the sliding window
  33047. * @return true if sample-set saturated
  33048. */
  33049. RollingAverage.prototype.isSaturated = function () {
  33050. return this._sampleCount >= this._samples.length;
  33051. };
  33052. /**
  33053. * Resets the rolling average (equivalent to 0 samples taken so far)
  33054. */
  33055. RollingAverage.prototype.reset = function () {
  33056. this.average = 0;
  33057. this.variance = 0;
  33058. this._sampleCount = 0;
  33059. this._pos = 0;
  33060. this._m2 = 0;
  33061. };
  33062. /**
  33063. * Wraps a value around the sample range boundaries
  33064. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33065. * @return Wrapped position in sample range
  33066. */
  33067. RollingAverage.prototype._wrapPosition = function (i) {
  33068. var max = this._samples.length;
  33069. return ((i % max) + max) % max;
  33070. };
  33071. return RollingAverage;
  33072. }());
  33073. BABYLON.RollingAverage = RollingAverage;
  33074. })(BABYLON || (BABYLON = {}));
  33075. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33076. var BABYLON;
  33077. (function (BABYLON) {
  33078. /**
  33079. * This groups together the common properties used for image processing either in direct forward pass
  33080. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33081. * or not.
  33082. */
  33083. var ImageProcessingConfiguration = /** @class */ (function () {
  33084. function ImageProcessingConfiguration() {
  33085. /**
  33086. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33087. */
  33088. this.colorCurves = new BABYLON.ColorCurves();
  33089. this._colorCurvesEnabled = false;
  33090. this._colorGradingEnabled = false;
  33091. this._colorGradingWithGreenDepth = true;
  33092. this._colorGradingBGR = true;
  33093. this._exposure = 1.0;
  33094. this._toneMappingEnabled = false;
  33095. this._contrast = 1.0;
  33096. /**
  33097. * Vignette stretch size.
  33098. */
  33099. this.vignetteStretch = 0;
  33100. /**
  33101. * Vignette centre X Offset.
  33102. */
  33103. this.vignetteCentreX = 0;
  33104. /**
  33105. * Vignette centre Y Offset.
  33106. */
  33107. this.vignetteCentreY = 0;
  33108. /**
  33109. * Vignette weight or intensity of the vignette effect.
  33110. */
  33111. this.vignetteWeight = 1.5;
  33112. /**
  33113. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33114. * if vignetteEnabled is set to true.
  33115. */
  33116. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33117. /**
  33118. * Camera field of view used by the Vignette effect.
  33119. */
  33120. this.vignetteCameraFov = 0.5;
  33121. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33122. this._vignetteEnabled = false;
  33123. this._applyByPostProcess = false;
  33124. this._isEnabled = true;
  33125. /**
  33126. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33127. * @type {BABYLON.Observable}
  33128. */
  33129. this.onUpdateParameters = new BABYLON.Observable();
  33130. }
  33131. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33132. /**
  33133. * Gets wether the color curves effect is enabled.
  33134. */
  33135. get: function () {
  33136. return this._colorCurvesEnabled;
  33137. },
  33138. /**
  33139. * Sets wether the color curves effect is enabled.
  33140. */
  33141. set: function (value) {
  33142. if (this._colorCurvesEnabled === value) {
  33143. return;
  33144. }
  33145. this._colorCurvesEnabled = value;
  33146. this._updateParameters();
  33147. },
  33148. enumerable: true,
  33149. configurable: true
  33150. });
  33151. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33152. /**
  33153. * Gets wether the color grading effect is enabled.
  33154. */
  33155. get: function () {
  33156. return this._colorGradingEnabled;
  33157. },
  33158. /**
  33159. * Sets wether the color grading effect is enabled.
  33160. */
  33161. set: function (value) {
  33162. if (this._colorGradingEnabled === value) {
  33163. return;
  33164. }
  33165. this._colorGradingEnabled = value;
  33166. this._updateParameters();
  33167. },
  33168. enumerable: true,
  33169. configurable: true
  33170. });
  33171. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33172. /**
  33173. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33174. */
  33175. get: function () {
  33176. return this._colorGradingWithGreenDepth;
  33177. },
  33178. /**
  33179. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33180. */
  33181. set: function (value) {
  33182. if (this._colorGradingWithGreenDepth === value) {
  33183. return;
  33184. }
  33185. this._colorGradingWithGreenDepth = value;
  33186. this._updateParameters();
  33187. },
  33188. enumerable: true,
  33189. configurable: true
  33190. });
  33191. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33192. /**
  33193. * Gets wether the color grading texture contains BGR values.
  33194. */
  33195. get: function () {
  33196. return this._colorGradingBGR;
  33197. },
  33198. /**
  33199. * Sets wether the color grading texture contains BGR values.
  33200. */
  33201. set: function (value) {
  33202. if (this._colorGradingBGR === value) {
  33203. return;
  33204. }
  33205. this._colorGradingBGR = value;
  33206. this._updateParameters();
  33207. },
  33208. enumerable: true,
  33209. configurable: true
  33210. });
  33211. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33212. /**
  33213. * Gets the Exposure used in the effect.
  33214. */
  33215. get: function () {
  33216. return this._exposure;
  33217. },
  33218. /**
  33219. * Sets the Exposure used in the effect.
  33220. */
  33221. set: function (value) {
  33222. if (this._exposure === value) {
  33223. return;
  33224. }
  33225. this._exposure = value;
  33226. this._updateParameters();
  33227. },
  33228. enumerable: true,
  33229. configurable: true
  33230. });
  33231. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33232. /**
  33233. * Gets wether the tone mapping effect is enabled.
  33234. */
  33235. get: function () {
  33236. return this._toneMappingEnabled;
  33237. },
  33238. /**
  33239. * Sets wether the tone mapping effect is enabled.
  33240. */
  33241. set: function (value) {
  33242. if (this._toneMappingEnabled === value) {
  33243. return;
  33244. }
  33245. this._toneMappingEnabled = value;
  33246. this._updateParameters();
  33247. },
  33248. enumerable: true,
  33249. configurable: true
  33250. });
  33251. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33252. /**
  33253. * Gets the contrast used in the effect.
  33254. */
  33255. get: function () {
  33256. return this._contrast;
  33257. },
  33258. /**
  33259. * Sets the contrast used in the effect.
  33260. */
  33261. set: function (value) {
  33262. if (this._contrast === value) {
  33263. return;
  33264. }
  33265. this._contrast = value;
  33266. this._updateParameters();
  33267. },
  33268. enumerable: true,
  33269. configurable: true
  33270. });
  33271. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33272. /**
  33273. * Gets the vignette blend mode allowing different kind of effect.
  33274. */
  33275. get: function () {
  33276. return this._vignetteBlendMode;
  33277. },
  33278. /**
  33279. * Sets the vignette blend mode allowing different kind of effect.
  33280. */
  33281. set: function (value) {
  33282. if (this._vignetteBlendMode === value) {
  33283. return;
  33284. }
  33285. this._vignetteBlendMode = value;
  33286. this._updateParameters();
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33292. /**
  33293. * Gets wether the vignette effect is enabled.
  33294. */
  33295. get: function () {
  33296. return this._vignetteEnabled;
  33297. },
  33298. /**
  33299. * Sets wether the vignette effect is enabled.
  33300. */
  33301. set: function (value) {
  33302. if (this._vignetteEnabled === value) {
  33303. return;
  33304. }
  33305. this._vignetteEnabled = value;
  33306. this._updateParameters();
  33307. },
  33308. enumerable: true,
  33309. configurable: true
  33310. });
  33311. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33312. /**
  33313. * Gets wether the image processing is applied through a post process or not.
  33314. */
  33315. get: function () {
  33316. return this._applyByPostProcess;
  33317. },
  33318. /**
  33319. * Sets wether the image processing is applied through a post process or not.
  33320. */
  33321. set: function (value) {
  33322. if (this._applyByPostProcess === value) {
  33323. return;
  33324. }
  33325. this._applyByPostProcess = value;
  33326. this._updateParameters();
  33327. },
  33328. enumerable: true,
  33329. configurable: true
  33330. });
  33331. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33332. /**
  33333. * Gets wether the image processing is enabled or not.
  33334. */
  33335. get: function () {
  33336. return this._isEnabled;
  33337. },
  33338. /**
  33339. * Sets wether the image processing is enabled or not.
  33340. */
  33341. set: function (value) {
  33342. if (this._isEnabled === value) {
  33343. return;
  33344. }
  33345. this._isEnabled = value;
  33346. this._updateParameters();
  33347. },
  33348. enumerable: true,
  33349. configurable: true
  33350. });
  33351. /**
  33352. * Method called each time the image processing information changes requires to recompile the effect.
  33353. */
  33354. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33355. this.onUpdateParameters.notifyObservers(this);
  33356. };
  33357. ImageProcessingConfiguration.prototype.getClassName = function () {
  33358. return "ImageProcessingConfiguration";
  33359. };
  33360. /**
  33361. * Prepare the list of uniforms associated with the Image Processing effects.
  33362. * @param uniformsList The list of uniforms used in the effect
  33363. * @param defines the list of defines currently in use
  33364. */
  33365. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33366. if (defines.EXPOSURE) {
  33367. uniforms.push("exposureLinear");
  33368. }
  33369. if (defines.CONTRAST) {
  33370. uniforms.push("contrast");
  33371. }
  33372. if (defines.COLORGRADING) {
  33373. uniforms.push("colorTransformSettings");
  33374. }
  33375. if (defines.VIGNETTE) {
  33376. uniforms.push("vInverseScreenSize");
  33377. uniforms.push("vignetteSettings1");
  33378. uniforms.push("vignetteSettings2");
  33379. }
  33380. if (defines.COLORCURVES) {
  33381. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33382. }
  33383. };
  33384. /**
  33385. * Prepare the list of samplers associated with the Image Processing effects.
  33386. * @param uniformsList The list of uniforms used in the effect
  33387. * @param defines the list of defines currently in use
  33388. */
  33389. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33390. if (defines.COLORGRADING) {
  33391. samplersList.push("txColorTransform");
  33392. }
  33393. };
  33394. /**
  33395. * Prepare the list of defines associated to the shader.
  33396. * @param defines the list of defines to complete
  33397. */
  33398. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33399. if (forPostProcess === void 0) { forPostProcess = false; }
  33400. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33401. defines.VIGNETTE = false;
  33402. defines.TONEMAPPING = false;
  33403. defines.CONTRAST = false;
  33404. defines.EXPOSURE = false;
  33405. defines.COLORCURVES = false;
  33406. defines.COLORGRADING = false;
  33407. defines.COLORGRADING3D = false;
  33408. defines.IMAGEPROCESSING = false;
  33409. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33410. return;
  33411. }
  33412. defines.VIGNETTE = this.vignetteEnabled;
  33413. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33414. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33415. defines.TONEMAPPING = this.toneMappingEnabled;
  33416. defines.CONTRAST = (this.contrast !== 1.0);
  33417. defines.EXPOSURE = (this.exposure !== 1.0);
  33418. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33419. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33420. if (defines.COLORGRADING) {
  33421. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33422. }
  33423. else {
  33424. defines.COLORGRADING3D = false;
  33425. }
  33426. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33427. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33428. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33429. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33430. };
  33431. /**
  33432. * Returns true if all the image processing information are ready.
  33433. */
  33434. ImageProcessingConfiguration.prototype.isReady = function () {
  33435. // Color Grading texure can not be none blocking.
  33436. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33437. };
  33438. /**
  33439. * Binds the image processing to the shader.
  33440. * @param effect The effect to bind to
  33441. */
  33442. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33443. if (aspectRatio === void 0) { aspectRatio = 1; }
  33444. // Color Curves
  33445. if (this._colorCurvesEnabled && this.colorCurves) {
  33446. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33447. }
  33448. // Vignette
  33449. if (this._vignetteEnabled) {
  33450. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33451. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33452. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33453. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33454. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33455. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33456. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33457. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33458. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33459. var vignettePower = -2.0 * this.vignetteWeight;
  33460. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33461. }
  33462. // Exposure
  33463. effect.setFloat("exposureLinear", this.exposure);
  33464. // Contrast
  33465. effect.setFloat("contrast", this.contrast);
  33466. // Color transform settings
  33467. if (this.colorGradingTexture) {
  33468. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33469. var textureSize = this.colorGradingTexture.getSize().height;
  33470. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33471. 0.5 / textureSize, // textureOffset
  33472. textureSize, // textureSize
  33473. this.colorGradingTexture.level // weight
  33474. );
  33475. }
  33476. };
  33477. /**
  33478. * Clones the current image processing instance.
  33479. * @return The cloned image processing
  33480. */
  33481. ImageProcessingConfiguration.prototype.clone = function () {
  33482. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33483. };
  33484. /**
  33485. * Serializes the current image processing instance to a json representation.
  33486. * @return a JSON representation
  33487. */
  33488. ImageProcessingConfiguration.prototype.serialize = function () {
  33489. return BABYLON.SerializationHelper.Serialize(this);
  33490. };
  33491. /**
  33492. * Parses the image processing from a json representation.
  33493. * @param source the JSON source to parse
  33494. * @return The parsed image processing
  33495. */
  33496. ImageProcessingConfiguration.Parse = function (source) {
  33497. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33498. };
  33499. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33500. /**
  33501. * Used to apply the vignette as a mix with the pixel color.
  33502. */
  33503. get: function () {
  33504. return this._VIGNETTEMODE_MULTIPLY;
  33505. },
  33506. enumerable: true,
  33507. configurable: true
  33508. });
  33509. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33510. /**
  33511. * Used to apply the vignette as a replacement of the pixel color.
  33512. */
  33513. get: function () {
  33514. return this._VIGNETTEMODE_OPAQUE;
  33515. },
  33516. enumerable: true,
  33517. configurable: true
  33518. });
  33519. // Static constants associated to the image processing.
  33520. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33521. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33522. __decorate([
  33523. BABYLON.serializeAsColorCurves()
  33524. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33525. __decorate([
  33526. BABYLON.serialize()
  33527. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33528. __decorate([
  33529. BABYLON.serializeAsTexture()
  33530. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33531. __decorate([
  33532. BABYLON.serialize()
  33533. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33534. __decorate([
  33535. BABYLON.serialize()
  33536. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33537. __decorate([
  33538. BABYLON.serialize()
  33539. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33540. __decorate([
  33541. BABYLON.serialize()
  33542. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33543. __decorate([
  33544. BABYLON.serialize()
  33545. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33546. __decorate([
  33547. BABYLON.serialize()
  33548. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33549. __decorate([
  33550. BABYLON.serialize()
  33551. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33552. __decorate([
  33553. BABYLON.serialize()
  33554. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33555. __decorate([
  33556. BABYLON.serialize()
  33557. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33558. __decorate([
  33559. BABYLON.serialize()
  33560. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33561. __decorate([
  33562. BABYLON.serializeAsColor4()
  33563. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33564. __decorate([
  33565. BABYLON.serialize()
  33566. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33567. __decorate([
  33568. BABYLON.serialize()
  33569. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33570. __decorate([
  33571. BABYLON.serialize()
  33572. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33573. __decorate([
  33574. BABYLON.serialize()
  33575. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33576. __decorate([
  33577. BABYLON.serialize()
  33578. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33579. return ImageProcessingConfiguration;
  33580. }());
  33581. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33582. })(BABYLON || (BABYLON = {}));
  33583. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33584. var BABYLON;
  33585. (function (BABYLON) {
  33586. /**
  33587. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33588. * It can help converting any input color in a desired output one. This can then be used to create effects
  33589. * from sepia, black and white to sixties or futuristic rendering...
  33590. *
  33591. * The only supported format is currently 3dl.
  33592. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33593. */
  33594. var ColorGradingTexture = /** @class */ (function (_super) {
  33595. __extends(ColorGradingTexture, _super);
  33596. /**
  33597. * Instantiates a ColorGradingTexture from the following parameters.
  33598. *
  33599. * @param url The location of the color gradind data (currently only supporting 3dl)
  33600. * @param scene The scene the texture will be used in
  33601. */
  33602. function ColorGradingTexture(url, scene) {
  33603. var _this = _super.call(this, scene) || this;
  33604. if (!url) {
  33605. return _this;
  33606. }
  33607. _this._engine = scene.getEngine();
  33608. _this._textureMatrix = BABYLON.Matrix.Identity();
  33609. _this.name = url;
  33610. _this.url = url;
  33611. _this.hasAlpha = false;
  33612. _this.isCube = false;
  33613. _this.is3D = _this._engine.webGLVersion > 1;
  33614. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33615. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33616. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33617. _this.anisotropicFilteringLevel = 1;
  33618. _this._texture = _this._getFromCache(url, true);
  33619. if (!_this._texture) {
  33620. if (!scene.useDelayedTextureLoading) {
  33621. _this.loadTexture();
  33622. }
  33623. else {
  33624. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33625. }
  33626. }
  33627. return _this;
  33628. }
  33629. /**
  33630. * Returns the texture matrix used in most of the material.
  33631. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33632. */
  33633. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33634. return this._textureMatrix;
  33635. };
  33636. /**
  33637. * Occurs when the file being loaded is a .3dl LUT file.
  33638. */
  33639. ColorGradingTexture.prototype.load3dlTexture = function () {
  33640. var engine = this._engine;
  33641. var texture;
  33642. if (engine.webGLVersion === 1) {
  33643. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33644. }
  33645. else {
  33646. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33647. }
  33648. this._texture = texture;
  33649. var callback = function (text) {
  33650. if (typeof text !== "string") {
  33651. return;
  33652. }
  33653. var data = null;
  33654. var tempData = null;
  33655. var line;
  33656. var lines = text.split('\n');
  33657. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33658. var maxColor = 0;
  33659. for (var i = 0; i < lines.length; i++) {
  33660. line = lines[i];
  33661. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33662. continue;
  33663. if (line.indexOf('#') === 0)
  33664. continue;
  33665. var words = line.split(" ");
  33666. if (size === 0) {
  33667. // Number of space + one
  33668. size = words.length;
  33669. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33670. tempData = new Float32Array(size * size * size * 4);
  33671. continue;
  33672. }
  33673. if (size != 0) {
  33674. var r = Math.max(parseInt(words[0]), 0);
  33675. var g = Math.max(parseInt(words[1]), 0);
  33676. var b = Math.max(parseInt(words[2]), 0);
  33677. maxColor = Math.max(r, maxColor);
  33678. maxColor = Math.max(g, maxColor);
  33679. maxColor = Math.max(b, maxColor);
  33680. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33681. if (tempData) {
  33682. tempData[pixelStorageIndex + 0] = r;
  33683. tempData[pixelStorageIndex + 1] = g;
  33684. tempData[pixelStorageIndex + 2] = b;
  33685. }
  33686. pixelIndexSlice++;
  33687. if (pixelIndexSlice % size == 0) {
  33688. pixelIndexH++;
  33689. pixelIndexSlice = 0;
  33690. if (pixelIndexH % size == 0) {
  33691. pixelIndexW++;
  33692. pixelIndexH = 0;
  33693. }
  33694. }
  33695. }
  33696. }
  33697. if (tempData && data) {
  33698. for (var i = 0; i < tempData.length; i++) {
  33699. if (i > 0 && (i + 1) % 4 === 0) {
  33700. data[i] = 255;
  33701. }
  33702. else {
  33703. var value = tempData[i];
  33704. data[i] = (value / maxColor * 255);
  33705. }
  33706. }
  33707. }
  33708. if (texture.is3D) {
  33709. texture.updateSize(size, size, size);
  33710. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33711. }
  33712. else {
  33713. texture.updateSize(size * size, size);
  33714. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33715. }
  33716. };
  33717. var scene = this.getScene();
  33718. if (scene) {
  33719. scene._loadFile(this.url, callback);
  33720. }
  33721. else {
  33722. this._engine._loadFile(this.url, callback);
  33723. }
  33724. return this._texture;
  33725. };
  33726. /**
  33727. * Starts the loading process of the texture.
  33728. */
  33729. ColorGradingTexture.prototype.loadTexture = function () {
  33730. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33731. this.load3dlTexture();
  33732. }
  33733. };
  33734. /**
  33735. * Clones the color gradind texture.
  33736. */
  33737. ColorGradingTexture.prototype.clone = function () {
  33738. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33739. // Base texture
  33740. newTexture.level = this.level;
  33741. return newTexture;
  33742. };
  33743. /**
  33744. * Called during delayed load for textures.
  33745. */
  33746. ColorGradingTexture.prototype.delayLoad = function () {
  33747. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33748. return;
  33749. }
  33750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33751. this._texture = this._getFromCache(this.url, true);
  33752. if (!this._texture) {
  33753. this.loadTexture();
  33754. }
  33755. };
  33756. /**
  33757. * Parses a color grading texture serialized by Babylon.
  33758. * @param parsedTexture The texture information being parsedTexture
  33759. * @param scene The scene to load the texture in
  33760. * @param rootUrl The root url of the data assets to load
  33761. * @return A color gradind texture
  33762. */
  33763. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33764. var texture = null;
  33765. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33766. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33767. texture.name = parsedTexture.name;
  33768. texture.level = parsedTexture.level;
  33769. }
  33770. return texture;
  33771. };
  33772. /**
  33773. * Serializes the LUT texture to json format.
  33774. */
  33775. ColorGradingTexture.prototype.serialize = function () {
  33776. if (!this.name) {
  33777. return null;
  33778. }
  33779. var serializationObject = {};
  33780. serializationObject.name = this.name;
  33781. serializationObject.level = this.level;
  33782. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33783. return serializationObject;
  33784. };
  33785. /**
  33786. * Empty line regex stored for GC.
  33787. */
  33788. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33789. return ColorGradingTexture;
  33790. }(BABYLON.BaseTexture));
  33791. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33792. })(BABYLON || (BABYLON = {}));
  33793. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33794. var BABYLON;
  33795. (function (BABYLON) {
  33796. /**
  33797. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33798. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33799. * 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;
  33800. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33801. */
  33802. var ColorCurves = /** @class */ (function () {
  33803. function ColorCurves() {
  33804. this._dirty = true;
  33805. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33806. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33807. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33808. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33809. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33810. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33811. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33812. this._globalHue = 30;
  33813. this._globalDensity = 0;
  33814. this._globalSaturation = 0;
  33815. this._globalExposure = 0;
  33816. this._highlightsHue = 30;
  33817. this._highlightsDensity = 0;
  33818. this._highlightsSaturation = 0;
  33819. this._highlightsExposure = 0;
  33820. this._midtonesHue = 30;
  33821. this._midtonesDensity = 0;
  33822. this._midtonesSaturation = 0;
  33823. this._midtonesExposure = 0;
  33824. this._shadowsHue = 30;
  33825. this._shadowsDensity = 0;
  33826. this._shadowsSaturation = 0;
  33827. this._shadowsExposure = 0;
  33828. }
  33829. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33830. /**
  33831. * Gets the global Hue value.
  33832. * 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).
  33833. */
  33834. get: function () {
  33835. return this._globalHue;
  33836. },
  33837. /**
  33838. * Sets the global Hue value.
  33839. * 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).
  33840. */
  33841. set: function (value) {
  33842. this._globalHue = value;
  33843. this._dirty = true;
  33844. },
  33845. enumerable: true,
  33846. configurable: true
  33847. });
  33848. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33849. /**
  33850. * Gets the global Density value.
  33851. * 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.
  33852. * Values less than zero provide a filter of opposite hue.
  33853. */
  33854. get: function () {
  33855. return this._globalDensity;
  33856. },
  33857. /**
  33858. * Sets the global Density value.
  33859. * 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.
  33860. * Values less than zero provide a filter of opposite hue.
  33861. */
  33862. set: function (value) {
  33863. this._globalDensity = value;
  33864. this._dirty = true;
  33865. },
  33866. enumerable: true,
  33867. configurable: true
  33868. });
  33869. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33870. /**
  33871. * Gets the global Saturation value.
  33872. * 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.
  33873. */
  33874. get: function () {
  33875. return this._globalSaturation;
  33876. },
  33877. /**
  33878. * Sets the global Saturation value.
  33879. * 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.
  33880. */
  33881. set: function (value) {
  33882. this._globalSaturation = value;
  33883. this._dirty = true;
  33884. },
  33885. enumerable: true,
  33886. configurable: true
  33887. });
  33888. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33889. /**
  33890. * Gets the highlights Hue value.
  33891. * 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).
  33892. */
  33893. get: function () {
  33894. return this._highlightsHue;
  33895. },
  33896. /**
  33897. * Sets the highlights Hue value.
  33898. * 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).
  33899. */
  33900. set: function (value) {
  33901. this._highlightsHue = value;
  33902. this._dirty = true;
  33903. },
  33904. enumerable: true,
  33905. configurable: true
  33906. });
  33907. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33908. /**
  33909. * Gets the highlights Density value.
  33910. * 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.
  33911. * Values less than zero provide a filter of opposite hue.
  33912. */
  33913. get: function () {
  33914. return this._highlightsDensity;
  33915. },
  33916. /**
  33917. * Sets the highlights Density value.
  33918. * 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.
  33919. * Values less than zero provide a filter of opposite hue.
  33920. */
  33921. set: function (value) {
  33922. this._highlightsDensity = value;
  33923. this._dirty = true;
  33924. },
  33925. enumerable: true,
  33926. configurable: true
  33927. });
  33928. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33929. /**
  33930. * Gets the highlights Saturation value.
  33931. * 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.
  33932. */
  33933. get: function () {
  33934. return this._highlightsSaturation;
  33935. },
  33936. /**
  33937. * Sets the highlights Saturation value.
  33938. * 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.
  33939. */
  33940. set: function (value) {
  33941. this._highlightsSaturation = value;
  33942. this._dirty = true;
  33943. },
  33944. enumerable: true,
  33945. configurable: true
  33946. });
  33947. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33948. /**
  33949. * Gets the highlights Exposure value.
  33950. * 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.
  33951. */
  33952. get: function () {
  33953. return this._highlightsExposure;
  33954. },
  33955. /**
  33956. * Sets the highlights Exposure value.
  33957. * 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.
  33958. */
  33959. set: function (value) {
  33960. this._highlightsExposure = value;
  33961. this._dirty = true;
  33962. },
  33963. enumerable: true,
  33964. configurable: true
  33965. });
  33966. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33967. /**
  33968. * Gets the midtones Hue value.
  33969. * 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).
  33970. */
  33971. get: function () {
  33972. return this._midtonesHue;
  33973. },
  33974. /**
  33975. * Sets the midtones Hue value.
  33976. * 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).
  33977. */
  33978. set: function (value) {
  33979. this._midtonesHue = value;
  33980. this._dirty = true;
  33981. },
  33982. enumerable: true,
  33983. configurable: true
  33984. });
  33985. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33986. /**
  33987. * Gets the midtones Density value.
  33988. * 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.
  33989. * Values less than zero provide a filter of opposite hue.
  33990. */
  33991. get: function () {
  33992. return this._midtonesDensity;
  33993. },
  33994. /**
  33995. * Sets the midtones Density value.
  33996. * 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.
  33997. * Values less than zero provide a filter of opposite hue.
  33998. */
  33999. set: function (value) {
  34000. this._midtonesDensity = value;
  34001. this._dirty = true;
  34002. },
  34003. enumerable: true,
  34004. configurable: true
  34005. });
  34006. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34007. /**
  34008. * Gets the midtones Saturation value.
  34009. * 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.
  34010. */
  34011. get: function () {
  34012. return this._midtonesSaturation;
  34013. },
  34014. /**
  34015. * Sets the midtones Saturation value.
  34016. * 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.
  34017. */
  34018. set: function (value) {
  34019. this._midtonesSaturation = value;
  34020. this._dirty = true;
  34021. },
  34022. enumerable: true,
  34023. configurable: true
  34024. });
  34025. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34026. /**
  34027. * Gets the midtones Exposure value.
  34028. * 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.
  34029. */
  34030. get: function () {
  34031. return this._midtonesExposure;
  34032. },
  34033. /**
  34034. * Sets the midtones Exposure value.
  34035. * 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.
  34036. */
  34037. set: function (value) {
  34038. this._midtonesExposure = value;
  34039. this._dirty = true;
  34040. },
  34041. enumerable: true,
  34042. configurable: true
  34043. });
  34044. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34045. /**
  34046. * Gets the shadows Hue value.
  34047. * 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).
  34048. */
  34049. get: function () {
  34050. return this._shadowsHue;
  34051. },
  34052. /**
  34053. * Sets the shadows Hue value.
  34054. * 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).
  34055. */
  34056. set: function (value) {
  34057. this._shadowsHue = value;
  34058. this._dirty = true;
  34059. },
  34060. enumerable: true,
  34061. configurable: true
  34062. });
  34063. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34064. /**
  34065. * Gets the shadows Density value.
  34066. * 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.
  34067. * Values less than zero provide a filter of opposite hue.
  34068. */
  34069. get: function () {
  34070. return this._shadowsDensity;
  34071. },
  34072. /**
  34073. * Sets the shadows Density value.
  34074. * 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.
  34075. * Values less than zero provide a filter of opposite hue.
  34076. */
  34077. set: function (value) {
  34078. this._shadowsDensity = value;
  34079. this._dirty = true;
  34080. },
  34081. enumerable: true,
  34082. configurable: true
  34083. });
  34084. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34085. /**
  34086. * Gets the shadows Saturation value.
  34087. * 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.
  34088. */
  34089. get: function () {
  34090. return this._shadowsSaturation;
  34091. },
  34092. /**
  34093. * Sets the shadows Saturation value.
  34094. * 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.
  34095. */
  34096. set: function (value) {
  34097. this._shadowsSaturation = value;
  34098. this._dirty = true;
  34099. },
  34100. enumerable: true,
  34101. configurable: true
  34102. });
  34103. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34104. /**
  34105. * Gets the shadows Exposure value.
  34106. * 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.
  34107. */
  34108. get: function () {
  34109. return this._shadowsExposure;
  34110. },
  34111. /**
  34112. * Sets the shadows Exposure value.
  34113. * 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.
  34114. */
  34115. set: function (value) {
  34116. this._shadowsExposure = value;
  34117. this._dirty = true;
  34118. },
  34119. enumerable: true,
  34120. configurable: true
  34121. });
  34122. ColorCurves.prototype.getClassName = function () {
  34123. return "ColorCurves";
  34124. };
  34125. /**
  34126. * Binds the color curves to the shader.
  34127. * @param colorCurves The color curve to bind
  34128. * @param effect The effect to bind to
  34129. */
  34130. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34131. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34132. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34133. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34134. if (colorCurves._dirty) {
  34135. colorCurves._dirty = false;
  34136. // Fill in global info.
  34137. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34138. // Compute highlights info.
  34139. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34140. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34141. // Compute midtones info.
  34142. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34143. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34144. // Compute shadows info.
  34145. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34146. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34147. // Compute deltas (neutral is midtones).
  34148. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34149. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34150. }
  34151. if (effect) {
  34152. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34153. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34154. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34155. }
  34156. };
  34157. /**
  34158. * Prepare the list of uniforms associated with the ColorCurves effects.
  34159. * @param uniformsList The list of uniforms used in the effect
  34160. */
  34161. ColorCurves.PrepareUniforms = function (uniformsList) {
  34162. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34163. };
  34164. /**
  34165. * Returns color grading data based on a hue, density, saturation and exposure value.
  34166. * @param filterHue The hue of the color filter.
  34167. * @param filterDensity The density of the color filter.
  34168. * @param saturation The saturation.
  34169. * @param exposure The exposure.
  34170. * @param result The result data container.
  34171. */
  34172. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34173. if (hue == null) {
  34174. return;
  34175. }
  34176. hue = ColorCurves.clamp(hue, 0, 360);
  34177. density = ColorCurves.clamp(density, -100, 100);
  34178. saturation = ColorCurves.clamp(saturation, -100, 100);
  34179. exposure = ColorCurves.clamp(exposure, -100, 100);
  34180. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34181. // so that the maximum filter density is only 50% control. This provides fine control
  34182. // for small values and reasonable range.
  34183. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34184. density *= 0.5;
  34185. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34186. if (density < 0) {
  34187. density *= -1;
  34188. hue = (hue + 180) % 360;
  34189. }
  34190. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34191. result.scaleToRef(2, result);
  34192. result.a = 1 + 0.01 * saturation;
  34193. };
  34194. /**
  34195. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34196. * @param value The input slider value in range [-100,100].
  34197. * @returns Adjusted value.
  34198. */
  34199. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34200. value /= 100;
  34201. var x = Math.abs(value);
  34202. x = Math.pow(x, 2);
  34203. if (value < 0) {
  34204. x *= -1;
  34205. }
  34206. x *= 100;
  34207. return x;
  34208. };
  34209. /**
  34210. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34211. * @param hue The hue (H) input.
  34212. * @param saturation The saturation (S) input.
  34213. * @param brightness The brightness (B) input.
  34214. * @result An RGBA color represented as Vector4.
  34215. */
  34216. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34217. var h = ColorCurves.clamp(hue, 0, 360);
  34218. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34219. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34220. if (s === 0) {
  34221. result.r = v;
  34222. result.g = v;
  34223. result.b = v;
  34224. }
  34225. else {
  34226. // sector 0 to 5
  34227. h /= 60;
  34228. var i = Math.floor(h);
  34229. // fractional part of h
  34230. var f = h - i;
  34231. var p = v * (1 - s);
  34232. var q = v * (1 - s * f);
  34233. var t = v * (1 - s * (1 - f));
  34234. switch (i) {
  34235. case 0:
  34236. result.r = v;
  34237. result.g = t;
  34238. result.b = p;
  34239. break;
  34240. case 1:
  34241. result.r = q;
  34242. result.g = v;
  34243. result.b = p;
  34244. break;
  34245. case 2:
  34246. result.r = p;
  34247. result.g = v;
  34248. result.b = t;
  34249. break;
  34250. case 3:
  34251. result.r = p;
  34252. result.g = q;
  34253. result.b = v;
  34254. break;
  34255. case 4:
  34256. result.r = t;
  34257. result.g = p;
  34258. result.b = v;
  34259. break;
  34260. default:// case 5:
  34261. result.r = v;
  34262. result.g = p;
  34263. result.b = q;
  34264. break;
  34265. }
  34266. }
  34267. result.a = 1;
  34268. };
  34269. /**
  34270. * Returns a value clamped between min and max
  34271. * @param value The value to clamp
  34272. * @param min The minimum of value
  34273. * @param max The maximum of value
  34274. * @returns The clamped value.
  34275. */
  34276. ColorCurves.clamp = function (value, min, max) {
  34277. return Math.min(Math.max(value, min), max);
  34278. };
  34279. /**
  34280. * Clones the current color curve instance.
  34281. * @return The cloned curves
  34282. */
  34283. ColorCurves.prototype.clone = function () {
  34284. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34285. };
  34286. /**
  34287. * Serializes the current color curve instance to a json representation.
  34288. * @return a JSON representation
  34289. */
  34290. ColorCurves.prototype.serialize = function () {
  34291. return BABYLON.SerializationHelper.Serialize(this);
  34292. };
  34293. /**
  34294. * Parses the color curve from a json representation.
  34295. * @param source the JSON source to parse
  34296. * @return The parsed curves
  34297. */
  34298. ColorCurves.Parse = function (source) {
  34299. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34300. };
  34301. __decorate([
  34302. BABYLON.serialize()
  34303. ], ColorCurves.prototype, "_globalHue", void 0);
  34304. __decorate([
  34305. BABYLON.serialize()
  34306. ], ColorCurves.prototype, "_globalDensity", void 0);
  34307. __decorate([
  34308. BABYLON.serialize()
  34309. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34310. __decorate([
  34311. BABYLON.serialize()
  34312. ], ColorCurves.prototype, "_globalExposure", void 0);
  34313. __decorate([
  34314. BABYLON.serialize()
  34315. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34316. __decorate([
  34317. BABYLON.serialize()
  34318. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34319. __decorate([
  34320. BABYLON.serialize()
  34321. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34322. __decorate([
  34323. BABYLON.serialize()
  34324. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34325. __decorate([
  34326. BABYLON.serialize()
  34327. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34328. __decorate([
  34329. BABYLON.serialize()
  34330. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34331. __decorate([
  34332. BABYLON.serialize()
  34333. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34334. __decorate([
  34335. BABYLON.serialize()
  34336. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34337. return ColorCurves;
  34338. }());
  34339. BABYLON.ColorCurves = ColorCurves;
  34340. })(BABYLON || (BABYLON = {}));
  34341. //# sourceMappingURL=babylon.colorCurves.js.map
  34342. //# sourceMappingURL=babylon.behavior.js.map
  34343. var BABYLON;
  34344. (function (BABYLON) {
  34345. var MaterialHelper = /** @class */ (function () {
  34346. function MaterialHelper() {
  34347. }
  34348. MaterialHelper.BindEyePosition = function (effect, scene) {
  34349. if (scene._forcedViewPosition) {
  34350. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34351. return;
  34352. }
  34353. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34354. };
  34355. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34356. defines._needUVs = true;
  34357. defines[key] = true;
  34358. if (texture.getTextureMatrix().isIdentity(true)) {
  34359. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34360. if (texture.coordinatesIndex === 0) {
  34361. defines["MAINUV1"] = true;
  34362. }
  34363. else {
  34364. defines["MAINUV2"] = true;
  34365. }
  34366. }
  34367. else {
  34368. defines[key + "DIRECTUV"] = 0;
  34369. }
  34370. };
  34371. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34372. var matrix = texture.getTextureMatrix();
  34373. if (!matrix.isIdentity(true)) {
  34374. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34375. }
  34376. };
  34377. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34378. if (defines._areMiscDirty) {
  34379. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34380. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34381. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34382. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34383. }
  34384. };
  34385. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34386. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34387. var changed = false;
  34388. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34389. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34390. changed = true;
  34391. }
  34392. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34393. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34394. changed = true;
  34395. }
  34396. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34397. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34398. changed = true;
  34399. }
  34400. if (defines["INSTANCES"] !== useInstances) {
  34401. defines["INSTANCES"] = useInstances;
  34402. changed = true;
  34403. }
  34404. if (changed) {
  34405. defines.markAsUnprocessed();
  34406. }
  34407. };
  34408. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34409. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34410. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34411. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34412. return false;
  34413. }
  34414. defines._normals = defines._needNormals;
  34415. defines._uvs = defines._needUVs;
  34416. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34417. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34418. defines["TANGENT"] = true;
  34419. }
  34420. if (defines._needUVs) {
  34421. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34422. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34423. }
  34424. else {
  34425. defines["UV1"] = false;
  34426. defines["UV2"] = false;
  34427. }
  34428. if (useVertexColor) {
  34429. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34430. defines["VERTEXCOLOR"] = hasVertexColors;
  34431. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34432. }
  34433. if (useBones) {
  34434. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34435. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34436. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34437. }
  34438. else {
  34439. defines["NUM_BONE_INFLUENCERS"] = 0;
  34440. defines["BonesPerMesh"] = 0;
  34441. }
  34442. }
  34443. if (useMorphTargets) {
  34444. var manager = mesh.morphTargetManager;
  34445. if (manager) {
  34446. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34447. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34448. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34449. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34450. }
  34451. else {
  34452. defines["MORPHTARGETS_TANGENT"] = false;
  34453. defines["MORPHTARGETS_NORMAL"] = false;
  34454. defines["MORPHTARGETS"] = false;
  34455. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34456. }
  34457. }
  34458. return true;
  34459. };
  34460. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34461. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34462. if (disableLighting === void 0) { disableLighting = false; }
  34463. if (!defines._areLightsDirty) {
  34464. return defines._needNormals;
  34465. }
  34466. var lightIndex = 0;
  34467. var needNormals = false;
  34468. var needRebuild = false;
  34469. var lightmapMode = false;
  34470. var shadowEnabled = false;
  34471. var specularEnabled = false;
  34472. if (scene.lightsEnabled && !disableLighting) {
  34473. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34474. var light = _a[_i];
  34475. needNormals = true;
  34476. if (defines["LIGHT" + lightIndex] === undefined) {
  34477. needRebuild = true;
  34478. }
  34479. defines["LIGHT" + lightIndex] = true;
  34480. defines["SPOTLIGHT" + lightIndex] = false;
  34481. defines["HEMILIGHT" + lightIndex] = false;
  34482. defines["POINTLIGHT" + lightIndex] = false;
  34483. defines["DIRLIGHT" + lightIndex] = false;
  34484. var type;
  34485. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34486. type = "SPOTLIGHT" + lightIndex;
  34487. }
  34488. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34489. type = "HEMILIGHT" + lightIndex;
  34490. }
  34491. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34492. type = "POINTLIGHT" + lightIndex;
  34493. }
  34494. else {
  34495. type = "DIRLIGHT" + lightIndex;
  34496. }
  34497. defines[type] = true;
  34498. // Specular
  34499. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34500. specularEnabled = true;
  34501. }
  34502. // Shadows
  34503. defines["SHADOW" + lightIndex] = false;
  34504. defines["SHADOWPCF" + lightIndex] = false;
  34505. defines["SHADOWESM" + lightIndex] = false;
  34506. defines["SHADOWCUBE" + lightIndex] = false;
  34507. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34508. var shadowGenerator = light.getShadowGenerator();
  34509. if (shadowGenerator) {
  34510. shadowEnabled = true;
  34511. shadowGenerator.prepareDefines(defines, lightIndex);
  34512. }
  34513. }
  34514. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34515. lightmapMode = true;
  34516. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34517. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34518. }
  34519. else {
  34520. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34521. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34522. }
  34523. lightIndex++;
  34524. if (lightIndex === maxSimultaneousLights)
  34525. break;
  34526. }
  34527. }
  34528. defines["SPECULARTERM"] = specularEnabled;
  34529. defines["SHADOWS"] = shadowEnabled;
  34530. // Resetting all other lights if any
  34531. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34532. if (defines["LIGHT" + index] !== undefined) {
  34533. defines["LIGHT" + index] = false;
  34534. defines["HEMILIGHT" + lightIndex] = false;
  34535. defines["POINTLIGHT" + lightIndex] = false;
  34536. defines["DIRLIGHT" + lightIndex] = false;
  34537. defines["SPOTLIGHT" + lightIndex] = false;
  34538. defines["SHADOW" + lightIndex] = false;
  34539. }
  34540. }
  34541. var caps = scene.getEngine().getCaps();
  34542. if (defines["SHADOWFLOAT"] === undefined) {
  34543. needRebuild = true;
  34544. }
  34545. defines["SHADOWFLOAT"] = shadowEnabled &&
  34546. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34547. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34548. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34549. if (needRebuild) {
  34550. defines.rebuild();
  34551. }
  34552. return needNormals;
  34553. };
  34554. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34555. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34556. var uniformsList;
  34557. var uniformBuffersList = null;
  34558. if (uniformsListOrOptions.uniformsNames) {
  34559. var options = uniformsListOrOptions;
  34560. uniformsList = options.uniformsNames;
  34561. uniformBuffersList = options.uniformBuffersNames;
  34562. samplersList = options.samplers;
  34563. defines = options.defines;
  34564. maxSimultaneousLights = options.maxSimultaneousLights;
  34565. }
  34566. else {
  34567. uniformsList = uniformsListOrOptions;
  34568. if (!samplersList) {
  34569. samplersList = [];
  34570. }
  34571. }
  34572. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34573. if (!defines["LIGHT" + lightIndex]) {
  34574. break;
  34575. }
  34576. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34577. if (uniformBuffersList) {
  34578. uniformBuffersList.push("Light" + lightIndex);
  34579. }
  34580. samplersList.push("shadowSampler" + lightIndex);
  34581. }
  34582. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34583. uniformsList.push("morphTargetInfluences");
  34584. }
  34585. };
  34586. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34587. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34588. if (rank === void 0) { rank = 0; }
  34589. var lightFallbackRank = 0;
  34590. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34591. if (!defines["LIGHT" + lightIndex]) {
  34592. break;
  34593. }
  34594. if (lightIndex > 0) {
  34595. lightFallbackRank = rank + lightIndex;
  34596. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34597. }
  34598. if (!defines["SHADOWS"]) {
  34599. if (defines["SHADOW" + lightIndex]) {
  34600. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34601. }
  34602. if (defines["SHADOWPCF" + lightIndex]) {
  34603. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34604. }
  34605. if (defines["SHADOWESM" + lightIndex]) {
  34606. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34607. }
  34608. }
  34609. }
  34610. return lightFallbackRank++;
  34611. };
  34612. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34613. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34614. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34615. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34616. var manager = mesh.morphTargetManager;
  34617. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34618. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34619. for (var index = 0; index < influencers; index++) {
  34620. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34621. if (normal) {
  34622. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34623. }
  34624. if (tangent) {
  34625. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34626. }
  34627. if (attribs.length > maxAttributesCount) {
  34628. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34629. }
  34630. }
  34631. }
  34632. };
  34633. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34634. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34635. fallbacks.addCPUSkinningFallback(0, mesh);
  34636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34638. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34639. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34640. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34641. }
  34642. }
  34643. };
  34644. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34645. if (defines["INSTANCES"]) {
  34646. attribs.push("world0");
  34647. attribs.push("world1");
  34648. attribs.push("world2");
  34649. attribs.push("world3");
  34650. }
  34651. };
  34652. // Bindings
  34653. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34654. if (light.shadowEnabled && mesh.receiveShadows) {
  34655. var shadowGenerator = light.getShadowGenerator();
  34656. if (shadowGenerator) {
  34657. shadowGenerator.bindShadowLight(lightIndex, effect);
  34658. }
  34659. }
  34660. };
  34661. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34662. light.transferToEffect(effect, lightIndex + "");
  34663. };
  34664. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34665. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34666. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34667. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34668. for (var i = 0; i < len; i++) {
  34669. var light = mesh._lightSources[i];
  34670. var iAsString = i.toString();
  34671. var scaledIntensity = light.getScaledIntensity();
  34672. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34673. MaterialHelper.BindLightProperties(light, effect, i);
  34674. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34675. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34676. if (defines["SPECULARTERM"]) {
  34677. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34678. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34679. }
  34680. // Shadows
  34681. if (scene.shadowsEnabled) {
  34682. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34683. }
  34684. light._uniformBuffer.update();
  34685. }
  34686. };
  34687. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34688. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34689. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34690. effect.setColor3("vFogColor", scene.fogColor);
  34691. }
  34692. };
  34693. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34694. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34695. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34696. if (matrices && effect) {
  34697. effect.setMatrices("mBones", matrices);
  34698. }
  34699. }
  34700. };
  34701. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34702. var manager = abstractMesh.morphTargetManager;
  34703. if (!abstractMesh || !manager) {
  34704. return;
  34705. }
  34706. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34707. };
  34708. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34709. if (defines["LOGARITHMICDEPTH"]) {
  34710. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34711. }
  34712. };
  34713. MaterialHelper.BindClipPlane = function (effect, scene) {
  34714. if (scene.clipPlane) {
  34715. var clipPlane = scene.clipPlane;
  34716. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34717. }
  34718. };
  34719. return MaterialHelper;
  34720. }());
  34721. BABYLON.MaterialHelper = MaterialHelper;
  34722. })(BABYLON || (BABYLON = {}));
  34723. //# sourceMappingURL=babylon.materialHelper.js.map
  34724. var BABYLON;
  34725. (function (BABYLON) {
  34726. var PushMaterial = /** @class */ (function (_super) {
  34727. __extends(PushMaterial, _super);
  34728. function PushMaterial(name, scene) {
  34729. var _this = _super.call(this, name, scene) || this;
  34730. _this.storeEffectOnSubMeshes = true;
  34731. return _this;
  34732. }
  34733. PushMaterial.prototype.getEffect = function () {
  34734. return this._activeEffect;
  34735. };
  34736. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34737. if (!mesh) {
  34738. return false;
  34739. }
  34740. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34741. return true;
  34742. }
  34743. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34744. };
  34745. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34746. this._activeEffect.setMatrix("world", world);
  34747. };
  34748. PushMaterial.prototype.bind = function (world, mesh) {
  34749. if (!mesh) {
  34750. return;
  34751. }
  34752. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34753. };
  34754. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34755. if (effect === void 0) { effect = null; }
  34756. _super.prototype._afterBind.call(this, mesh);
  34757. this.getScene()._cachedEffect = effect;
  34758. };
  34759. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34760. if (visibility === void 0) { visibility = 1; }
  34761. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34762. };
  34763. return PushMaterial;
  34764. }(BABYLON.Material));
  34765. BABYLON.PushMaterial = PushMaterial;
  34766. })(BABYLON || (BABYLON = {}));
  34767. //# sourceMappingURL=babylon.pushMaterial.js.map
  34768. var BABYLON;
  34769. (function (BABYLON) {
  34770. var StandardMaterialDefines = /** @class */ (function (_super) {
  34771. __extends(StandardMaterialDefines, _super);
  34772. function StandardMaterialDefines() {
  34773. var _this = _super.call(this) || this;
  34774. _this.MAINUV1 = false;
  34775. _this.MAINUV2 = false;
  34776. _this.DIFFUSE = false;
  34777. _this.DIFFUSEDIRECTUV = 0;
  34778. _this.AMBIENT = false;
  34779. _this.AMBIENTDIRECTUV = 0;
  34780. _this.OPACITY = false;
  34781. _this.OPACITYDIRECTUV = 0;
  34782. _this.OPACITYRGB = false;
  34783. _this.REFLECTION = false;
  34784. _this.EMISSIVE = false;
  34785. _this.EMISSIVEDIRECTUV = 0;
  34786. _this.SPECULAR = false;
  34787. _this.SPECULARDIRECTUV = 0;
  34788. _this.BUMP = false;
  34789. _this.BUMPDIRECTUV = 0;
  34790. _this.PARALLAX = false;
  34791. _this.PARALLAXOCCLUSION = false;
  34792. _this.SPECULAROVERALPHA = false;
  34793. _this.CLIPPLANE = false;
  34794. _this.ALPHATEST = false;
  34795. _this.DEPTHPREPASS = false;
  34796. _this.ALPHAFROMDIFFUSE = false;
  34797. _this.POINTSIZE = false;
  34798. _this.FOG = false;
  34799. _this.SPECULARTERM = false;
  34800. _this.DIFFUSEFRESNEL = false;
  34801. _this.OPACITYFRESNEL = false;
  34802. _this.REFLECTIONFRESNEL = false;
  34803. _this.REFRACTIONFRESNEL = false;
  34804. _this.EMISSIVEFRESNEL = false;
  34805. _this.FRESNEL = false;
  34806. _this.NORMAL = false;
  34807. _this.UV1 = false;
  34808. _this.UV2 = false;
  34809. _this.VERTEXCOLOR = false;
  34810. _this.VERTEXALPHA = false;
  34811. _this.NUM_BONE_INFLUENCERS = 0;
  34812. _this.BonesPerMesh = 0;
  34813. _this.INSTANCES = false;
  34814. _this.GLOSSINESS = false;
  34815. _this.ROUGHNESS = false;
  34816. _this.EMISSIVEASILLUMINATION = false;
  34817. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34818. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34819. _this.LIGHTMAP = false;
  34820. _this.LIGHTMAPDIRECTUV = 0;
  34821. _this.USELIGHTMAPASSHADOWMAP = false;
  34822. _this.REFLECTIONMAP_3D = false;
  34823. _this.REFLECTIONMAP_SPHERICAL = false;
  34824. _this.REFLECTIONMAP_PLANAR = false;
  34825. _this.REFLECTIONMAP_CUBIC = false;
  34826. _this.REFLECTIONMAP_PROJECTION = false;
  34827. _this.REFLECTIONMAP_SKYBOX = false;
  34828. _this.REFLECTIONMAP_EXPLICIT = false;
  34829. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34830. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34831. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34832. _this.INVERTCUBICMAP = false;
  34833. _this.LOGARITHMICDEPTH = false;
  34834. _this.REFRACTION = false;
  34835. _this.REFRACTIONMAP_3D = false;
  34836. _this.REFLECTIONOVERALPHA = false;
  34837. _this.TWOSIDEDLIGHTING = false;
  34838. _this.SHADOWFLOAT = false;
  34839. _this.MORPHTARGETS = false;
  34840. _this.MORPHTARGETS_NORMAL = false;
  34841. _this.MORPHTARGETS_TANGENT = false;
  34842. _this.NUM_MORPH_INFLUENCERS = 0;
  34843. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34844. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34845. _this.IMAGEPROCESSING = false;
  34846. _this.VIGNETTE = false;
  34847. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34848. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34849. _this.TONEMAPPING = false;
  34850. _this.CONTRAST = false;
  34851. _this.COLORCURVES = false;
  34852. _this.COLORGRADING = false;
  34853. _this.COLORGRADING3D = false;
  34854. _this.SAMPLER3DGREENDEPTH = false;
  34855. _this.SAMPLER3DBGRMAP = false;
  34856. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34857. _this.EXPOSURE = false;
  34858. _this.rebuild();
  34859. return _this;
  34860. }
  34861. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34862. var modes = [
  34863. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34864. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34865. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34866. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34867. ];
  34868. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34869. var mode = modes_1[_i];
  34870. this[mode] = (mode === modeToEnable);
  34871. }
  34872. };
  34873. return StandardMaterialDefines;
  34874. }(BABYLON.MaterialDefines));
  34875. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34876. var StandardMaterial = /** @class */ (function (_super) {
  34877. __extends(StandardMaterial, _super);
  34878. function StandardMaterial(name, scene) {
  34879. var _this = _super.call(this, name, scene) || this;
  34880. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34881. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34882. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34883. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34884. _this.specularPower = 64;
  34885. _this._useAlphaFromDiffuseTexture = false;
  34886. _this._useEmissiveAsIllumination = false;
  34887. _this._linkEmissiveWithDiffuse = false;
  34888. _this._useSpecularOverAlpha = false;
  34889. _this._useReflectionOverAlpha = false;
  34890. _this._disableLighting = false;
  34891. _this._useParallax = false;
  34892. _this._useParallaxOcclusion = false;
  34893. _this.parallaxScaleBias = 0.05;
  34894. _this._roughness = 0;
  34895. _this.indexOfRefraction = 0.98;
  34896. _this.invertRefractionY = true;
  34897. _this._useLightmapAsShadowmap = false;
  34898. _this._useReflectionFresnelFromSpecular = false;
  34899. _this._useGlossinessFromSpecularMapAlpha = false;
  34900. _this._maxSimultaneousLights = 4;
  34901. /**
  34902. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34903. */
  34904. _this._invertNormalMapX = false;
  34905. /**
  34906. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34907. */
  34908. _this._invertNormalMapY = false;
  34909. /**
  34910. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34911. */
  34912. _this._twoSidedLighting = false;
  34913. _this._renderTargets = new BABYLON.SmartArray(16);
  34914. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34915. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34916. // Setup the default processing configuration to the scene.
  34917. _this._attachImageProcessingConfiguration(null);
  34918. _this.getRenderTargetTextures = function () {
  34919. _this._renderTargets.reset();
  34920. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34921. _this._renderTargets.push(_this._reflectionTexture);
  34922. }
  34923. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34924. _this._renderTargets.push(_this._refractionTexture);
  34925. }
  34926. return _this._renderTargets;
  34927. };
  34928. return _this;
  34929. }
  34930. ;
  34931. ;
  34932. ;
  34933. ;
  34934. ;
  34935. ;
  34936. ;
  34937. ;
  34938. ;
  34939. ;
  34940. ;
  34941. ;
  34942. ;
  34943. ;
  34944. ;
  34945. ;
  34946. ;
  34947. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34948. /**
  34949. * Gets the image processing configuration used either in this material.
  34950. */
  34951. get: function () {
  34952. return this._imageProcessingConfiguration;
  34953. },
  34954. /**
  34955. * Sets the Default image processing configuration used either in the this material.
  34956. *
  34957. * If sets to null, the scene one is in use.
  34958. */
  34959. set: function (value) {
  34960. this._attachImageProcessingConfiguration(value);
  34961. // Ensure the effect will be rebuilt.
  34962. this._markAllSubMeshesAsTexturesDirty();
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. /**
  34968. * Attaches a new image processing configuration to the Standard Material.
  34969. * @param configuration
  34970. */
  34971. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34972. var _this = this;
  34973. if (configuration === this._imageProcessingConfiguration) {
  34974. return;
  34975. }
  34976. // Detaches observer.
  34977. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34978. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34979. }
  34980. // Pick the scene configuration if needed.
  34981. if (!configuration) {
  34982. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34983. }
  34984. else {
  34985. this._imageProcessingConfiguration = configuration;
  34986. }
  34987. // Attaches observer.
  34988. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34989. _this._markAllSubMeshesAsImageProcessingDirty();
  34990. });
  34991. };
  34992. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34993. /**
  34994. * Gets wether the color curves effect is enabled.
  34995. */
  34996. get: function () {
  34997. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34998. },
  34999. /**
  35000. * Sets wether the color curves effect is enabled.
  35001. */
  35002. set: function (value) {
  35003. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35004. },
  35005. enumerable: true,
  35006. configurable: true
  35007. });
  35008. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35009. /**
  35010. * Gets wether the color grading effect is enabled.
  35011. */
  35012. get: function () {
  35013. return this.imageProcessingConfiguration.colorGradingEnabled;
  35014. },
  35015. /**
  35016. * Gets wether the color grading effect is enabled.
  35017. */
  35018. set: function (value) {
  35019. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35020. },
  35021. enumerable: true,
  35022. configurable: true
  35023. });
  35024. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35025. /**
  35026. * Gets wether tonemapping is enabled or not.
  35027. */
  35028. get: function () {
  35029. return this._imageProcessingConfiguration.toneMappingEnabled;
  35030. },
  35031. /**
  35032. * Sets wether tonemapping is enabled or not
  35033. */
  35034. set: function (value) {
  35035. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35036. },
  35037. enumerable: true,
  35038. configurable: true
  35039. });
  35040. ;
  35041. ;
  35042. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35043. /**
  35044. * The camera exposure used on this material.
  35045. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35046. * This corresponds to a photographic exposure.
  35047. */
  35048. get: function () {
  35049. return this._imageProcessingConfiguration.exposure;
  35050. },
  35051. /**
  35052. * The camera exposure used on this material.
  35053. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35054. * This corresponds to a photographic exposure.
  35055. */
  35056. set: function (value) {
  35057. this._imageProcessingConfiguration.exposure = value;
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. ;
  35063. ;
  35064. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35065. /**
  35066. * Gets The camera contrast used on this material.
  35067. */
  35068. get: function () {
  35069. return this._imageProcessingConfiguration.contrast;
  35070. },
  35071. /**
  35072. * Sets The camera contrast used on this material.
  35073. */
  35074. set: function (value) {
  35075. this._imageProcessingConfiguration.contrast = value;
  35076. },
  35077. enumerable: true,
  35078. configurable: true
  35079. });
  35080. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35081. /**
  35082. * Gets the Color Grading 2D Lookup Texture.
  35083. */
  35084. get: function () {
  35085. return this._imageProcessingConfiguration.colorGradingTexture;
  35086. },
  35087. /**
  35088. * Sets the Color Grading 2D Lookup Texture.
  35089. */
  35090. set: function (value) {
  35091. this._imageProcessingConfiguration.colorGradingTexture = value;
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35097. /**
  35098. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35099. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35100. * 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;
  35101. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35102. */
  35103. get: function () {
  35104. return this._imageProcessingConfiguration.colorCurves;
  35105. },
  35106. /**
  35107. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35108. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35109. * 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;
  35110. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35111. */
  35112. set: function (value) {
  35113. this._imageProcessingConfiguration.colorCurves = value;
  35114. },
  35115. enumerable: true,
  35116. configurable: true
  35117. });
  35118. StandardMaterial.prototype.getClassName = function () {
  35119. return "StandardMaterial";
  35120. };
  35121. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35122. get: function () {
  35123. return this._useLogarithmicDepth;
  35124. },
  35125. set: function (value) {
  35126. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35127. this._markAllSubMeshesAsMiscDirty();
  35128. },
  35129. enumerable: true,
  35130. configurable: true
  35131. });
  35132. StandardMaterial.prototype.needAlphaBlending = function () {
  35133. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35134. };
  35135. StandardMaterial.prototype.needAlphaTesting = function () {
  35136. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35137. };
  35138. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35139. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35140. };
  35141. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35142. return this._diffuseTexture;
  35143. };
  35144. /**
  35145. * Child classes can use it to update shaders
  35146. */
  35147. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35148. if (useInstances === void 0) { useInstances = false; }
  35149. if (subMesh.effect && this.isFrozen) {
  35150. if (this._wasPreviouslyReady && subMesh.effect) {
  35151. return true;
  35152. }
  35153. }
  35154. if (!subMesh._materialDefines) {
  35155. subMesh._materialDefines = new StandardMaterialDefines();
  35156. }
  35157. var scene = this.getScene();
  35158. var defines = subMesh._materialDefines;
  35159. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35160. if (defines._renderId === scene.getRenderId()) {
  35161. return true;
  35162. }
  35163. }
  35164. var engine = scene.getEngine();
  35165. // Lights
  35166. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35167. // Textures
  35168. if (defines._areTexturesDirty) {
  35169. defines._needUVs = false;
  35170. defines.MAINUV1 = false;
  35171. defines.MAINUV2 = false;
  35172. if (scene.texturesEnabled) {
  35173. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35174. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35175. return false;
  35176. }
  35177. else {
  35178. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35179. }
  35180. }
  35181. else {
  35182. defines.DIFFUSE = false;
  35183. }
  35184. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35185. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35186. return false;
  35187. }
  35188. else {
  35189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35190. }
  35191. }
  35192. else {
  35193. defines.AMBIENT = false;
  35194. }
  35195. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35196. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35197. return false;
  35198. }
  35199. else {
  35200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35201. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35202. }
  35203. }
  35204. else {
  35205. defines.OPACITY = false;
  35206. }
  35207. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35208. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35209. return false;
  35210. }
  35211. else {
  35212. defines._needNormals = true;
  35213. defines.REFLECTION = true;
  35214. defines.ROUGHNESS = (this._roughness > 0);
  35215. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35216. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35217. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35218. switch (this._reflectionTexture.coordinatesMode) {
  35219. case BABYLON.Texture.CUBIC_MODE:
  35220. case BABYLON.Texture.INVCUBIC_MODE:
  35221. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35222. break;
  35223. case BABYLON.Texture.EXPLICIT_MODE:
  35224. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35225. break;
  35226. case BABYLON.Texture.PLANAR_MODE:
  35227. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35228. break;
  35229. case BABYLON.Texture.PROJECTION_MODE:
  35230. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35231. break;
  35232. case BABYLON.Texture.SKYBOX_MODE:
  35233. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35234. break;
  35235. case BABYLON.Texture.SPHERICAL_MODE:
  35236. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35237. break;
  35238. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35239. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35240. break;
  35241. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35242. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35243. break;
  35244. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35245. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35246. break;
  35247. }
  35248. }
  35249. }
  35250. else {
  35251. defines.REFLECTION = false;
  35252. }
  35253. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35254. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35255. return false;
  35256. }
  35257. else {
  35258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35259. }
  35260. }
  35261. else {
  35262. defines.EMISSIVE = false;
  35263. }
  35264. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35265. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35266. return false;
  35267. }
  35268. else {
  35269. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35270. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35271. }
  35272. }
  35273. else {
  35274. defines.LIGHTMAP = false;
  35275. }
  35276. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35277. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35278. return false;
  35279. }
  35280. else {
  35281. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35282. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35283. }
  35284. }
  35285. else {
  35286. defines.SPECULAR = false;
  35287. }
  35288. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35289. // Bump texure can not be not blocking.
  35290. if (!this._bumpTexture.isReady()) {
  35291. return false;
  35292. }
  35293. else {
  35294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35295. defines.PARALLAX = this._useParallax;
  35296. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35297. }
  35298. }
  35299. else {
  35300. defines.BUMP = false;
  35301. }
  35302. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35303. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35304. return false;
  35305. }
  35306. else {
  35307. defines._needUVs = true;
  35308. defines.REFRACTION = true;
  35309. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35310. }
  35311. }
  35312. else {
  35313. defines.REFRACTION = false;
  35314. }
  35315. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35316. }
  35317. else {
  35318. defines.DIFFUSE = false;
  35319. defines.AMBIENT = false;
  35320. defines.OPACITY = false;
  35321. defines.REFLECTION = false;
  35322. defines.EMISSIVE = false;
  35323. defines.LIGHTMAP = false;
  35324. defines.BUMP = false;
  35325. defines.REFRACTION = false;
  35326. }
  35327. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35328. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35329. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35330. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35331. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35332. }
  35333. if (defines._areImageProcessingDirty) {
  35334. if (!this._imageProcessingConfiguration.isReady()) {
  35335. return false;
  35336. }
  35337. this._imageProcessingConfiguration.prepareDefines(defines);
  35338. }
  35339. if (defines._areFresnelDirty) {
  35340. if (StandardMaterial.FresnelEnabled) {
  35341. // Fresnel
  35342. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35343. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35344. this._reflectionFresnelParameters) {
  35345. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35346. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35347. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35348. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35349. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35350. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35351. defines._needNormals = true;
  35352. defines.FRESNEL = true;
  35353. }
  35354. }
  35355. else {
  35356. defines.FRESNEL = false;
  35357. }
  35358. }
  35359. // Misc.
  35360. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35361. // Attribs
  35362. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35363. // Values that need to be evaluated on every frame
  35364. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35365. // Get correct effect
  35366. if (defines.isDirty) {
  35367. defines.markAsProcessed();
  35368. scene.resetCachedMaterial();
  35369. // Fallbacks
  35370. var fallbacks = new BABYLON.EffectFallbacks();
  35371. if (defines.REFLECTION) {
  35372. fallbacks.addFallback(0, "REFLECTION");
  35373. }
  35374. if (defines.SPECULAR) {
  35375. fallbacks.addFallback(0, "SPECULAR");
  35376. }
  35377. if (defines.BUMP) {
  35378. fallbacks.addFallback(0, "BUMP");
  35379. }
  35380. if (defines.PARALLAX) {
  35381. fallbacks.addFallback(1, "PARALLAX");
  35382. }
  35383. if (defines.PARALLAXOCCLUSION) {
  35384. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35385. }
  35386. if (defines.SPECULAROVERALPHA) {
  35387. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35388. }
  35389. if (defines.FOG) {
  35390. fallbacks.addFallback(1, "FOG");
  35391. }
  35392. if (defines.POINTSIZE) {
  35393. fallbacks.addFallback(0, "POINTSIZE");
  35394. }
  35395. if (defines.LOGARITHMICDEPTH) {
  35396. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35397. }
  35398. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35399. if (defines.SPECULARTERM) {
  35400. fallbacks.addFallback(0, "SPECULARTERM");
  35401. }
  35402. if (defines.DIFFUSEFRESNEL) {
  35403. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35404. }
  35405. if (defines.OPACITYFRESNEL) {
  35406. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35407. }
  35408. if (defines.REFLECTIONFRESNEL) {
  35409. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35410. }
  35411. if (defines.EMISSIVEFRESNEL) {
  35412. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35413. }
  35414. if (defines.FRESNEL) {
  35415. fallbacks.addFallback(4, "FRESNEL");
  35416. }
  35417. //Attributes
  35418. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35419. if (defines.NORMAL) {
  35420. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35421. }
  35422. if (defines.UV1) {
  35423. attribs.push(BABYLON.VertexBuffer.UVKind);
  35424. }
  35425. if (defines.UV2) {
  35426. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35427. }
  35428. if (defines.VERTEXCOLOR) {
  35429. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35430. }
  35431. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35432. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35433. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35434. var shaderName = "default";
  35435. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35436. "vFogInfos", "vFogColor", "pointSize",
  35437. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35438. "mBones",
  35439. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35440. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35441. "logarithmicDepthConstant", "vTangentSpaceParams"
  35442. ];
  35443. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35444. var uniformBuffers = ["Material", "Scene"];
  35445. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35446. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35447. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35448. uniformsNames: uniforms,
  35449. uniformBuffersNames: uniformBuffers,
  35450. samplers: samplers,
  35451. defines: defines,
  35452. maxSimultaneousLights: this._maxSimultaneousLights
  35453. });
  35454. if (this.customShaderNameResolve) {
  35455. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35456. }
  35457. var join = defines.toString();
  35458. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35459. attributes: attribs,
  35460. uniformsNames: uniforms,
  35461. uniformBuffersNames: uniformBuffers,
  35462. samplers: samplers,
  35463. defines: join,
  35464. fallbacks: fallbacks,
  35465. onCompiled: this.onCompiled,
  35466. onError: this.onError,
  35467. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35468. }, engine), defines);
  35469. this.buildUniformLayout();
  35470. }
  35471. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35472. return false;
  35473. }
  35474. defines._renderId = scene.getRenderId();
  35475. this._wasPreviouslyReady = true;
  35476. return true;
  35477. };
  35478. StandardMaterial.prototype.buildUniformLayout = function () {
  35479. // Order is important !
  35480. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35481. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35482. this._uniformBuffer.addUniform("opacityParts", 4);
  35483. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35484. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35485. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35486. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35487. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35488. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35489. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35490. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35491. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35492. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35493. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35494. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35495. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35496. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35497. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35498. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35499. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35500. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35501. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35502. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35503. this._uniformBuffer.addUniform("specularMatrix", 16);
  35504. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35505. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35506. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35507. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35508. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35509. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35510. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35511. this._uniformBuffer.addUniform("pointSize", 1);
  35512. this._uniformBuffer.create();
  35513. };
  35514. StandardMaterial.prototype.unbind = function () {
  35515. if (this._activeEffect) {
  35516. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35517. this._activeEffect.setTexture("reflection2DSampler", null);
  35518. }
  35519. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35520. this._activeEffect.setTexture("refraction2DSampler", null);
  35521. }
  35522. }
  35523. _super.prototype.unbind.call(this);
  35524. };
  35525. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35526. var scene = this.getScene();
  35527. var defines = subMesh._materialDefines;
  35528. if (!defines) {
  35529. return;
  35530. }
  35531. var effect = subMesh.effect;
  35532. if (!effect) {
  35533. return;
  35534. }
  35535. this._activeEffect = effect;
  35536. // Matrices
  35537. this.bindOnlyWorldMatrix(world);
  35538. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35539. // Bones
  35540. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35541. if (mustRebind) {
  35542. this._uniformBuffer.bindToEffect(effect, "Material");
  35543. this.bindViewProjection(effect);
  35544. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35545. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35546. // Fresnel
  35547. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35548. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35549. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35550. }
  35551. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35552. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35553. }
  35554. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35555. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35556. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35557. }
  35558. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35559. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35560. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35561. }
  35562. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35563. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35564. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35565. }
  35566. }
  35567. // Textures
  35568. if (scene.texturesEnabled) {
  35569. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35570. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35571. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35572. }
  35573. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35574. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35575. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35576. }
  35577. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35578. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35579. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35580. }
  35581. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35582. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35583. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35584. }
  35585. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35586. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35587. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35588. }
  35589. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35590. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35591. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35592. }
  35593. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35594. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35595. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35596. }
  35597. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35598. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35599. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35600. if (scene._mirroredCameraPosition) {
  35601. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35602. }
  35603. else {
  35604. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35605. }
  35606. }
  35607. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35608. var depth = 1.0;
  35609. if (!this._refractionTexture.isCube) {
  35610. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35611. if (this._refractionTexture.depth) {
  35612. depth = this._refractionTexture.depth;
  35613. }
  35614. }
  35615. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35616. }
  35617. }
  35618. // Point size
  35619. if (this.pointsCloud) {
  35620. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35621. }
  35622. if (defines.SPECULARTERM) {
  35623. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35624. }
  35625. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35626. // Diffuse
  35627. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35628. }
  35629. // Textures
  35630. if (scene.texturesEnabled) {
  35631. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35632. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35633. }
  35634. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35635. effect.setTexture("ambientSampler", this._ambientTexture);
  35636. }
  35637. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35638. effect.setTexture("opacitySampler", this._opacityTexture);
  35639. }
  35640. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35641. if (this._reflectionTexture.isCube) {
  35642. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35643. }
  35644. else {
  35645. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35646. }
  35647. }
  35648. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35649. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35650. }
  35651. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35652. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35653. }
  35654. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35655. effect.setTexture("specularSampler", this._specularTexture);
  35656. }
  35657. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35658. effect.setTexture("bumpSampler", this._bumpTexture);
  35659. }
  35660. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35661. var depth = 1.0;
  35662. if (this._refractionTexture.isCube) {
  35663. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35664. }
  35665. else {
  35666. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35667. }
  35668. }
  35669. }
  35670. // Clip plane
  35671. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35672. // Colors
  35673. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35674. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35675. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35676. }
  35677. if (mustRebind || !this.isFrozen) {
  35678. // Lights
  35679. if (scene.lightsEnabled && !this._disableLighting) {
  35680. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35681. }
  35682. // View
  35683. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35684. this.bindView(effect);
  35685. }
  35686. // Fog
  35687. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35688. // Morph targets
  35689. if (defines.NUM_MORPH_INFLUENCERS) {
  35690. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35691. }
  35692. // Log. depth
  35693. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35694. // image processing
  35695. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35696. this._imageProcessingConfiguration.bind(this._activeEffect);
  35697. }
  35698. }
  35699. this._uniformBuffer.update();
  35700. this._afterBind(mesh, this._activeEffect);
  35701. };
  35702. StandardMaterial.prototype.getAnimatables = function () {
  35703. var results = [];
  35704. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35705. results.push(this._diffuseTexture);
  35706. }
  35707. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35708. results.push(this._ambientTexture);
  35709. }
  35710. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35711. results.push(this._opacityTexture);
  35712. }
  35713. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35714. results.push(this._reflectionTexture);
  35715. }
  35716. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35717. results.push(this._emissiveTexture);
  35718. }
  35719. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35720. results.push(this._specularTexture);
  35721. }
  35722. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35723. results.push(this._bumpTexture);
  35724. }
  35725. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35726. results.push(this._lightmapTexture);
  35727. }
  35728. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35729. results.push(this._refractionTexture);
  35730. }
  35731. return results;
  35732. };
  35733. StandardMaterial.prototype.getActiveTextures = function () {
  35734. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35735. if (this._diffuseTexture) {
  35736. activeTextures.push(this._diffuseTexture);
  35737. }
  35738. if (this._ambientTexture) {
  35739. activeTextures.push(this._ambientTexture);
  35740. }
  35741. if (this._opacityTexture) {
  35742. activeTextures.push(this._opacityTexture);
  35743. }
  35744. if (this._reflectionTexture) {
  35745. activeTextures.push(this._reflectionTexture);
  35746. }
  35747. if (this._emissiveTexture) {
  35748. activeTextures.push(this._emissiveTexture);
  35749. }
  35750. if (this._specularTexture) {
  35751. activeTextures.push(this._specularTexture);
  35752. }
  35753. if (this._bumpTexture) {
  35754. activeTextures.push(this._bumpTexture);
  35755. }
  35756. if (this._lightmapTexture) {
  35757. activeTextures.push(this._lightmapTexture);
  35758. }
  35759. if (this._refractionTexture) {
  35760. activeTextures.push(this._refractionTexture);
  35761. }
  35762. return activeTextures;
  35763. };
  35764. StandardMaterial.prototype.hasTexture = function (texture) {
  35765. if (_super.prototype.hasTexture.call(this, texture)) {
  35766. return true;
  35767. }
  35768. if (this._diffuseTexture === texture) {
  35769. return true;
  35770. }
  35771. if (this._ambientTexture === texture) {
  35772. return true;
  35773. }
  35774. if (this._opacityTexture === texture) {
  35775. return true;
  35776. }
  35777. if (this._reflectionTexture === texture) {
  35778. return true;
  35779. }
  35780. if (this._emissiveTexture === texture) {
  35781. return true;
  35782. }
  35783. if (this._specularTexture === texture) {
  35784. return true;
  35785. }
  35786. if (this._bumpTexture === texture) {
  35787. return true;
  35788. }
  35789. if (this._lightmapTexture === texture) {
  35790. return true;
  35791. }
  35792. if (this._refractionTexture === texture) {
  35793. return true;
  35794. }
  35795. return false;
  35796. };
  35797. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35798. if (forceDisposeTextures) {
  35799. if (this._diffuseTexture) {
  35800. this._diffuseTexture.dispose();
  35801. }
  35802. if (this._ambientTexture) {
  35803. this._ambientTexture.dispose();
  35804. }
  35805. if (this._opacityTexture) {
  35806. this._opacityTexture.dispose();
  35807. }
  35808. if (this._reflectionTexture) {
  35809. this._reflectionTexture.dispose();
  35810. }
  35811. if (this._emissiveTexture) {
  35812. this._emissiveTexture.dispose();
  35813. }
  35814. if (this._specularTexture) {
  35815. this._specularTexture.dispose();
  35816. }
  35817. if (this._bumpTexture) {
  35818. this._bumpTexture.dispose();
  35819. }
  35820. if (this._lightmapTexture) {
  35821. this._lightmapTexture.dispose();
  35822. }
  35823. if (this._refractionTexture) {
  35824. this._refractionTexture.dispose();
  35825. }
  35826. }
  35827. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35828. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35829. }
  35830. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35831. };
  35832. StandardMaterial.prototype.clone = function (name) {
  35833. var _this = this;
  35834. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35835. result.name = name;
  35836. result.id = name;
  35837. return result;
  35838. };
  35839. StandardMaterial.prototype.serialize = function () {
  35840. return BABYLON.SerializationHelper.Serialize(this);
  35841. };
  35842. // Statics
  35843. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35844. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35845. };
  35846. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35847. get: function () {
  35848. return StandardMaterial._DiffuseTextureEnabled;
  35849. },
  35850. set: function (value) {
  35851. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35852. return;
  35853. }
  35854. StandardMaterial._DiffuseTextureEnabled = value;
  35855. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35856. },
  35857. enumerable: true,
  35858. configurable: true
  35859. });
  35860. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35861. get: function () {
  35862. return StandardMaterial._AmbientTextureEnabled;
  35863. },
  35864. set: function (value) {
  35865. if (StandardMaterial._AmbientTextureEnabled === value) {
  35866. return;
  35867. }
  35868. StandardMaterial._AmbientTextureEnabled = value;
  35869. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35870. },
  35871. enumerable: true,
  35872. configurable: true
  35873. });
  35874. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35875. get: function () {
  35876. return StandardMaterial._OpacityTextureEnabled;
  35877. },
  35878. set: function (value) {
  35879. if (StandardMaterial._OpacityTextureEnabled === value) {
  35880. return;
  35881. }
  35882. StandardMaterial._OpacityTextureEnabled = value;
  35883. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35884. },
  35885. enumerable: true,
  35886. configurable: true
  35887. });
  35888. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35889. get: function () {
  35890. return StandardMaterial._ReflectionTextureEnabled;
  35891. },
  35892. set: function (value) {
  35893. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35894. return;
  35895. }
  35896. StandardMaterial._ReflectionTextureEnabled = value;
  35897. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35898. },
  35899. enumerable: true,
  35900. configurable: true
  35901. });
  35902. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35903. get: function () {
  35904. return StandardMaterial._EmissiveTextureEnabled;
  35905. },
  35906. set: function (value) {
  35907. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35908. return;
  35909. }
  35910. StandardMaterial._EmissiveTextureEnabled = value;
  35911. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35912. },
  35913. enumerable: true,
  35914. configurable: true
  35915. });
  35916. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35917. get: function () {
  35918. return StandardMaterial._SpecularTextureEnabled;
  35919. },
  35920. set: function (value) {
  35921. if (StandardMaterial._SpecularTextureEnabled === value) {
  35922. return;
  35923. }
  35924. StandardMaterial._SpecularTextureEnabled = value;
  35925. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35926. },
  35927. enumerable: true,
  35928. configurable: true
  35929. });
  35930. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35931. get: function () {
  35932. return StandardMaterial._BumpTextureEnabled;
  35933. },
  35934. set: function (value) {
  35935. if (StandardMaterial._BumpTextureEnabled === value) {
  35936. return;
  35937. }
  35938. StandardMaterial._BumpTextureEnabled = value;
  35939. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35940. },
  35941. enumerable: true,
  35942. configurable: true
  35943. });
  35944. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35945. get: function () {
  35946. return StandardMaterial._LightmapTextureEnabled;
  35947. },
  35948. set: function (value) {
  35949. if (StandardMaterial._LightmapTextureEnabled === value) {
  35950. return;
  35951. }
  35952. StandardMaterial._LightmapTextureEnabled = value;
  35953. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35954. },
  35955. enumerable: true,
  35956. configurable: true
  35957. });
  35958. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35959. get: function () {
  35960. return StandardMaterial._RefractionTextureEnabled;
  35961. },
  35962. set: function (value) {
  35963. if (StandardMaterial._RefractionTextureEnabled === value) {
  35964. return;
  35965. }
  35966. StandardMaterial._RefractionTextureEnabled = value;
  35967. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35968. },
  35969. enumerable: true,
  35970. configurable: true
  35971. });
  35972. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35973. get: function () {
  35974. return StandardMaterial._ColorGradingTextureEnabled;
  35975. },
  35976. set: function (value) {
  35977. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35978. return;
  35979. }
  35980. StandardMaterial._ColorGradingTextureEnabled = value;
  35981. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35982. },
  35983. enumerable: true,
  35984. configurable: true
  35985. });
  35986. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35987. get: function () {
  35988. return StandardMaterial._FresnelEnabled;
  35989. },
  35990. set: function (value) {
  35991. if (StandardMaterial._FresnelEnabled === value) {
  35992. return;
  35993. }
  35994. StandardMaterial._FresnelEnabled = value;
  35995. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35996. },
  35997. enumerable: true,
  35998. configurable: true
  35999. });
  36000. // Flags used to enable or disable a type of texture for all Standard Materials
  36001. StandardMaterial._DiffuseTextureEnabled = true;
  36002. StandardMaterial._AmbientTextureEnabled = true;
  36003. StandardMaterial._OpacityTextureEnabled = true;
  36004. StandardMaterial._ReflectionTextureEnabled = true;
  36005. StandardMaterial._EmissiveTextureEnabled = true;
  36006. StandardMaterial._SpecularTextureEnabled = true;
  36007. StandardMaterial._BumpTextureEnabled = true;
  36008. StandardMaterial._LightmapTextureEnabled = true;
  36009. StandardMaterial._RefractionTextureEnabled = true;
  36010. StandardMaterial._ColorGradingTextureEnabled = true;
  36011. StandardMaterial._FresnelEnabled = true;
  36012. __decorate([
  36013. BABYLON.serializeAsTexture("diffuseTexture")
  36014. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36015. __decorate([
  36016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36017. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36018. __decorate([
  36019. BABYLON.serializeAsTexture("ambientTexture")
  36020. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36021. __decorate([
  36022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36023. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36024. __decorate([
  36025. BABYLON.serializeAsTexture("opacityTexture")
  36026. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36027. __decorate([
  36028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36029. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36030. __decorate([
  36031. BABYLON.serializeAsTexture("reflectionTexture")
  36032. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36033. __decorate([
  36034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36035. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36036. __decorate([
  36037. BABYLON.serializeAsTexture("emissiveTexture")
  36038. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36039. __decorate([
  36040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36041. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36042. __decorate([
  36043. BABYLON.serializeAsTexture("specularTexture")
  36044. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36045. __decorate([
  36046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36047. ], StandardMaterial.prototype, "specularTexture", void 0);
  36048. __decorate([
  36049. BABYLON.serializeAsTexture("bumpTexture")
  36050. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36051. __decorate([
  36052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36053. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36054. __decorate([
  36055. BABYLON.serializeAsTexture("lightmapTexture")
  36056. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36057. __decorate([
  36058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36059. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36060. __decorate([
  36061. BABYLON.serializeAsTexture("refractionTexture")
  36062. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36063. __decorate([
  36064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36065. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36066. __decorate([
  36067. BABYLON.serializeAsColor3("ambient")
  36068. ], StandardMaterial.prototype, "ambientColor", void 0);
  36069. __decorate([
  36070. BABYLON.serializeAsColor3("diffuse")
  36071. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36072. __decorate([
  36073. BABYLON.serializeAsColor3("specular")
  36074. ], StandardMaterial.prototype, "specularColor", void 0);
  36075. __decorate([
  36076. BABYLON.serializeAsColor3("emissive")
  36077. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36078. __decorate([
  36079. BABYLON.serialize()
  36080. ], StandardMaterial.prototype, "specularPower", void 0);
  36081. __decorate([
  36082. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36083. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36084. __decorate([
  36085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36086. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36087. __decorate([
  36088. BABYLON.serialize("useEmissiveAsIllumination")
  36089. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36090. __decorate([
  36091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36092. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36093. __decorate([
  36094. BABYLON.serialize("linkEmissiveWithDiffuse")
  36095. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36096. __decorate([
  36097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36098. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36099. __decorate([
  36100. BABYLON.serialize("useSpecularOverAlpha")
  36101. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36102. __decorate([
  36103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36104. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36105. __decorate([
  36106. BABYLON.serialize("useReflectionOverAlpha")
  36107. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36108. __decorate([
  36109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36110. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36111. __decorate([
  36112. BABYLON.serialize("disableLighting")
  36113. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36114. __decorate([
  36115. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36116. ], StandardMaterial.prototype, "disableLighting", void 0);
  36117. __decorate([
  36118. BABYLON.serialize("useParallax")
  36119. ], StandardMaterial.prototype, "_useParallax", void 0);
  36120. __decorate([
  36121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36122. ], StandardMaterial.prototype, "useParallax", void 0);
  36123. __decorate([
  36124. BABYLON.serialize("useParallaxOcclusion")
  36125. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36126. __decorate([
  36127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36128. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36129. __decorate([
  36130. BABYLON.serialize()
  36131. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36132. __decorate([
  36133. BABYLON.serialize("roughness")
  36134. ], StandardMaterial.prototype, "_roughness", void 0);
  36135. __decorate([
  36136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36137. ], StandardMaterial.prototype, "roughness", void 0);
  36138. __decorate([
  36139. BABYLON.serialize()
  36140. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36141. __decorate([
  36142. BABYLON.serialize()
  36143. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36144. __decorate([
  36145. BABYLON.serialize("useLightmapAsShadowmap")
  36146. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36147. __decorate([
  36148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36149. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36150. __decorate([
  36151. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36152. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36153. __decorate([
  36154. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36155. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36156. __decorate([
  36157. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36158. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36159. __decorate([
  36160. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36161. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36162. __decorate([
  36163. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36164. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36165. __decorate([
  36166. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36167. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36168. __decorate([
  36169. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36170. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36171. __decorate([
  36172. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36173. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36174. __decorate([
  36175. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36176. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36177. __decorate([
  36178. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36179. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36180. __decorate([
  36181. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36182. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36183. __decorate([
  36184. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36185. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36186. __decorate([
  36187. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36188. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36189. __decorate([
  36190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36191. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36192. __decorate([
  36193. BABYLON.serialize("maxSimultaneousLights")
  36194. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36195. __decorate([
  36196. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36197. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36198. __decorate([
  36199. BABYLON.serialize("invertNormalMapX")
  36200. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36201. __decorate([
  36202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36203. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36204. __decorate([
  36205. BABYLON.serialize("invertNormalMapY")
  36206. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36207. __decorate([
  36208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36209. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36210. __decorate([
  36211. BABYLON.serialize("twoSidedLighting")
  36212. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36213. __decorate([
  36214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36215. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36216. __decorate([
  36217. BABYLON.serialize()
  36218. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36219. return StandardMaterial;
  36220. }(BABYLON.PushMaterial));
  36221. BABYLON.StandardMaterial = StandardMaterial;
  36222. })(BABYLON || (BABYLON = {}));
  36223. //# sourceMappingURL=babylon.standardMaterial.js.map
  36224. (function() {
  36225. globalObject["BABYLON"] = globalObject["BABYLON"] || BABYLON;
  36226. module.exports = BABYLON;
  36227. })();
  36228. }